diff --git a/b2g/chrome/content/shell.js b/b2g/chrome/content/shell.js index 8ee85a21b43a..5e202ed62713 100644 --- a/b2g/chrome/content/shell.js +++ b/b2g/chrome/content/shell.js @@ -11,7 +11,6 @@ Cu.import('resource://gre/modules/AlarmService.jsm'); Cu.import('resource://gre/modules/ActivitiesService.jsm'); Cu.import('resource://gre/modules/PermissionPromptHelper.jsm'); Cu.import('resource://gre/modules/ObjectWrapper.jsm'); -Cu.import('resource://gre/modules/NotificationDB.jsm'); Cu.import('resource://gre/modules/accessibility/AccessFu.jsm'); Cu.import('resource://gre/modules/Payment.jsm'); Cu.import("resource://gre/modules/AppsUtils.jsm"); diff --git a/b2g/installer/package-manifest.in b/b2g/installer/package-manifest.in index b2d884c822cc..ab57076707c8 100644 --- a/b2g/installer/package-manifest.in +++ b/b2g/installer/package-manifest.in @@ -348,8 +348,6 @@ @BINPATH@/components/ContactManager.manifest @BINPATH@/components/PhoneNumberService.js @BINPATH@/components/PhoneNumberService.manifest -@BINPATH@/components/NotificationStorage.js -@BINPATH@/components/NotificationStorage.manifest @BINPATH@/components/PermissionSettings.js @BINPATH@/components/PermissionSettings.manifest @BINPATH@/components/PermissionPromptService.js diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index b511658e62a4..51c6728c7789 100644 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -7,7 +7,6 @@ let Ci = Components.interfaces; let Cu = Components.utils; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/NotificationDB.jsm"); Cu.import("resource:///modules/RecentWindow.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "Task", diff --git a/browser/components/nsBrowserGlue.js b/browser/components/nsBrowserGlue.js index fc28b84c3d95..5127880d15ca 100644 --- a/browser/components/nsBrowserGlue.js +++ b/browser/components/nsBrowserGlue.js @@ -81,8 +81,8 @@ const PREF_PLUGINS_NOTIFYUSER = "plugins.update.notifyUser"; const PREF_PLUGINS_UPDATEURL = "plugins.update.url"; // We try to backup bookmarks at idle times, to avoid doing that at shutdown. -// Number of idle seconds before trying to backup bookmarks. 15 minutes. -const BOOKMARKS_BACKUP_IDLE_TIME = 15 * 60; +// Number of idle seconds before trying to backup bookmarks. 10 minutes. +const BOOKMARKS_BACKUP_IDLE_TIME = 10 * 60; // Minimum interval in milliseconds between backups. const BOOKMARKS_BACKUP_INTERVAL = 86400 * 1000; // Maximum number of backups to create. Old ones will be purged. @@ -257,8 +257,7 @@ BrowserGlue.prototype = { this._onPlacesShutdown(); break; case "idle": - if ((this._idleService.idleTime > BOOKMARKS_BACKUP_IDLE_TIME * 1000) && - this._shouldBackupBookmarks()) + if (this._idleService.idleTime > BOOKMARKS_BACKUP_IDLE_TIME * 1000) this._backupBookmarks(); break; case "distribution-customization-complete": @@ -1049,8 +1048,7 @@ BrowserGlue.prototype = { Services.prefs.getBoolPref("browser.bookmarks.restore_default_bookmarks"); if (restoreDefaultBookmarks) { // Ensure that we already have a bookmarks backup for today. - if (this._shouldBackupBookmarks()) - yield this._backupBookmarks(); + yield this._backupBookmarks(); importBookmarks = true; } } catch(ex) {} @@ -1059,7 +1057,7 @@ BrowserGlue.prototype = { // from bookmarks.html, we will try to restore from JSON if (importBookmarks && !restoreDefaultBookmarks && !importBookmarksHTML) { // get latest JSON backup - var bookmarksBackupFile = PlacesBackups.getMostRecent("json"); + var bookmarksBackupFile = yield PlacesBackups.getMostRecent("json"); if (bookmarksBackupFile) { // restore from JSON backup yield BookmarkJSONUtils.importFromFile(bookmarksBackupFile, true); @@ -1183,22 +1181,19 @@ BrowserGlue.prototype = { } let waitingForBackupToComplete = true; - if (this._shouldBackupBookmarks()) { - waitingForBackupToComplete = false; - this._backupBookmarks().then( - function onSuccess() { - waitingForBackupToComplete = true; - }, - function onFailure() { - Cu.reportError("Unable to backup bookmarks."); - waitingForBackupToComplete = true; - } - ); - } + this._backupBookmarks().then( + function onSuccess() { + waitingForBackupToComplete = false; + }, + function onFailure() { + Cu.reportError("Unable to backup bookmarks."); + waitingForBackupToComplete = false; + } + ); // Backup bookmarks to bookmarks.html to support apps that depend // on the legacy format. - let waitingForHTMLExportToComplete = true; + let waitingForHTMLExportToComplete = false; // If this fails to get the preference value, we don't export. if (Services.prefs.getBoolPref("browser.bookmarks.autoExportHTML")) { // Exceptionally, since this is a non-default setting and HTML format is @@ -1207,51 +1202,44 @@ BrowserGlue.prototype = { // the event loop on shutdown until we include a watchdog to prevent // potential hangs (bug 518683). The asynchronous shutdown operations // will then be handled by a shutdown service (bug 435058). - waitingForHTMLExportToComplete = false; + waitingForHTMLExportToComplete = true; BookmarkHTMLUtils.exportToFile(Services.dirsvc.get("BMarks", Ci.nsIFile)).then( function onSuccess() { - waitingForHTMLExportToComplete = true; + waitingForHTMLExportToComplete = false; }, function onFailure() { Cu.reportError("Unable to auto export html."); - waitingForHTMLExportToComplete = true; + waitingForHTMLExportToComplete = false; } ); } + // The events loop should spin at least once because waitingForBackupToComplete + // is true before checking whether backup should be made. let thread = Services.tm.currentThread; - while (!waitingForBackupToComplete || !waitingForHTMLExportToComplete) { + while (waitingForBackupToComplete || waitingForHTMLExportToComplete) { thread.processNextEvent(true); } }, - /** - * Determine whether to backup bookmarks or not. - * @return true if bookmarks should be backed up, false if not. - */ - _shouldBackupBookmarks: function BG__shouldBackupBookmarks() { - let lastBackupFile = PlacesBackups.getMostRecent(); - - // Should backup bookmarks if there are no backups or the maximum interval between - // backups elapsed. - return (!lastBackupFile || - new Date() - PlacesBackups.getDateForFile(lastBackupFile) > BOOKMARKS_BACKUP_INTERVAL); - }, - /** * Backup bookmarks. */ _backupBookmarks: function BG__backupBookmarks() { return Task.spawn(function() { - // Backup bookmarks if there are no backups or the maximum interval between - // backups elapsed. - let maxBackups = BOOKMARKS_BACKUP_MAX_BACKUPS; - try { - maxBackups = Services.prefs.getIntPref("browser.bookmarks.max_backups"); - } - catch(ex) { /* Use default. */ } + let lastBackupFile = yield PlacesBackups.getMostRecentBackup(); + // Should backup bookmarks if there are no backups or the maximum + // interval between backups elapsed. + if (!lastBackupFile || + new Date() - PlacesBackups.getDateForFile(lastBackupFile) > BOOKMARKS_BACKUP_INTERVAL) { + let maxBackups = BOOKMARKS_BACKUP_MAX_BACKUPS; + try { + maxBackups = Services.prefs.getIntPref("browser.bookmarks.max_backups"); + } + catch(ex) { /* Use default. */ } - yield PlacesBackups.create(maxBackups); // Don't force creation. + yield PlacesBackups.create(maxBackups); // Don't force creation. + } }); }, diff --git a/browser/components/places/content/places.js b/browser/components/places/content/places.js index ffa837860997..0403fad151c1 100644 --- a/browser/components/places/content/places.js +++ b/browser/components/places/content/places.js @@ -407,59 +407,64 @@ var PlacesOrganizer = { while (restorePopup.childNodes.length > 1) restorePopup.removeChild(restorePopup.firstChild); - let backupFiles = PlacesBackups.entries; - if (backupFiles.length == 0) - return; + Task.spawn(function() { + let backupFiles = yield PlacesBackups.getBackupFiles(); + if (backupFiles.length == 0) + return; - // Populate menu with backups. - for (let i = 0; i < backupFiles.length; i++) { - let [size, unit] = DownloadUtils.convertByteUnits(backupFiles[i].fileSize); - let sizeString = PlacesUtils.getFormattedString("backupFileSizeText", - [size, unit]); - let sizeInfo; - let bookmarkCount = PlacesBackups.getBookmarkCountForFile(backupFiles[i]); - if (bookmarkCount != null) { - sizeInfo = " (" + sizeString + " - " + - PlacesUIUtils.getPluralString("detailsPane.itemsCountLabel", - bookmarkCount, - [bookmarkCount]) + - ")"; - } else { - sizeInfo = " (" + sizeString + ")"; + // Populate menu with backups. + for (let i = 0; i < backupFiles.length; i++) { + let fileSize = (yield OS.File.stat(backupFiles[i])).size; + let [size, unit] = DownloadUtils.convertByteUnits(fileSize); + let sizeString = PlacesUtils.getFormattedString("backupFileSizeText", + [size, unit]); + let sizeInfo; + let bookmarkCount = PlacesBackups.getBookmarkCountForFile(backupFiles[i]); + if (bookmarkCount != null) { + sizeInfo = " (" + sizeString + " - " + + PlacesUIUtils.getPluralString("detailsPane.itemsCountLabel", + bookmarkCount, + [bookmarkCount]) + + ")"; + } else { + sizeInfo = " (" + sizeString + ")"; + } + + let backupDate = PlacesBackups.getDateForFile(backupFiles[i]); + let m = restorePopup.insertBefore(document.createElement("menuitem"), + document.getElementById("restoreFromFile")); + m.setAttribute("label", + dateSvc.FormatDate("", + Ci.nsIScriptableDateFormat.dateFormatLong, + backupDate.getFullYear(), + backupDate.getMonth() + 1, + backupDate.getDate()) + + sizeInfo); + m.setAttribute("value", OS.Path.basename(backupFiles[i])); + m.setAttribute("oncommand", + "PlacesOrganizer.onRestoreMenuItemClick(this);"); } - let backupDate = PlacesBackups.getDateForFile(backupFiles[i]); - let m = restorePopup.insertBefore(document.createElement("menuitem"), - document.getElementById("restoreFromFile")); - m.setAttribute("label", - dateSvc.FormatDate("", - Ci.nsIScriptableDateFormat.dateFormatLong, - backupDate.getFullYear(), - backupDate.getMonth() + 1, - backupDate.getDate()) + - sizeInfo); - m.setAttribute("value", backupFiles[i].leafName); - m.setAttribute("oncommand", - "PlacesOrganizer.onRestoreMenuItemClick(this);"); - } - - // Add the restoreFromFile item. - restorePopup.insertBefore(document.createElement("menuseparator"), - document.getElementById("restoreFromFile")); + // Add the restoreFromFile item. + restorePopup.insertBefore(document.createElement("menuseparator"), + document.getElementById("restoreFromFile")); + }); }, /** * Called when a menuitem is selected from the restore menu. */ onRestoreMenuItemClick: function PO_onRestoreMenuItemClick(aMenuItem) { - let backupName = aMenuItem.getAttribute("value"); - let backupFiles = PlacesBackups.entries; - for (let i = 0; i < backupFiles.length; i++) { - if (backupFiles[i].leafName == backupName) { - this.restoreBookmarksFromFile(backupFiles[i]); - break; + Task.spawn(function() { + let backupName = aMenuItem.getAttribute("value"); + let backupFilePaths = yield PlacesBackups.getBackupFiles(); + for (let backupFilePath of backupFilePaths) { + if (OS.Path.basename(backupFilePath) == backupName) { + PlacesOrganizer.restoreBookmarksFromFile(new FileUtils.File(backupFilePath)); + break; + } } - } + }); }, /** diff --git a/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js b/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js index 8fdfca29c3a0..c2081939d8d4 100644 --- a/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js +++ b/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js @@ -319,20 +319,25 @@ function run_test() { let bg = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver); // Initialize Places. PlacesUtils.history; + // Observes Places initialisation complete. + Services.obs.addObserver(function waitPlaceInitComplete() { + Services.obs.removeObserver(waitPlaceInitComplete, "places-browser-init-complete"); + + // Ensure preferences status. + do_check_false(Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML)); + do_check_false(Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS)); + try { + do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); + do_throw("importBookmarksHTML pref should not exist"); + } + catch(ex) {} + + waitForImportAndSmartBookmarks(next_test); + }, "places-browser-init-complete", false); + // Usually places init would async notify to glue, but we want to avoid // randomness here, thus we fire the notification synchronously. bg.observe(null, "places-init-complete", null); - - // Ensure preferences status. - do_check_false(Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML)); - do_check_false(Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS)); - try { - do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); - do_throw("importBookmarksHTML pref should not exist"); - } - catch(ex) {} - - waitForImportAndSmartBookmarks(next_test); } function waitForImportAndSmartBookmarks(aCallback) { diff --git a/browser/installer/package-manifest.in b/browser/installer/package-manifest.in index 7183b5f5666c..4c99a6271c8e 100644 --- a/browser/installer/package-manifest.in +++ b/browser/installer/package-manifest.in @@ -528,8 +528,6 @@ @BINPATH@/components/ContactManager.manifest @BINPATH@/components/PhoneNumberService.js @BINPATH@/components/PhoneNumberService.manifest -@BINPATH@/components/NotificationStorage.js -@BINPATH@/components/NotificationStorage.manifest @BINPATH@/components/AlarmsManager.js @BINPATH@/components/AlarmsManager.manifest @BINPATH@/components/Push.js diff --git a/content/svg/content/src/SVGFEGaussianBlurElement.cpp b/content/svg/content/src/SVGFEGaussianBlurElement.cpp index 44b5bef5eede..67d6f73828de 100644 --- a/content/svg/content/src/SVGFEGaussianBlurElement.cpp +++ b/content/svg/content/src/SVGFEGaussianBlurElement.cpp @@ -106,8 +106,8 @@ BoxBlur(const uint8_t *aInput, uint8_t *aOutput, int32_t aLeftLobe, int32_t aRightLobe, bool aAlphaOnly) { int32_t boxSize = aLeftLobe + aRightLobe + 1; - int32_t scaledDivisor = ComputeScaledDivisor(boxSize); - int32_t sums[4] = {0, 0, 0, 0}; + uint32_t scaledDivisor = ComputeScaledDivisor(boxSize); + uint32_t sums[4] = {0, 0, 0, 0}; for (int32_t i=0; i < boxSize; i++) { int32_t pos = aStartMinor - aLeftLobe + i; @@ -119,7 +119,7 @@ BoxBlur(const uint8_t *aInput, uint8_t *aOutput, } aOutput += aStrideMinor*aStartMinor; - if (aStartMinor + int32_t(boxSize) <= aEndMinor) { + if (aStartMinor + boxSize <= aEndMinor) { const uint8_t *lastInput = aInput + aStartMinor*aStrideMinor; const uint8_t *nextInput = aInput + (aStartMinor + aRightLobe + 1)*aStrideMinor; #define OUTPUT(j) aOutput[j] = (sums[j]*scaledDivisor) >> 24; diff --git a/dom/bindings/Bindings.conf b/dom/bindings/Bindings.conf index 60002e16feb8..9a26565157fa 100644 --- a/dom/bindings/Bindings.conf +++ b/dom/bindings/Bindings.conf @@ -118,10 +118,6 @@ DOMInterfaces = { 'resultNotAddRefed': [ 'playbackRate' ], }, -'Notification' : { - 'nativeType': 'mozilla::dom::Notification' -}, - 'AudioNode' : { 'concrete': False, 'binaryNames': { diff --git a/dom/datastore/DataStore.jsm b/dom/datastore/DataStore.jsm index f18ffb0b85ca..45884bf2f260 100644 --- a/dom/datastore/DataStore.jsm +++ b/dom/datastore/DataStore.jsm @@ -147,9 +147,11 @@ this.DataStore.prototype = { let pendingIds = aIds.length; let indexPos = 0; + let self = this; + function getInternalSuccess(aEvent, aPos) { debug("GetInternal success. Record: " + aEvent.target.result); - results[aPos] = aEvent.target.result; + results[aPos] = ObjectWrapper.wrap(aEvent.target.result, self._window); if (!--pendingIds) { aCallback(results); return; diff --git a/dom/datastore/tests/file_bug924104.html b/dom/datastore/tests/file_bug924104.html new file mode 100644 index 000000000000..7593c51721ba --- /dev/null +++ b/dom/datastore/tests/file_bug924104.html @@ -0,0 +1,77 @@ + + + + + Test for bug 924104 + + +
+ + + diff --git a/dom/datastore/tests/mochitest.ini b/dom/datastore/tests/mochitest.ini index e27ab12b5516..cf3056acfce1 100644 --- a/dom/datastore/tests/mochitest.ini +++ b/dom/datastore/tests/mochitest.ini @@ -11,6 +11,7 @@ support-files = file_app2.template.webapp file_arrays.html file_sync.html + file_bug924104.html [test_app_install.html] [test_readonly.html] @@ -20,3 +21,4 @@ support-files = [test_arrays.html] [test_oop.html] [test_sync.html] +[test_bug924104.html] diff --git a/dom/datastore/tests/test_bug924104.html b/dom/datastore/tests/test_bug924104.html new file mode 100644 index 000000000000..e8d948e3b89c --- /dev/null +++ b/dom/datastore/tests/test_bug924104.html @@ -0,0 +1,129 @@ + + + + + Test bug 924104 + + + + +
+ + + diff --git a/dom/interfaces/notification/moz.build b/dom/interfaces/notification/moz.build index c87af1a9ec74..1a5ba8599576 100644 --- a/dom/interfaces/notification/moz.build +++ b/dom/interfaces/notification/moz.build @@ -6,7 +6,6 @@ XPIDL_SOURCES += [ 'nsIDOMDesktopNotification.idl', - 'nsINotificationStorage.idl', ] XPIDL_MODULE = 'dom_notification' diff --git a/dom/interfaces/notification/nsINotificationStorage.idl b/dom/interfaces/notification/nsINotificationStorage.idl deleted file mode 100644 index a046989222d4..000000000000 --- a/dom/interfaces/notification/nsINotificationStorage.idl +++ /dev/null @@ -1,92 +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/. */ - -#include "domstubs.idl" - -[scriptable, uuid(fb089720-1c5c-11e3-b773-0800200c9a66)] -interface nsINotificationStorageCallback : nsISupports -{ - /** - * Callback function used to pass single notification back - * into C++ land for Notification.get return data. - * - * @param id: a uuid for this notification - * @param title: the notification title - * @param dir: the notification direction, - * possible values are "ltr", "rtl", "auto" - * @param lang: the notification language - * @param body: the notification body - * @param tag: the notification tag - */ - [implicit_jscontext] - void handle(in DOMString id, - in DOMString title, - in DOMString dir, - in DOMString lang, - in DOMString body, - in DOMString tag, - in DOMString icon); - - /** - * Callback function used to notify C++ the we have returned - * all notification objects for this Notification.get call. - */ - [implicit_jscontext] - void done(); -}; - -/** - * Interface for notification persistence layer. - */ -[scriptable, uuid(b177b080-2a23-11e3-8224-0800200c9a66)] -interface nsINotificationStorage : nsISupports -{ - - /** - * Add/replace a notification to the persistence layer. - * - * @param origin: the origin/app of this notification - * @param id: a uuid for this notification - * @param title: the notification title - * @param dir: the notification direction, - * possible values are "ltr", "rtl", "auto" - * @param lang: the notification language - * @param body: the notification body - * @param tag: notification tag, will replace any existing - * notifications with same origin/tag pair - */ - void put(in DOMString origin, - in DOMString id, - in DOMString title, - in DOMString dir, - in DOMString lang, - in DOMString body, - in DOMString tag, - in DOMString icon); - - /** - * Retrieve a list of notifications. - * - * @param origin: the origin/app for which to fetch notifications from - * @param tag: used to fetch only a specific tag - * @param callback: nsINotificationStorageCallback, used for - * returning notifications objects - */ - void get(in DOMString origin, - in DOMString tag, - in nsINotificationStorageCallback aCallback); - - /** - * Remove a notification from storage. - * - * @param origin: the origin/app to delete the notification from - * @param id: the uuid for the notification to delete - */ - void delete(in DOMString origin, - in DOMString id); -}; - -%{C++ -#define NS_NOTIFICATION_STORAGE_CONTRACTID "@mozilla.org/notificationStorage;1" -%} diff --git a/dom/promise/Promise.cpp b/dom/promise/Promise.cpp index 0af9a6202efa..1fcbb4fb514f 100644 --- a/dom/promise/Promise.cpp +++ b/dom/promise/Promise.cpp @@ -189,20 +189,6 @@ Promise::EnabledForScope(JSContext* aCx, JSObject* /* unused */) prin->GetAppStatus() == nsIPrincipal::APP_STATUS_CERTIFIED; } -void -Promise::MaybeResolve(JSContext* aCx, - const Optional >& aValue) -{ - MaybeResolveInternal(aCx, aValue); -} - -void -Promise::MaybeReject(JSContext* aCx, - const Optional >& aValue) -{ - MaybeRejectInternal(aCx, aValue); -} - static void EnterCompartment(Maybe& aAc, JSContext* aCx, const Optional >& aValue) @@ -243,9 +229,9 @@ Promise::JSCallback(JSContext *aCx, unsigned aArgc, JS::Value *aVp) PromiseCallback::Task task = static_cast(v.toInt32()); if (task == PromiseCallback::Resolve) { - promise->MaybeResolveInternal(aCx, value); + promise->MaybeResolve(aCx, value); } else { - promise->MaybeRejectInternal(aCx, value); + promise->MaybeReject(aCx, value); } return true; @@ -314,7 +300,7 @@ Promise::Constructor(const GlobalObject& aGlobal, Maybe ac; EnterCompartment(ac, cx, value); - promise->MaybeRejectInternal(cx, value); + promise->MaybeReject(cx, value); } return promise.forget(); @@ -333,7 +319,7 @@ Promise::Resolve(const GlobalObject& aGlobal, JSContext* aCx, nsRefPtr promise = new Promise(window); Optional > value(aCx, aValue); - promise->MaybeResolveInternal(aCx, value); + promise->MaybeResolve(aCx, value); return promise.forget(); } @@ -350,7 +336,7 @@ Promise::Reject(const GlobalObject& aGlobal, JSContext* aCx, nsRefPtr promise = new Promise(window); Optional > value(aCx, aValue); - promise->MaybeRejectInternal(aCx, value); + promise->MaybeReject(aCx, value); return promise.forget(); } @@ -455,9 +441,9 @@ Promise::MaybeReportRejected() } void -Promise::MaybeResolveInternal(JSContext* aCx, - const Optional >& aValue, - PromiseTaskSync aAsynchronous) +Promise::MaybeResolve(JSContext* aCx, + const Optional >& aValue, + PromiseTaskSync aAsynchronous) { if (mResolvePending) { return; @@ -467,9 +453,9 @@ Promise::MaybeResolveInternal(JSContext* aCx, } void -Promise::MaybeRejectInternal(JSContext* aCx, - const Optional >& aValue, - PromiseTaskSync aAsynchronous) +Promise::MaybeReject(JSContext* aCx, + const Optional >& aValue, + PromiseTaskSync aAsynchronous) { if (mResolvePending) { return; diff --git a/dom/promise/Promise.h b/dom/promise/Promise.h index de2c06f11525..26c6f8c1f8b7 100644 --- a/dom/promise/Promise.h +++ b/dom/promise/Promise.h @@ -43,11 +43,6 @@ public: static bool PrefEnabled(); static bool EnabledForScope(JSContext* aCx, JSObject* /* unused */); - void MaybeResolve(JSContext* aCx, - const Optional >& aValue); - void MaybeReject(JSContext* aCx, - const Optional >& aValue); - // WebIDL nsPIDOMWindow* GetParentObject() const @@ -119,12 +114,12 @@ private: // report it to the error console. void MaybeReportRejected(); - void MaybeResolveInternal(JSContext* aCx, - const Optional >& aValue, - PromiseTaskSync aSync = AsyncTask); - void MaybeRejectInternal(JSContext* aCx, - const Optional >& aValue, - PromiseTaskSync aSync = AsyncTask); + void MaybeResolve(JSContext* aCx, + const Optional >& aValue, + PromiseTaskSync aSync = AsyncTask); + void MaybeReject(JSContext* aCx, + const Optional >& aValue, + PromiseTaskSync aSync = AsyncTask); void ResolveInternal(JSContext* aCx, const Optional >& aValue, diff --git a/dom/src/notification/Notification.cpp b/dom/src/notification/Notification.cpp index 151668205574..dc91865f68b1 100644 --- a/dom/src/notification/Notification.cpp +++ b/dom/src/notification/Notification.cpp @@ -5,7 +5,6 @@ #include "PCOMContentPermissionRequestChild.h" #include "mozilla/dom/Notification.h" #include "mozilla/dom/OwningNonNull.h" -#include "mozilla/dom/Promise.h" #include "mozilla/Preferences.h" #include "TabChild.h" #include "nsContentUtils.h" @@ -13,135 +12,20 @@ #include "nsIAlertsService.h" #include "nsIContentPermissionPrompt.h" #include "nsIDocument.h" -#include "nsINotificationStorage.h" #include "nsIPermissionManager.h" -#include "nsIUUIDGenerator.h" #include "nsServiceManagerUtils.h" #include "nsToolkitCompsCID.h" #include "nsGlobalWindow.h" #include "nsDOMJSUtils.h" #include "nsIScriptSecurityManager.h" -#include "nsIAppsService.h" - #ifdef MOZ_B2G #include "nsIDOMDesktopNotification.h" +#include "nsIAppsService.h" #endif namespace mozilla { namespace dom { -class NotificationStorageCallback MOZ_FINAL : public nsINotificationStorageCallback -{ -public: - NS_DECL_CYCLE_COLLECTING_ISUPPORTS - NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(NotificationStorageCallback) - - NotificationStorageCallback(const GlobalObject& aGlobal, nsPIDOMWindow* aWindow, Promise* aPromise) - : mCount(0), - mGlobal(aGlobal.Get()), - mWindow(aWindow), - mPromise(aPromise) - { - MOZ_ASSERT(aWindow); - MOZ_ASSERT(aPromise); - JSContext* cx = aGlobal.GetContext(); - mNotifications = JS_NewArrayObject(cx, 0, nullptr); - HoldData(); - } - - NS_IMETHOD Handle(const nsAString& aID, - const nsAString& aTitle, - const nsAString& aDir, - const nsAString& aLang, - const nsAString& aBody, - const nsAString& aTag, - const nsAString& aIcon, - JSContext* aCx) - { - MOZ_ASSERT(!aID.IsEmpty()); - MOZ_ASSERT(!aTitle.IsEmpty()); - - NotificationOptions options; - options.mDir = Notification::StringToDirection(nsString(aDir)); - options.mLang = aLang; - options.mBody = aBody; - options.mTag = aTag; - options.mIcon = aIcon; - nsRefPtr notification = Notification::CreateInternal(mWindow, - aID, - aTitle, - options); - JSAutoCompartment ac(aCx, mGlobal); - JS::RootedObject scope(aCx, mGlobal); - JS::RootedObject element(aCx, notification->WrapObject(aCx, scope)); - NS_ENSURE_TRUE(element, NS_ERROR_FAILURE); - - if (!JS_DefineElement(aCx, mNotifications, mCount++, - JS::ObjectValue(*element), nullptr, nullptr, 0)) { - return NS_ERROR_FAILURE; - } - return NS_OK; - } - - NS_IMETHOD Done(JSContext* aCx) - { - JSAutoCompartment ac(aCx, mGlobal); - Optional result(aCx, JS::ObjectValue(*mNotifications)); - mPromise->MaybeResolve(aCx, result); - return NS_OK; - } - -private: - ~NotificationStorageCallback() - { - DropData(); - } - - void HoldData() - { - mozilla::HoldJSObjects(this); - } - - void DropData() - { - mGlobal = nullptr; - mNotifications = nullptr; - mozilla::DropJSObjects(this); - } - - uint32_t mCount; - JS::Heap mGlobal; - nsCOMPtr mWindow; - nsRefPtr mPromise; - JS::Heap mNotifications; -}; - -NS_IMPL_CYCLE_COLLECTING_ADDREF(NotificationStorageCallback) -NS_IMPL_CYCLE_COLLECTING_RELEASE(NotificationStorageCallback) -NS_IMPL_CYCLE_COLLECTION_CLASS(NotificationStorageCallback) - -NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(NotificationStorageCallback) - NS_INTERFACE_MAP_ENTRY(nsINotificationStorageCallback) - NS_INTERFACE_MAP_ENTRY(nsISupports) -NS_INTERFACE_MAP_END - -NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(NotificationStorageCallback) - NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mGlobal) - NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mNotifications) -NS_IMPL_CYCLE_COLLECTION_TRACE_END - -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(NotificationStorageCallback) - NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS - NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow) - NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPromise) -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END - -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(NotificationStorageCallback) - NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow) - NS_IMPL_CYCLE_COLLECTION_UNLINK(mPromise) - tmp->DropData(); -NS_IMPL_CYCLE_COLLECTION_UNLINK_END - class NotificationPermissionRequest : public nsIContentPermissionRequest, public PCOMContentPermissionRequestChild, public nsIRunnable @@ -372,15 +256,12 @@ NotificationTask::Run() { switch (mAction) { case eShow: - mNotification->ShowInternal(); - break; + return mNotification->ShowInternal(); case eClose: - mNotification->CloseInternal(); - break; + return mNotification->CloseInternal(); default: MOZ_CRASH("Unexpected action for NotificationTask."); } - return NS_OK; } NS_IMPL_ISUPPORTS1(NotificationObserver, nsIObserver) @@ -401,103 +282,50 @@ NotificationObserver::Observe(nsISupports* aSubject, const char* aTopic, return NS_OK; } -Notification::Notification(const nsAString& aID, const nsAString& aTitle, const nsAString& aBody, +Notification::Notification(const nsAString& aTitle, const nsAString& aBody, NotificationDirection aDir, const nsAString& aLang, const nsAString& aTag, const nsAString& aIconUrl) - : mID(aID), mTitle(aTitle), mBody(aBody), mDir(aDir), mLang(aLang), + : mTitle(aTitle), mBody(aBody), mDir(aDir), mLang(aLang), mTag(aTag), mIconUrl(aIconUrl), mIsClosed(false) { SetIsDOMBinding(); } -// static already_AddRefed Notification::Constructor(const GlobalObject& aGlobal, const nsAString& aTitle, const NotificationOptions& aOptions, ErrorResult& aRv) { - MOZ_ASSERT(NS_IsMainThread()); + nsString tag; + if (aOptions.mTag.WasPassed()) { + tag.Append(NS_LITERAL_STRING("tag:")); + tag.Append(aOptions.mTag.Value()); + } else { + tag.Append(NS_LITERAL_STRING("notag:")); + tag.AppendInt(sCount++); + } + + nsRefPtr notification = new Notification(aTitle, + aOptions.mBody, + aOptions.mDir, + aOptions.mLang, + tag, + aOptions.mIcon); + nsCOMPtr window = do_QueryInterface(aGlobal.GetAsSupports()); MOZ_ASSERT(window, "Window should not be null."); - nsRefPtr notification = CreateInternal(window, - EmptyString(), - aTitle, - aOptions); + notification->BindToOwner(window); // Queue a task to show the notification. nsCOMPtr showNotificationTask = new NotificationTask(notification, NotificationTask::eShow); - NS_DispatchToCurrentThread(showNotificationTask); - - // Persist the notification. - nsresult rv; - nsCOMPtr notificationStorage = - do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv); - if (NS_FAILED(rv)) { - aRv.Throw(rv); - return nullptr; - } - - nsString origin; - aRv = GetOrigin(window, origin); - if (aRv.Failed()) { - return nullptr; - } - - nsString id; - notification->GetID(id); - aRv = notificationStorage->Put(origin, - id, - aTitle, - DirectionToString(aOptions.mDir), - aOptions.mLang, - aOptions.mBody, - aOptions.mTag, - aOptions.mIcon); - if (aRv.Failed()) { - return nullptr; - } + NS_DispatchToMainThread(showNotificationTask); return notification.forget(); } -already_AddRefed -Notification::CreateInternal(nsPIDOMWindow* aWindow, - const nsAString& aID, - const nsAString& aTitle, - const NotificationOptions& aOptions) -{ - nsString id; - if (!aID.IsEmpty()) { - id = aID; - } else { - nsCOMPtr uuidgen = - do_GetService("@mozilla.org/uuid-generator;1"); - NS_ENSURE_TRUE(uuidgen, nullptr); - nsID uuid; - nsresult rv = uuidgen->GenerateUUIDInPlace(&uuid); - NS_ENSURE_SUCCESS(rv, nullptr); - - char buffer[NSID_LENGTH]; - uuid.ToProvidedString(buffer); - NS_ConvertASCIItoUTF16 convertedID(buffer); - id = convertedID; - } - - nsRefPtr notification = new Notification(id, - aTitle, - aOptions.mBody, - aOptions.mDir, - aOptions.mLang, - aOptions.mTag, - aOptions.mIcon); - - notification->BindToOwner(aWindow); - return notification.forget(); -} - -void +nsresult Notification::ShowInternal() { nsCOMPtr alertService = @@ -508,8 +336,7 @@ Notification::ShowInternal() NotificationPermission::Granted || !alertService) { // We do not have permission to show a notification or alert service // is not available. - DispatchTrustedEvent(NS_LITERAL_STRING("error")); - return; + return DispatchTrustedEvent(NS_LITERAL_STRING("error")); } nsresult rv; @@ -517,18 +344,17 @@ Notification::ShowInternal() if (mIconUrl.Length() > 0) { // Resolve image URL against document base URI. nsIDocument* doc = GetOwner()->GetExtantDoc(); - if (doc) { - nsCOMPtr baseUri = doc->GetBaseURI(); - if (baseUri) { - nsCOMPtr srcUri; - rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(srcUri), - mIconUrl, doc, baseUri); - if (NS_SUCCEEDED(rv)) { - nsAutoCString src; - srcUri->GetSpec(src); - absoluteUrl = NS_ConvertUTF8toUTF16(src); - } - } + NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED); + nsCOMPtr baseUri = doc->GetBaseURI(); + NS_ENSURE_TRUE(baseUri, NS_ERROR_UNEXPECTED); + nsCOMPtr srcUri; + rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(srcUri), + mIconUrl, doc, baseUri); + NS_ENSURE_SUCCESS(rv, rv); + if (srcUri) { + nsAutoCString src; + srcUri->GetSpec(src); + absoluteUrl = NS_ConvertUTF8toUTF16(src); } } @@ -536,7 +362,7 @@ Notification::ShowInternal() nsString alertName; rv = GetAlertName(alertName); - NS_ENSURE_SUCCESS_VOID(rv); + NS_ENSURE_SUCCESS(rv, rv); #ifdef MOZ_B2G nsCOMPtr appNotifier = @@ -548,15 +374,12 @@ Notification::ShowInternal() if (appId != nsIScriptSecurityManager::UNKNOWN_APP_ID) { nsCOMPtr appsService = do_GetService("@mozilla.org/AppsService;1"); nsString manifestUrl = EmptyString(); - rv = appsService->GetManifestURLByLocalId(appId, manifestUrl); - if (NS_SUCCEEDED(rv)) { - appNotifier->ShowAppNotification(mIconUrl, mTitle, mBody, - true, - manifestUrl, - observer, - alertName); - return; - } + appsService->GetManifestURLByLocalId(appId, manifestUrl); + return appNotifier->ShowAppNotification(mIconUrl, mTitle, mBody, + true, + manifestUrl, + observer, + alertName); } } #endif @@ -565,9 +388,9 @@ Notification::ShowInternal() // nsIObserver. Thus the cookie must be unique to differentiate observers. nsString uniqueCookie = NS_LITERAL_STRING("notification:"); uniqueCookie.AppendInt(sCount++); - alertService->ShowAlertNotification(absoluteUrl, mTitle, mBody, true, - uniqueCookie, observer, alertName, - DirectionToString(mDir), mLang); + return alertService->ShowAlertNotification(absoluteUrl, mTitle, mBody, true, + uniqueCookie, observer, alertName, + DirectionToString(mDir), mLang); } void @@ -655,47 +478,6 @@ Notification::GetPermissionInternal(nsISupports* aGlobal, ErrorResult& aRv) } } -already_AddRefed -Notification::Get(const GlobalObject& aGlobal, - const GetNotificationOptions& aFilter, - ErrorResult& aRv) -{ - nsCOMPtr window = do_QueryInterface(aGlobal.GetAsSupports()); - MOZ_ASSERT(window); - nsIDocument* doc = window->GetExtantDoc(); - if (!doc) { - aRv.Throw(NS_ERROR_UNEXPECTED); - return nullptr; - } - - nsString origin; - aRv = GetOrigin(window, origin); - if (aRv.Failed()) { - return nullptr; - } - - nsresult rv; - nsCOMPtr notificationStorage = - do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv); - if (NS_FAILED(rv)) { - aRv.Throw(rv); - return nullptr; - } - - nsRefPtr promise = new Promise(window); - nsCOMPtr callback = - new NotificationStorageCallback(aGlobal, window, promise); - nsString tag = aFilter.mTag.WasPassed() ? - aFilter.mTag.Value() : - EmptyString(); - aRv = notificationStorage->Get(origin, tag, callback); - if (aRv.Failed()) { - return nullptr; - } - - return promise.forget(); -} - bool Notification::PrefEnabled() { @@ -717,61 +499,22 @@ Notification::Close() NS_DispatchToMainThread(showNotificationTask); } -void +nsresult Notification::CloseInternal() { if (!mIsClosed) { - nsresult rv; - // Don't bail out if notification storage fails, since we still - // want to send the close event through the alert service. - nsCOMPtr notificationStorage = - do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID); - if (notificationStorage) { - nsString origin; - rv = GetOrigin(GetOwner(), origin); - if (NS_SUCCEEDED(rv)) { - notificationStorage->Delete(origin, mID); - } - } - nsCOMPtr alertService = do_GetService(NS_ALERTSERVICE_CONTRACTID); + if (alertService) { nsString alertName; - rv = GetAlertName(alertName); - if (NS_SUCCEEDED(rv)) { - alertService->CloseAlert(alertName); - } + nsresult rv = GetAlertName(alertName); + NS_ENSURE_SUCCESS(rv, rv); + + rv = alertService->CloseAlert(alertName); + NS_ENSURE_SUCCESS(rv, rv); } } -} - -nsresult -Notification::GetOrigin(nsPIDOMWindow* aWindow, nsString& aOrigin) -{ - MOZ_ASSERT(aWindow); - nsresult rv; - nsIDocument* doc = aWindow->GetExtantDoc(); - NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED); - nsIPrincipal* principal = doc->NodePrincipal(); - NS_ENSURE_TRUE(principal, NS_ERROR_UNEXPECTED); - - uint16_t appStatus = principal->GetAppStatus(); - uint32_t appId = principal->GetAppId(); - - if (appStatus == nsIPrincipal::APP_STATUS_NOT_INSTALLED || - appId == nsIScriptSecurityManager::NO_APP_ID || - appId == nsIScriptSecurityManager::UNKNOWN_APP_ID) { - rv = nsContentUtils::GetUTFOrigin(principal, aOrigin); - NS_ENSURE_SUCCESS(rv, rv); - } else { - // If we are in "app code", use manifest URL as unique origin since - // multiple apps can share the same origin but not same notifications. - nsCOMPtr appsService = - do_GetService("@mozilla.org/AppsService;1", &rv); - NS_ENSURE_SUCCESS(rv, rv); - appsService->GetManifestURLByLocalId(appId, aOrigin); - } return NS_OK; } @@ -779,12 +522,20 @@ Notification::GetOrigin(nsPIDOMWindow* aWindow, nsString& aOrigin) nsresult Notification::GetAlertName(nsString& aAlertName) { - // Get the notification name that is unique per origin + ID. - // The name of the alert is of the form origin#ID. - nsresult rv = GetOrigin(GetOwner(), aAlertName); + // Get the notification name that is unique per origin + tag. + // The name of the alert is of the form origin#tag + + nsPIDOMWindow* owner = GetOwner(); + NS_ENSURE_TRUE(owner, NS_ERROR_UNEXPECTED); + + nsIDocument* doc = owner->GetExtantDoc(); + NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED); + + nsresult rv = nsContentUtils::GetUTFOrigin(doc->NodePrincipal(), + aAlertName); NS_ENSURE_SUCCESS(rv, rv); aAlertName.AppendLiteral("#"); - aAlertName.Append(mID); + aAlertName.Append(mTag); return NS_OK; } diff --git a/dom/src/notification/Notification.h b/dom/src/notification/Notification.h index f6a47c91744a..afadfd60eb03 100644 --- a/dom/src/notification/Notification.h +++ b/dom/src/notification/Notification.h @@ -10,37 +10,31 @@ #include "nsDOMEventTargetHelper.h" #include "nsIObserver.h" -#include "nsCycleCollectionParticipant.h" - namespace mozilla { namespace dom { - class NotificationObserver; -class Promise; class Notification : public nsDOMEventTargetHelper { friend class NotificationTask; friend class NotificationPermissionRequest; friend class NotificationObserver; - friend class NotificationStorageCallback; - public: IMPL_EVENT_HANDLER(click) IMPL_EVENT_HANDLER(show) IMPL_EVENT_HANDLER(error) IMPL_EVENT_HANDLER(close) + Notification(const nsAString& aTitle, const nsAString& aBody, + NotificationDirection aDir, const nsAString& aLang, + const nsAString& aTag, const nsAString& aIconUrl); + static already_AddRefed Constructor(const GlobalObject& aGlobal, const nsAString& aTitle, const NotificationOptions& aOption, ErrorResult& aRv); - void GetID(nsAString& aRetval) { - aRetval = mID; - } - - void GetTitle(nsAString& aRetval) + void GetTitle(nsString& aRetval) { aRetval = mTitle; } @@ -50,22 +44,24 @@ public: return mDir; } - void GetLang(nsAString& aRetval) + void GetLang(nsString& aRetval) { aRetval = mLang; } - void GetBody(nsAString& aRetval) + void GetBody(nsString& aRetval) { aRetval = mBody; } - void GetTag(nsAString& aRetval) + void GetTag(nsString& aRetval) { - aRetval = mTag; + if (StringBeginsWith(mTag, NS_LITERAL_STRING("tag:"))) { + aRetval = Substring(mTag, 4); + } } - void GetIcon(nsAString& aRetval) + void GetIcon(nsString& aRetval) { aRetval = mIconUrl; } @@ -77,10 +73,6 @@ public: static NotificationPermission GetPermission(const GlobalObject& aGlobal, ErrorResult& aRv); - static already_AddRefed Get(const GlobalObject& aGlobal, - const GetNotificationOptions& aFilter, - ErrorResult& aRv); - void Close(); static bool PrefEnabled(); @@ -93,17 +85,8 @@ public: virtual JSObject* WrapObject(JSContext* aCx, JS::Handle aScope) MOZ_OVERRIDE; protected: - Notification(const nsAString& aID, const nsAString& aTitle, const nsAString& aBody, - NotificationDirection aDir, const nsAString& aLang, - const nsAString& aTag, const nsAString& aIconUrl); - - static already_AddRefed CreateInternal(nsPIDOMWindow* aWindow, - const nsAString& aID, - const nsAString& aTitle, - const NotificationOptions& aOptions); - - void ShowInternal(); - void CloseInternal(); + nsresult ShowInternal(); + nsresult CloseInternal(); static NotificationPermission GetPermissionInternal(nsISupports* aGlobal, ErrorResult& rv); @@ -120,22 +103,8 @@ protected: } } - static const NotificationDirection StringToDirection(const nsAString& aDirection) - { - if (aDirection.EqualsLiteral("ltr")) { - return NotificationDirection::Ltr; - } - if (aDirection.EqualsLiteral("rtl")) { - return NotificationDirection::Rtl; - } - return NotificationDirection::Auto; - } - - static nsresult GetOrigin(nsPIDOMWindow* aWindow, nsString& aOrigin); - nsresult GetAlertName(nsString& aAlertName); - nsString mID; nsString mTitle; nsString mBody; NotificationDirection mDir; diff --git a/dom/src/notification/NotificationDB.jsm b/dom/src/notification/NotificationDB.jsm deleted file mode 100644 index dd590c175266..000000000000 --- a/dom/src/notification/NotificationDB.jsm +++ /dev/null @@ -1,270 +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/. */ - -"use strict"; - -this.EXPORTED_SYMBOLS = []; - -const DEBUG = false; -function debug(s) { dump("-*- NotificationDB component: " + s + "\n"); } - -const Cu = Components.utils; -const Cc = Components.classes; -const Ci = Components.interfaces; - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/osfile.jsm"); - -XPCOMUtils.defineLazyServiceGetter(this, "ppmm", - "@mozilla.org/parentprocessmessagemanager;1", - "nsIMessageListenerManager"); - -XPCOMUtils.defineLazyGetter(this, "gEncoder", function() { - return new TextEncoder(); -}); - -XPCOMUtils.defineLazyGetter(this, "gDecoder", function() { - return new TextDecoder(); -}); - - -const NOTIFICATION_STORE_DIR = OS.Constants.Path.profileDir; -const NOTIFICATION_STORE_PATH = - OS.Path.join(NOTIFICATION_STORE_DIR, "notificationstore.json"); - -let NotificationDB = { - init: function() { - this.notifications = {}; - this.byTag = {}; - this.loaded = false; - - this.tasks = []; // read/write operation queue - this.runningTask = false; - - ppmm.addMessageListener("Notification:Save", this); - ppmm.addMessageListener("Notification:Delete", this); - ppmm.addMessageListener("Notification:GetAll", this); - }, - - // Attempt to read notification file, if it's not there we will create it. - load: function(callback) { - var promise = OS.File.read(NOTIFICATION_STORE_PATH); - promise.then( - function onSuccess(data) { - try { - this.notifications = JSON.parse(gDecoder.decode(data)); - } catch (e) { - if (DEBUG) { debug("Unable to parse file data " + e); } - } - this.loaded = true; - callback && callback(); - }.bind(this), - - // If read failed, we assume we have no notifications to load. - function onFailure(reason) { - this.loaded = true; - this.createStore(callback); - }.bind(this) - ); - }, - - // Creates the notification directory. - createStore: function(callback) { - var promise = OS.File.makeDir(NOTIFICATION_STORE_DIR, { - ignoreExisting: true - }); - promise.then( - function onSuccess() { - this.createFile(callback); - }.bind(this), - - function onFailure(reason) { - if (DEBUG) { debug("Directory creation failed:" + reason); } - callback && callback(); - } - ); - }, - - // Creates the notification file once the directory is created. - createFile: function(callback) { - var promise = OS.File.open(NOTIFICATION_STORE_PATH, {create: true}); - promise.then( - function onSuccess(handle) { - callback && callback(); - }, - function onFailure(reason) { - if (DEBUG) { debug("File creation failed:" + reason); } - callback && callback(); - } - ); - }, - - // Save current notifications to the file. - save: function(callback) { - var data = gEncoder.encode(JSON.stringify(this.notifications)); - var promise = OS.File.writeAtomic(NOTIFICATION_STORE_PATH, data); - promise.then( - function onSuccess() { - callback && callback(); - }, - function onFailure(reason) { - if (DEBUG) { debug("Save failed:" + reason); } - callback && callback(); - } - ); - }, - - // Helper function: callback will be called once file exists and/or is loaded. - ensureLoaded: function(callback) { - if (!this.loaded) { - this.load(callback); - } else { - callback(); - } - }, - - receiveMessage: function(message) { - if (DEBUG) { debug("Received message:" + message.name); } - - switch (message.name) { - case "Notification:GetAll": - this.queueTask("getall", message.data, function(notifications) { - message.target.sendAsyncMessage("Notification:GetAll:Return:OK", { - requestID: message.data.requestID, - notifications: notifications - }); - }); - break; - - case "Notification:Save": - this.queueTask("save", message.data, function() { - message.target.sendAsyncMessage("Notification:Save:Return:OK", { - requestID: message.data.requestID - }); - }); - break; - - case "Notification:Delete": - this.queueTask("delete", message.data, function() { - message.target.sendAsyncMessage("Notification:Delete:Return:OK", { - requestID: message.data.requestID - }); - }); - break; - - default: - if (DEBUG) { debug("Invalid message name" + message.name); } - } - }, - - // We need to make sure any read/write operations are atomic, - // so use a queue to run each operation sequentially. - queueTask: function(operation, data, callback) { - if (DEBUG) { debug("Queueing task: " + operation); } - this.tasks.push({ - operation: operation, - data: data, - callback: callback - }); - - // Only run immediately if we aren't currently running another task. - if (!this.runningTask) { - if (DEBUG) { dump("Task queue was not running, starting now..."); } - this.runNextTask(); - } - }, - - runNextTask: function() { - if (this.tasks.length === 0) { - if (DEBUG) { dump("No more tasks to run, queue depleted"); } - this.runningTask = false; - return; - } - this.runningTask = true; - - // Always make sure we are loaded before performing any read/write tasks. - this.ensureLoaded(function() { - var task = this.tasks.shift(); - - // Wrap the task callback to make sure we immediately - // run the next task after running the original callback. - var wrappedCallback = function() { - if (DEBUG) { debug("Finishing task: " + task.operation); } - task.callback.apply(this, arguments); - this.runNextTask(); - }.bind(this); - - switch (task.operation) { - case "getall": - this.taskGetAll(task.data, wrappedCallback); - break; - - case "save": - this.taskSave(task.data, wrappedCallback); - break; - - case "delete": - this.taskDelete(task.data, wrappedCallback); - break; - } - }.bind(this)); - }, - - taskGetAll: function(data, callback) { - if (DEBUG) { debug("Task, getting all"); } - var origin = data.origin; - var notifications = []; - // Grab only the notifications for specified origin. - for (var i in this.notifications[origin]) { - notifications.push(this.notifications[origin][i]); - } - callback(notifications); - }, - - taskSave: function(data, callback) { - if (DEBUG) { debug("Task, saving"); } - var origin = data.origin; - var notification = data.notification; - if (!this.notifications[origin]) { - this.notifications[origin] = {}; - this.byTag[origin] = {}; - } - - // We might have existing notification with this tag, - // if so we need to remove it before saving the new one. - if (notification.tag && this.byTag[origin][notification.tag]) { - var oldNotification = this.byTag[origin][notification.tag]; - delete this.notifications[origin][oldNotification.id]; - this.byTag[origin][notification.tag] = notification; - } - - this.notifications[origin][notification.id] = notification; - this.save(callback); - }, - - taskDelete: function(data, callback) { - if (DEBUG) { debug("Task, deleting"); } - var origin = data.origin; - var id = data.id; - if (!this.notifications[origin]) { - if (DEBUG) { debug("No notifications found for origin: " + origin); } - return; - } - - // Make sure we can find the notification to delete. - var oldNotification = this.notifications[origin][id]; - if (!oldNotification) { - if (DEBUG) { debug("No notification found with id: " + id); } - return; - } - - if (oldNotification.tag) { - delete this.byTag[origin][oldNotification.tag]; - } - delete this.notifications[origin][id]; - this.save(callback); - } -}; - -NotificationDB.init(); diff --git a/dom/src/notification/NotificationStorage.js b/dom/src/notification/NotificationStorage.js deleted file mode 100644 index b8b86ea28113..000000000000 --- a/dom/src/notification/NotificationStorage.js +++ /dev/null @@ -1,174 +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/. */ - -"use strict"; - -const DEBUG = false; -function debug(s) { dump("-*- NotificationStorage.js: " + s + "\n"); } - -const Cc = Components.classes; -const Ci = Components.interfaces; -const Cu = Components.utils; - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - -const NOTIFICATIONSTORAGE_CID = "{37f819b0-0b5c-11e3-8ffd-0800200c9a66}"; -const NOTIFICATIONSTORAGE_CONTRACTID = "@mozilla.org/notificationStorage;1"; - -XPCOMUtils.defineLazyServiceGetter(this, "cpmm", - "@mozilla.org/childprocessmessagemanager;1", - "nsIMessageSender"); - - -function NotificationStorage() { - // cache objects - this._notifications = {}; - this._byTag = {}; - this._cached = false; - - this._requests = {}; - this._requestCount = 0; - - // Register for message listeners. - cpmm.addMessageListener("Notification:GetAll:Return:OK", this); -} - -NotificationStorage.prototype = { - - put: function(origin, id, title, dir, lang, body, tag, icon) { - if (DEBUG) { debug("PUT: " + id + ": " + title); } - var notification = { - id: id, - title: title, - dir: dir, - lang: lang, - body: body, - tag: tag, - icon: icon - }; - - this._notifications[id] = notification; - if (tag) { - // We might have existing notification with this tag, - // if so we need to remove it from our cache. - if (this._byTag[tag]) { - var oldNotification = this._byTag[tag]; - delete this._notifications[oldNotification.id]; - } - - this._byTag[tag] = notification; - }; - - cpmm.sendAsyncMessage("Notification:Save", { - origin: origin, - notification: notification - }); - }, - - get: function(origin, tag, callback) { - if (DEBUG) { debug("GET: " + tag); } - if (this._cached) { - this._fetchFromCache(tag, callback); - } else { - this._fetchFromDB(origin, tag, callback); - } - }, - - delete: function(origin, id) { - if (DEBUG) { debug("DELETE: " + id); } - var notification = this._notifications[id]; - if (notification) { - if (notification.tag) { - delete this._byTag[notification.tag]; - } - delete this._notifications[id]; - } - - cpmm.sendAsyncMessage("Notification:Delete", { - origin: origin, - id: id - }); - }, - - receiveMessage: function(message) { - switch (message.name) { - case "Notification:GetAll:Return:OK": - var request = this._requests[message.data.requestID]; - delete this._requests[message.data.requestID]; - this._populateCache(message.data.notifications); - this._fetchFromCache(request.tag, request.callback); - break; - - default: - if (DEBUG) debug("Unrecognized message: " + message.name); - break; - } - }, - - _fetchFromDB: function(origin, tag, callback) { - var request = { - origin: origin, - tag: tag, - callback: callback - }; - var requestID = this._requestCount++; - this._requests[requestID] = request; - cpmm.sendAsyncMessage("Notification:GetAll", { - origin: origin, - requestID: requestID - }); - }, - - _fetchFromCache: function(tag, callback) { - var notifications = []; - // If a tag was specified and we have a notification - // with this tag, return that. If no tag was specified - // simple return all stored notifications. - if (tag && this._byTag[tag]) { - notifications.push(this._byTag[tag]); - } else if (!tag) { - for (var id in this._notifications) { - notifications.push(this._notifications[id]); - } - } - - // Pass each notification back separately. - notifications.forEach(function(notification) { - try { - callback.handle(notification.id, - notification.title, - notification.dir, - notification.lang, - notification.body, - notification.tag, - notification.icon); - } catch (e) { - if (DEBUG) { debug("Error calling callback handle: " + e); } - } - }); - try { - callback.done(); - } catch (e) { - if (DEBUG) { debug("Error calling callback done: " + e); } - } - }, - - _populateCache: function(notifications) { - notifications.forEach(function(notification) { - this._notifications[notification.id] = notification; - if (notification.tag) { - this._byTag[notification.tag] = notification; - } - }.bind(this)); - this._cached = true; - }, - - classID : Components.ID(NOTIFICATIONSTORAGE_CID), - contractID : NOTIFICATIONSTORAGE_CONTRACTID, - QueryInterface: XPCOMUtils.generateQI([Ci.nsINotificationStorage, - Ci.nsIMessageListener]), -}; - - -this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NotificationStorage]); diff --git a/dom/src/notification/NotificationStorage.manifest b/dom/src/notification/NotificationStorage.manifest deleted file mode 100644 index 34c5c51388de..000000000000 --- a/dom/src/notification/NotificationStorage.manifest +++ /dev/null @@ -1,3 +0,0 @@ -# NotificationStorage.js -component {37f819b0-0b5c-11e3-8ffd-0800200c9a66} NotificationStorage.js -contract @mozilla.org/notificationStorage;1 {37f819b0-0b5c-11e3-8ffd-0800200c9a66} diff --git a/dom/src/notification/moz.build b/dom/src/notification/moz.build index 8687cb00cb98..f4644c861e26 100644 --- a/dom/src/notification/moz.build +++ b/dom/src/notification/moz.build @@ -6,15 +6,6 @@ MODULE = 'dom' -EXTRA_COMPONENTS += [ - 'NotificationStorage.js', - 'NotificationStorage.manifest', -] - -EXTRA_JS_MODULES += [ - 'NotificationDB.jsm' -] - EXPORTS.mozilla.dom += [ 'DesktopNotification.h', 'Notification.h', diff --git a/dom/src/storage/DOMStorageCache.cpp b/dom/src/storage/DOMStorageCache.cpp index 813e2a6fac5b..741d7299d524 100644 --- a/dom/src/storage/DOMStorageCache.cpp +++ b/dom/src/storage/DOMStorageCache.cpp @@ -75,12 +75,12 @@ NS_IMETHODIMP_(void) DOMStorageCacheBridge::Release(void) // DOMStorageCache DOMStorageCache::DOMStorageCache(const nsACString* aScope) -: mManager(nullptr) -, mScope(*aScope) +: mScope(*aScope) , mMonitor("DOMStorageCache") , mLoaded(false) , mLoadResult(NS_OK) , mInitialized(false) +, mPersistent(false) , mSessionOnlyDataSetActive(false) , mPreloadTelemetryRecorded(false) { @@ -128,15 +128,17 @@ DOMStorageCache::Init(DOMStorageManager* aManager, return; } - mManager = aManager; mInitialized = true; mPrincipal = aPrincipal; mPersistent = aPersistent; mQuotaScope = aQuotaScope.IsEmpty() ? mScope : aQuotaScope; if (mPersistent) { + mManager = aManager; Preload(); } + + mUsage = aManager->GetScopeUsage(mQuotaScope); } inline bool @@ -208,12 +210,8 @@ DOMStorageCache::ProcessUsageDelta(uint32_t aGetDataSetIndex, const int64_t aDel } // Now check eTLD+1 limit - GetDatabase(); - if (sDatabase) { - DOMStorageUsage* usage = sDatabase->GetScopeUsage(mQuotaScope); - if (!usage->CheckAndSetETLD1UsageDelta(aGetDataSetIndex, aDelta)) { - return false; - } + if (mUsage && !mUsage->CheckAndSetETLD1UsageDelta(aGetDataSetIndex, aDelta)) { + return false; } // Update size in our data set @@ -235,7 +233,6 @@ DOMStorageCache::Preload() } sDatabase->AsyncPreload(this); - sDatabase->GetScopeUsage(mQuotaScope); } namespace { // anon diff --git a/dom/src/storage/DOMStorageCache.h b/dom/src/storage/DOMStorageCache.h index 5492ae3ec5ea..5d75233aeaa4 100644 --- a/dom/src/storage/DOMStorageCache.h +++ b/dom/src/storage/DOMStorageCache.h @@ -20,6 +20,7 @@ namespace mozilla { namespace dom { class DOMStorage; +class DOMStorageUsage; class DOMStorageManager; class DOMStorageDBBridge; @@ -170,6 +171,10 @@ private: // Cache could potentially overlive the manager, hence the hard ref. nsRefPtr mManager; + // Reference to the usage counter object we check on for eTLD+1 quota limit. + // Obtained from the manager during initialization (Init method). + nsRefPtr mUsage; + // Timer that holds this cache alive for a while after it has been preloaded. nsCOMPtr mKeepAliveTimer; @@ -227,6 +232,8 @@ private: class DOMStorageUsageBridge { public: + NS_INLINE_DECL_THREADSAFE_REFCOUNTING(DOMStorageUsageBridge) + virtual ~DOMStorageUsageBridge() {} virtual const nsCString& Scope() = 0; diff --git a/dom/src/storage/DOMStorageDBThread.cpp b/dom/src/storage/DOMStorageDBThread.cpp index 3cdffa31bbbe..fec2f661f5a3 100644 --- a/dom/src/storage/DOMStorageDBThread.cpp +++ b/dom/src/storage/DOMStorageDBThread.cpp @@ -37,21 +37,6 @@ DOMStorageDBBridge::DOMStorageDBBridge() { } -DOMStorageUsage* -DOMStorageDBBridge::GetScopeUsage(const nsACString& aScope) -{ - DOMStorageUsage* usage; - if (mUsages.Get(aScope, &usage)) { - return usage; - } - - usage = new DOMStorageUsage(aScope); - AsyncGetUsage(usage); - mUsages.Put(aScope, usage); - - return usage; -} - DOMStorageDBThread::DOMStorageDBThread() : mThread(nullptr) diff --git a/dom/src/storage/DOMStorageDBThread.h b/dom/src/storage/DOMStorageDBThread.h index 7e930c1e7ed0..ed517b57fc5b 100644 --- a/dom/src/storage/DOMStorageDBThread.h +++ b/dom/src/storage/DOMStorageDBThread.h @@ -81,13 +81,6 @@ public: // Get the complete list of scopes having data virtual void GetScopesHavingData(InfallibleTArray* aScopes) = 0; - - // Returns object keeping usage cache for the scope. - DOMStorageUsage* GetScopeUsage(const nsACString& aScope); - -protected: - // Keeps usage cache objects for eTLD+1 scopes we have touched. - nsClassHashtable mUsages; }; // The implementation of the the database engine, this directly works @@ -157,7 +150,7 @@ public: friend class PendingOperations; OperationType mType; nsRefPtr mCache; - DOMStorageUsageBridge* mUsage; + nsRefPtr mUsage; nsString mKey; nsString mValue; nsCString mScope; diff --git a/dom/src/storage/DOMStorageIPC.cpp b/dom/src/storage/DOMStorageIPC.cpp index 569a45d4773f..b64ec456dd41 100644 --- a/dom/src/storage/DOMStorageIPC.cpp +++ b/dom/src/storage/DOMStorageIPC.cpp @@ -253,12 +253,7 @@ DOMStorageDBChild::RecvLoadDone(const nsCString& aScope, const nsresult& aRv) bool DOMStorageDBChild::RecvLoadUsage(const nsCString& aScope, const int64_t& aUsage) { - DOMStorageDBBridge* db = DOMStorageCache::GetDatabase(); - if (!db) { - return false; - } - - DOMStorageUsageBridge* scopeUsage = db->GetScopeUsage(aScope); + nsRefPtr scopeUsage = mManager->GetScopeUsage(aScope); scopeUsage->LoadUsage(aUsage); return true; } @@ -404,7 +399,7 @@ DOMStorageDBParent::RecvAsyncGetUsage(const nsCString& aScope) } // The object releases it self in LoadUsage method - UsageParentBridge* usage = new UsageParentBridge(this, aScope); + nsRefPtr usage = new UsageParentBridge(this, aScope); db->AsyncGetUsage(usage); return true; } @@ -733,7 +728,6 @@ DOMStorageDBParent::UsageParentBridge::LoadUsage(const int64_t aUsage) { nsRefPtr r = new UsageRunnable(mParent, mScope, aUsage); NS_DispatchToMainThread(r); - delete this; } } // ::dom diff --git a/dom/src/storage/DOMStorageManager.cpp b/dom/src/storage/DOMStorageManager.cpp index d8da757b9438..0ba950ba5d6e 100644 --- a/dom/src/storage/DOMStorageManager.cpp +++ b/dom/src/storage/DOMStorageManager.cpp @@ -269,6 +269,28 @@ DOMStorageManager::GetCache(const nsACString& aScope) const return entry->cache(); } +already_AddRefed +DOMStorageManager::GetScopeUsage(const nsACString& aScope) +{ + nsRefPtr usage; + if (mUsages.Get(aScope, &usage)) { + return usage.forget(); + } + + usage = new DOMStorageUsage(aScope); + + if (mType == LocalStorage) { + DOMStorageDBBridge* db = DOMStorageCache::StartDatabase(); + if (db) { + db->AsyncGetUsage(usage); + } + } + + mUsages.Put(aScope, usage); + + return usage.forget(); +} + already_AddRefed DOMStorageManager::PutCache(const nsACString& aScope, nsIPrincipal* aPrincipal) @@ -283,7 +305,7 @@ DOMStorageManager::PutCache(const nsACString& aScope, case SessionStorage: // Lifetime handled by the manager, don't persist entry->HardRef(); - cache->Init(nullptr, false, aPrincipal, quotaScope); + cache->Init(this, false, aPrincipal, quotaScope); break; case LocalStorage: diff --git a/dom/src/storage/DOMStorageManager.h b/dom/src/storage/DOMStorageManager.h index f6c3ee9819f4..36477d45e35b 100644 --- a/dom/src/storage/DOMStorageManager.h +++ b/dom/src/storage/DOMStorageManager.h @@ -13,6 +13,8 @@ #include "DOMStorageCache.h" #include "nsTHashtable.h" +#include "nsDataHashtable.h" +#include "nsHashKeys.h" namespace mozilla { namespace dom { @@ -35,6 +37,8 @@ public: static uint32_t GetQuota(); // Gets (but not ensures) cache for the given scope DOMStorageCache* GetCache(const nsACString& aScope) const; + // Returns object keeping usage cache for the scope. + already_AddRefed GetScopeUsage(const nsACString& aScope); protected: DOMStorageManager(nsPIDOMStorage::StorageType aType); @@ -97,6 +101,9 @@ private: void* aClosure); protected: + // Keeps usage cache objects for eTLD+1 scopes we have touched. + nsDataHashtable > mUsages; + friend class DOMStorageCache; // Releases cache since it is no longer referrered by any DOMStorage object. virtual void DropCache(DOMStorageCache* aCache); diff --git a/dom/tests/mochitest/moz.build b/dom/tests/mochitest/moz.build index 3dc79b5b1156..28c9c0495046 100644 --- a/dom/tests/mochitest/moz.build +++ b/dom/tests/mochitest/moz.build @@ -29,3 +29,7 @@ DIRS += [ if CONFIG['MOZ_GAMEPAD']: DIRS += ['gamepad'] +#needs IPC support, also tests do not run successfully in Firefox for now +#if CONFIG['MOZ_BUILD_APP'] != 'mobile': +# DIRS += ['notification'] + diff --git a/dom/tests/mochitest/notification/MockServices.js b/dom/tests/mochitest/notification/MockServices.js deleted file mode 100644 index 164cc7e9a91f..000000000000 --- a/dom/tests/mochitest/notification/MockServices.js +++ /dev/null @@ -1,81 +0,0 @@ -var MockServices = (function () { - "use strict"; - - const MOCK_ALERTS_CID = SpecialPowers.wrap(SpecialPowers.Components) - .ID("{48068bc2-40ab-4904-8afd-4cdfb3a385f3}"); - const ALERTS_SERVICE_CONTRACT_ID = "@mozilla.org/alerts-service;1"; - - const MOCK_SYSTEM_ALERTS_CID = SpecialPowers.wrap(SpecialPowers.Components) - .ID("{e86d888c-e41b-4b78-9104-2f2742a532de}"); - const SYSTEM_ALERTS_SERVICE_CONTRACT_ID = "@mozilla.org/system-alerts-service;1"; - - var registrar = SpecialPowers.wrap(SpecialPowers.Components).manager - .QueryInterface(SpecialPowers.Ci.nsIComponentRegistrar); - - var activeNotifications = Object.create(null); - - var mockAlertsService = { - showAlertNotification: function(imageUrl, title, text, textClickable, - cookie, alertListener, name) { - var listener = SpecialPowers.wrap(alertListener); - activeNotifications[name] = { - listener: listener, - cookie: cookie - }; - - // fake async alert show event - setTimeout(function () { - listener.observe(null, "alertshow", cookie); - }, 100); - - // ?? SpecialPowers.wrap(alertListener).observe(null, "alertclickcallback", cookie); - }, - - showAppNotification: function(imageUrl, title, text, textClickable, - manifestURL, alertListener, name) { - this.showAlertNotification(imageUrl, title, text, textClickable, "", alertListener, name); - }, - - closeAlert: function(name) { - var notification = activeNotifications[name]; - if (notification) { - notification.listener.observe(null, "alertfinished", notification.cookie); - delete activeNotifications[name]; - } - }, - - QueryInterface: function(aIID) { - if (SpecialPowers.wrap(aIID).equals(SpecialPowers.Ci.nsISupports) || - SpecialPowers.wrap(aIID).equals(SpecialPowers.Ci.nsIAlertsService)) { - return this; - } - throw SpecialPowers.Components.results.NS_ERROR_NO_INTERFACE; - }, - - createInstance: function(aOuter, aIID) { - if (aOuter != null) { - throw SpecialPowers.Components.results.NS_ERROR_NO_AGGREGATION; - } - return this.QueryInterface(aIID); - } - }; - mockAlertsService = SpecialPowers.wrapCallbackObject(mockAlertsService); - - // MockServices API - return { - register: function () { - registrar.registerFactory(MOCK_ALERTS_CID, "alerts service", - ALERTS_SERVICE_CONTRACT_ID, - mockAlertsService); - - registrar.registerFactory(MOCK_SYSTEM_ALERTS_CID, "system alerts service", - SYSTEM_ALERTS_SERVICE_CONTRACT_ID, - mockAlertsService); - }, - - unregister: function () { - registrar.unregisterFactory(MOCK_ALERTS_CID, mockAlertsService); - registrar.unregisterFactory(MOCK_SYSTEM_ALERTS_CID, mockAlertsService); - }, - }; -})(); diff --git a/dom/tests/mochitest/notification/NotificationTest.js b/dom/tests/mochitest/notification/NotificationTest.js deleted file mode 100644 index 871ec137a632..000000000000 --- a/dom/tests/mochitest/notification/NotificationTest.js +++ /dev/null @@ -1,73 +0,0 @@ -var NotificationTest = (function () { - "use strict"; - - function info(msg, name) { - SimpleTest.info("::Notification Tests::" + (name || ""), msg); - } - - function setup_testing_env() { - SimpleTest.waitForExplicitFinish(); - // turn on testing pref (used by notification.cpp, and mock the alerts - SpecialPowers.setBoolPref("notification.prompt.testing", true); - } - - function teardown_testing_env() { - SimpleTest.finish(); - } - - function executeTests(tests, callback) { - // context is `this` object in test functions - // it can be used to track data between tests - var context = {}; - - (function executeRemainingTests(remainingTests) { - if (!remainingTests.length) { - return callback(); - } - - var nextTest = remainingTests.shift(); - var finishTest = executeRemainingTests.bind(null, remainingTests); - var startTest = nextTest.call.bind(nextTest, context, finishTest); - - try { - startTest(); - // if no callback was defined for test function, - // we must manually invoke finish to continue - if (nextTest.length === 0) { - finishTest(); - } - } catch (e) { - ok(false, "Test threw exception!"); - finishTest(); - } - })(tests); - } - - // NotificationTest API - return { - run: function (tests, callback) { - setup_testing_env(); - - addLoadEvent(function () { - executeTests(tests, function () { - teardown_testing_env(); - callback && callback(); - }); - }); - }, - - allowNotifications: function () { - SpecialPowers.setBoolPref("notification.prompt.testing.allow", true); - }, - - denyNotifications: function () { - SpecialPowers.setBoolPref("notification.prompt.testing.allow", false); - }, - - clickNotification: function (notification) { - // TODO: how?? - }, - - info: info - }; -})(); diff --git a/dom/tests/mochitest/notification/desktop-notification/create_notification.html b/dom/tests/mochitest/notification/create_notification.html similarity index 100% rename from dom/tests/mochitest/notification/desktop-notification/create_notification.html rename to dom/tests/mochitest/notification/create_notification.html diff --git a/dom/tests/mochitest/notification/desktop-notification/moz.build b/dom/tests/mochitest/notification/desktop-notification/moz.build deleted file mode 100644 index 895d11993cfb..000000000000 --- a/dom/tests/mochitest/notification/desktop-notification/moz.build +++ /dev/null @@ -1,6 +0,0 @@ -# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- -# vim: set filetype=python: -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - diff --git a/dom/tests/mochitest/notification/mochitest.ini b/dom/tests/mochitest/notification/mochitest.ini index a3b5890d5947..64766ae948d0 100644 --- a/dom/tests/mochitest/notification/mochitest.ini +++ b/dom/tests/mochitest/notification/mochitest.ini @@ -1,7 +1,10 @@ [DEFAULT] support-files = - MockServices.js - NotificationTest.js + create_notification.html + notification_common.js -[test_notification_basics.html] -[test_notification_storage.html] +[test_basic_notification.html] +[test_basic_notification_click.html] +[test_leak_windowClose.html] +[test_notification_tag.html] +[test_web_notifications.html] diff --git a/dom/tests/mochitest/notification/desktop-notification/notification_common.js b/dom/tests/mochitest/notification/notification_common.js similarity index 100% rename from dom/tests/mochitest/notification/desktop-notification/notification_common.js rename to dom/tests/mochitest/notification/notification_common.js diff --git a/dom/tests/mochitest/notification/desktop-notification/test_basic_notification.html b/dom/tests/mochitest/notification/test_basic_notification.html similarity index 100% rename from dom/tests/mochitest/notification/desktop-notification/test_basic_notification.html rename to dom/tests/mochitest/notification/test_basic_notification.html diff --git a/dom/tests/mochitest/notification/desktop-notification/test_basic_notification_click.html b/dom/tests/mochitest/notification/test_basic_notification_click.html similarity index 100% rename from dom/tests/mochitest/notification/desktop-notification/test_basic_notification_click.html rename to dom/tests/mochitest/notification/test_basic_notification_click.html diff --git a/dom/tests/mochitest/notification/desktop-notification/test_leak_windowClose.html b/dom/tests/mochitest/notification/test_leak_windowClose.html similarity index 100% rename from dom/tests/mochitest/notification/desktop-notification/test_leak_windowClose.html rename to dom/tests/mochitest/notification/test_leak_windowClose.html diff --git a/dom/tests/mochitest/notification/test_notification_basics.html b/dom/tests/mochitest/notification/test_notification_basics.html deleted file mode 100644 index dc7e74e5c043..000000000000 --- a/dom/tests/mochitest/notification/test_notification_basics.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - Notification Basics - - - - - - -

- -

-
-
-
diff --git a/dom/tests/mochitest/notification/test_notification_storage.html b/dom/tests/mochitest/notification/test_notification_storage.html
deleted file mode 100644
index abc5d7702e58..000000000000
--- a/dom/tests/mochitest/notification/test_notification_storage.html
+++ /dev/null
@@ -1,132 +0,0 @@
-
-
-
-  Notification Basics
-  
-  
-  
-  
-
-
-

- -

-
-
-
diff --git a/dom/tests/mochitest/notification/desktop-notification/test_notification_tag.html b/dom/tests/mochitest/notification/test_notification_tag.html
similarity index 100%
rename from dom/tests/mochitest/notification/desktop-notification/test_notification_tag.html
rename to dom/tests/mochitest/notification/test_notification_tag.html
diff --git a/dom/tests/mochitest/notification/desktop-notification/test_system_principal.xul b/dom/tests/mochitest/notification/test_system_principal.xul
similarity index 100%
rename from dom/tests/mochitest/notification/desktop-notification/test_system_principal.xul
rename to dom/tests/mochitest/notification/test_system_principal.xul
diff --git a/dom/tests/mochitest/notification/test_web_notifications.html b/dom/tests/mochitest/notification/test_web_notifications.html
new file mode 100644
index 000000000000..681cf76cb247
--- /dev/null
+++ b/dom/tests/mochitest/notification/test_web_notifications.html
@@ -0,0 +1,100 @@
+
+
+
+
+  Bug 782211
+  
+  
+  
+
+
+Bug 782211
+

+ +
+
+ + + diff --git a/dom/webidl/Notification.webidl b/dom/webidl/Notification.webidl index cc39d0ed1c25..fef3f993315d 100644 --- a/dom/webidl/Notification.webidl +++ b/dom/webidl/Notification.webidl @@ -19,9 +19,6 @@ interface Notification : EventTarget { [Throws] static void requestPermission(optional NotificationPermissionCallback permissionCallback); - [Throws] - static Promise get(optional GetNotificationOptions filter); - attribute EventHandler onclick; attribute EventHandler onshow; @@ -55,12 +52,8 @@ dictionary NotificationOptions { NotificationDirection dir = "auto"; DOMString lang = ""; DOMString body = ""; - DOMString tag = ""; - DOMString icon = ""; -}; - -dictionary GetNotificationOptions { DOMString tag; + DOMString icon = ""; }; enum NotificationPermission { diff --git a/gfx/2d/QuartzSupport.mm b/gfx/2d/QuartzSupport.mm index 141587e6af13..d64b9fac0208 100644 --- a/gfx/2d/QuartzSupport.mm +++ b/gfx/2d/QuartzSupport.mm @@ -458,26 +458,20 @@ MacIOSurface::CGLTexImageIOSurface2D(void *c) } CGColorSpaceRef CreateSystemColorSpace() { - CMProfileRef system_profile = nullptr; - CGColorSpaceRef cspace = nullptr; - - if (::CMGetSystemProfile(&system_profile) == noErr) { - // Create a colorspace with the systems profile - cspace = ::CGColorSpaceCreateWithPlatformColorSpace(system_profile); - ::CMCloseProfile(system_profile); - } else { - // Default to generic - cspace = ::CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); - } - - return cspace; + CGColorSpaceRef cspace = ::CGDisplayCopyColorSpace(::CGMainDisplayID()); + if (!cspace) { + cspace = ::CGColorSpaceCreateDeviceRGB(); + } + return cspace; } CGContextRef MacIOSurface::CreateIOSurfaceContext() { + CGColorSpaceRef cspace = CreateSystemColorSpace(); CGContextRef ref = MacIOSurfaceLib::IOSurfaceContextCreate(mIOSurfacePtr, GetDevicePixelWidth(), GetDevicePixelHeight(), - 8, 32, CreateSystemColorSpace(), 0x2002); + 8, 32, cspace, 0x2002); + ::CGColorSpaceRelease(cspace); return ref; } @@ -639,9 +633,7 @@ nsresult nsCARenderer::SetupRenderer(void *aCALayer, int aWidth, int aHeight, dataProvider, nullptr, true, kCGRenderingIntentDefault); ::CGDataProviderRelease(dataProvider); - if (colorSpace) { - ::CGColorSpaceRelease(colorSpace); - } + ::CGColorSpaceRelease(colorSpace); if (!mCGImage) { mUnsupportedWidth = aWidth; mUnsupportedHeight = aHeight; diff --git a/js/src/TraceLogging.cpp b/js/src/TraceLogging.cpp index 80b07fbe26b8..82542774fd0c 100644 --- a/js/src/TraceLogging.cpp +++ b/js/src/TraceLogging.cpp @@ -90,17 +90,17 @@ const char* const TraceLogging::typeName[] = { "e,b", // engine baseline "e,o" // engine ionmonkey }; -TraceLogging* TraceLogging::loggers[] = {NULL, NULL, NULL}; +TraceLogging* TraceLogging::loggers[] = {nullptr, nullptr, nullptr}; bool TraceLogging::atexitSet = false; uint64_t TraceLogging::startupTime = 0; TraceLogging::TraceLogging(Logger id) : nextTextId(1), - entries(NULL), + entries(nullptr), curEntry(0), numEntries(1000000), fileno(0), - out(NULL), + out(nullptr), id(id) { textMap.init(); @@ -111,12 +111,12 @@ TraceLogging::~TraceLogging() if (entries) { flush(); free(entries); - entries = NULL; + entries = nullptr; } if (out) { fclose(out); - out = NULL; + out = nullptr; } } @@ -137,7 +137,7 @@ TraceLogging::grow() } void -TraceLogging::log(Type type, const char* text /* = NULL */, unsigned int number /* = 0 */) +TraceLogging::log(Type type, const char* text /* = nullptr */, unsigned int number /* = 0 */) { uint64_t now = rdtsc() - startupTime; @@ -149,7 +149,7 @@ TraceLogging::log(Type type, const char* text /* = NULL */, unsigned int number } uint32_t textId = 0; - char *text_ = NULL; + char *text_ = nullptr; if (text) { TextHashMap::AddPtr p = textMap.lookupForAdd(text); @@ -248,9 +248,9 @@ TraceLogging::flush() exit(-1); } - if (entries[i].text() != NULL) { + if (entries[i].text() != nullptr) { free(entries[i].text()); - entries[i].text_ = NULL; + entries[i].text_ = nullptr; } } curEntry = 0; @@ -279,7 +279,7 @@ TraceLogging::releaseLoggers() continue; delete loggers[i]; - loggers[i] = NULL; + loggers[i] = nullptr; } } diff --git a/js/src/TraceLogging.h b/js/src/TraceLogging.h index 3a3ad82f8cea..0b93542738f8 100644 --- a/js/src/TraceLogging.h +++ b/js/src/TraceLogging.h @@ -102,7 +102,7 @@ class TraceLogging TraceLogging(Logger id); ~TraceLogging(); - void log(Type type, const char* text = NULL, unsigned int number = 0); + void log(Type type, const char* text = nullptr, unsigned int number = 0); void log(Type type, const JS::CompileOptions &options); void log(Type type, JSScript* script); void log(const char* log); diff --git a/js/src/builtin/TestingFunctions.cpp b/js/src/builtin/TestingFunctions.cpp index f9b585414865..487e418e82e3 100644 --- a/js/src/builtin/TestingFunctions.cpp +++ b/js/src/builtin/TestingFunctions.cpp @@ -830,7 +830,7 @@ DumpHeapComplete(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); DumpHeapNurseryBehaviour nurseryBehaviour = js::IgnoreNurseryObjects; - FILE *dumpFile = NULL; + FILE *dumpFile = nullptr; unsigned i = 0; if (argc > i) { diff --git a/js/src/gc/Nursery.cpp b/js/src/gc/Nursery.cpp index d86ccdc05fe1..d6252bc8b130 100644 --- a/js/src/gc/Nursery.cpp +++ b/js/src/gc/Nursery.cpp @@ -97,6 +97,9 @@ js::Nursery::allocate(size_t size) { JS_ASSERT(!runtime()->isHeapBusy()); + /* Ensure there's enough space to replace the contents with a RelocationOverlay. */ + JS_ASSERT(size >= sizeof(RelocationOverlay)); + if (position() + size > currentEnd()) { if (currentChunk_ + 1 == numActiveChunks_) return nullptr; diff --git a/js/src/jit-test/tests/basic/bug923390.js b/js/src/jit-test/tests/basic/bug923390.js new file mode 100644 index 000000000000..756d4e9d5e55 --- /dev/null +++ b/js/src/jit-test/tests/basic/bug923390.js @@ -0,0 +1,3 @@ +if (getpda) { + getpda(); +} diff --git a/js/src/jit/AsmJS.cpp b/js/src/jit/AsmJS.cpp index beb11b624678..b786e2acb62c 100644 --- a/js/src/jit/AsmJS.cpp +++ b/js/src/jit/AsmJS.cpp @@ -5081,7 +5081,7 @@ class ParallelCompilationGuard { WorkerThreadState *parallelState_; public: - ParallelCompilationGuard() : parallelState_(NULL) {} + ParallelCompilationGuard() : parallelState_(nullptr) {} ~ParallelCompilationGuard() { if (parallelState_) { JS_ASSERT(parallelState_->asmJSCompilationInProgress == true); diff --git a/js/src/jit/IonBuilder.cpp b/js/src/jit/IonBuilder.cpp index 9ad69d6c55b3..7e8620d1023e 100644 --- a/js/src/jit/IonBuilder.cpp +++ b/js/src/jit/IonBuilder.cpp @@ -7777,7 +7777,7 @@ IonBuilder::freezePropTypeSets(types::TemporaryTypeSet *types, continue; // Walk the prototype chain. Everyone has to have the property, since we - // just checked, so propSet cannot be NULL. + // just checked, so propSet cannot be nullptr. while (true) { types::HeapTypeSetKey property = type->property(NameToId(name)); JS_ALWAYS_TRUE(!property.notEmpty(constraints())); diff --git a/js/src/jit/IonBuilder.h b/js/src/jit/IonBuilder.h index 21fafd790a89..b41f8405d9d9 100644 --- a/js/src/jit/IonBuilder.h +++ b/js/src/jit/IonBuilder.h @@ -687,7 +687,7 @@ class IonBuilder : public MIRGenerator } bool isInlineBuilder() const { - return callerBuilder_ != NULL; + return callerBuilder_ != nullptr; } private: diff --git a/js/src/jit/RangeAnalysis.h b/js/src/jit/RangeAnalysis.h index bf6446df8752..cbe482e6b9f3 100644 --- a/js/src/jit/RangeAnalysis.h +++ b/js/src/jit/RangeAnalysis.h @@ -273,8 +273,8 @@ class Range : public TempObject { // Construct a range from the given raw values. Range(int32_t l, bool lb, int32_t h, bool hb, bool f, uint16_t e) - : symbolicLower_(NULL), - symbolicUpper_(NULL) + : symbolicLower_(nullptr), + symbolicUpper_(nullptr) { rawInitialize(l, lb, h, hb, f, e); } diff --git a/js/src/jsalloc.h b/js/src/jsalloc.h index 451ee3e745ef..03b6b569e18a 100644 --- a/js/src/jsalloc.h +++ b/js/src/jsalloc.h @@ -53,14 +53,14 @@ class TempAllocPolicy void *malloc_(size_t bytes) { void *p = js_malloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } void *calloc_(size_t bytes) { void *p = js_calloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } diff --git a/js/src/jsanalyze.cpp b/js/src/jsanalyze.cpp index d3b9b2c1626d..ebde6016c5e4 100644 --- a/js/src/jsanalyze.cpp +++ b/js/src/jsanalyze.cpp @@ -440,7 +440,7 @@ ScriptAnalysis::analyzeLifetimes(JSContext *cx) } unsigned savedCount = 0; - LoopAnalysis *loop = NULL; + LoopAnalysis *loop = nullptr; uint32_t offset = script_->length - 1; while (offset < script_->length) { @@ -525,7 +525,7 @@ ScriptAnalysis::analyzeLifetimes(JSContext *cx) setOOM(cx); return; } - var.saved = NULL; + var.saved = nullptr; saved[i--] = saved[--savedCount]; } savedCount = 0; @@ -617,7 +617,7 @@ ScriptAnalysis::analyzeLifetimes(JSContext *cx) setOOM(cx); return; } - var.saved = NULL; + var.saved = nullptr; saved[i--] = saved[--savedCount]; } else if (loop && !var.savedEnd) { /* @@ -680,7 +680,7 @@ ScriptAnalysis::addVariable(JSContext *cx, LifetimeVariable &var, unsigned offse setOOM(cx); return; } - var.saved = NULL; + var.saved = nullptr; } } @@ -730,7 +730,7 @@ ScriptAnalysis::killVariable(JSContext *cx, LifetimeVariable &var, unsigned offs } else { var.saved = var.lifetime; var.savedEnd = 0; - var.lifetime = NULL; + var.lifetime = nullptr; saved[savedCount++] = &var; } @@ -1510,7 +1510,7 @@ ScriptAnalysis::freezeNewValues(JSContext *cx, uint32_t offset) Bytecode &code = getCode(offset); Vector *pending = code.pendingValues; - code.pendingValues = NULL; + code.pendingValues = nullptr; unsigned count = pending->length(); if (count == 0) { diff --git a/js/src/jsanalyze.h b/js/src/jsanalyze.h index 6ff82c6421d2..bc6e6efa2c28 100644 --- a/js/src/jsanalyze.h +++ b/js/src/jsanalyze.h @@ -336,7 +336,7 @@ struct LifetimeVariable return segment; segment = segment->next; } - return NULL; + return nullptr; } /* diff --git a/js/src/jsapi-tests/selfTest.cpp b/js/src/jsapi-tests/selfTest.cpp index b78e265378fc..0d25d197e5e5 100644 --- a/js/src/jsapi-tests/selfTest.cpp +++ b/js/src/jsapi-tests/selfTest.cpp @@ -21,7 +21,7 @@ END_TEST(selfTest_NaNsAreSame) BEGIN_TEST(selfTest_globalHasNoParent) { - CHECK(JS_GetParent(global) == NULL); + CHECK(JS_GetParent(global) == nullptr); return true; } END_TEST(selfTest_globalHasNoParent) diff --git a/js/src/jsapi-tests/testAddPropertyPropcache.cpp b/js/src/jsapi-tests/testAddPropertyPropcache.cpp index fd8446b522c3..dfe750e34f1e 100644 --- a/js/src/jsapi-tests/testAddPropertyPropcache.cpp +++ b/js/src/jsapi-tests/testAddPropertyPropcache.cpp @@ -33,13 +33,13 @@ const JSClass addPropertyClass = { BEGIN_TEST(testAddPropertyHook) { - JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL)); + JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr)); CHECK(obj); JS::RootedValue proto(cx, OBJECT_TO_JSVAL(obj)); - JS_InitClass(cx, global, obj, &addPropertyClass, NULL, 0, NULL, NULL, NULL, - NULL); + JS_InitClass(cx, global, obj, &addPropertyClass, nullptr, 0, nullptr, nullptr, nullptr, + nullptr); - obj = JS_NewArrayObject(cx, 0, NULL); + obj = JS_NewArrayObject(cx, 0, nullptr); CHECK(obj); JS::RootedValue arr(cx, OBJECT_TO_JSVAL(obj)); @@ -48,7 +48,7 @@ BEGIN_TEST(testAddPropertyHook) JSPROP_ENUMERATE)); for (int i = 0; i < expectedCount; ++i) { - obj = JS_NewObject(cx, &addPropertyClass, NULL, NULL); + obj = JS_NewObject(cx, &addPropertyClass, nullptr, nullptr); CHECK(obj); JS::RootedValue vobj(cx, OBJECT_TO_JSVAL(obj)); JS::RootedObject arrObj(cx, JSVAL_TO_OBJECT(arr)); diff --git a/js/src/jsapi-tests/testArrayBuffer.cpp b/js/src/jsapi-tests/testArrayBuffer.cpp index 4a6b899d1c14..d9fa877dbf4e 100644 --- a/js/src/jsapi-tests/testArrayBuffer.cpp +++ b/js/src/jsapi-tests/testArrayBuffer.cpp @@ -46,7 +46,7 @@ BEGIN_TEST(testArrayBuffer_bug720949_steal) // Modifying the underlying data should update the value returned through the view uint8_t *data = JS_GetArrayBufferData(obj); - CHECK(data != NULL); + CHECK(data != nullptr); *reinterpret_cast(data) = MAGIC_VALUE_2; CHECK(JS_GetElement(cx, view, 0, &v)); CHECK_SAME(v, INT_TO_JSVAL(MAGIC_VALUE_2)); @@ -54,8 +54,8 @@ BEGIN_TEST(testArrayBuffer_bug720949_steal) // Steal the contents void *contents; CHECK(JS_StealArrayBufferContents(cx, obj, &contents, &data)); - CHECK(contents != NULL); - CHECK(data != NULL); + CHECK(contents != nullptr); + CHECK(data != nullptr); // Check that the original ArrayBuffer is neutered CHECK_EQUAL(JS_GetArrayBufferByteLength(obj), 0); @@ -78,11 +78,11 @@ BEGIN_TEST(testArrayBuffer_bug720949_steal) data = JS_GetArrayBufferData(obj); JS::RootedObject dstview(cx, JS_NewInt32ArrayWithBuffer(cx, dst, 0, -1)); - CHECK(dstview != NULL); + CHECK(dstview != nullptr); CHECK_EQUAL(JS_GetArrayBufferByteLength(dst), size); data = JS_GetArrayBufferData(dst); - CHECK(data != NULL); + CHECK(data != nullptr); CHECK_EQUAL(*reinterpret_cast(data), MAGIC_VALUE_2); CHECK(JS_GetElement(cx, dstview, 0, &v)); CHECK_SAME(v, INT_TO_JSVAL(MAGIC_VALUE_2)); @@ -105,7 +105,7 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList) // No views buffer = JS_NewArrayBuffer(cx, 2000); - buffer = NULL; + buffer = nullptr; GC(cx); // One view. @@ -115,15 +115,15 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList) void *contents; uint8_t *data; CHECK(JS_StealArrayBufferContents(cx, buffer, &contents, &data)); - CHECK(contents != NULL); - CHECK(data != NULL); - JS_free(NULL, contents); + CHECK(contents != nullptr); + CHECK(data != nullptr); + JS_free(nullptr, contents); GC(cx); CHECK(isNeutered(view)); CHECK(isNeutered(buffer)); - view = NULL; + view = nullptr; GC(cx); - buffer = NULL; + buffer = nullptr; GC(cx); } @@ -135,7 +135,7 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList) JS::RootedObject view2(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200)); // Remove, re-add a view - view2 = NULL; + view2 = nullptr; GC(cx); view2 = JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200); @@ -143,19 +143,19 @@ BEGIN_TEST(testArrayBuffer_bug720949_viewList) void *contents; uint8_t *data; CHECK(JS_StealArrayBufferContents(cx, buffer, &contents, &data)); - CHECK(contents != NULL); - CHECK(data != NULL); - JS_free(NULL, contents); + CHECK(contents != nullptr); + CHECK(data != nullptr); + JS_free(nullptr, contents); CHECK(isNeutered(view1)); CHECK(isNeutered(view2)); CHECK(isNeutered(buffer)); - view1 = NULL; + view1 = nullptr; GC(cx); - view2 = NULL; + view2 = nullptr; GC(cx); - buffer = NULL; + buffer = nullptr; GC(cx); } diff --git a/js/src/jsapi-tests/testBindCallable.cpp b/js/src/jsapi-tests/testBindCallable.cpp index ac27c1c2a865..b8ded16fd593 100644 --- a/js/src/jsapi-tests/testBindCallable.cpp +++ b/js/src/jsapi-tests/testBindCallable.cpp @@ -20,7 +20,8 @@ BEGIN_TEST(test_BindCallable) CHECK(newCallable); JS::RootedValue retval(cx); - bool called = JS_CallFunctionValue(cx, NULL, OBJECT_TO_JSVAL(newCallable), 0, NULL, retval.address()); + bool called = JS_CallFunctionValue(cx, nullptr, OBJECT_TO_JSVAL(newCallable), 0, nullptr, + retval.address()); CHECK(called); CHECK(JSVAL_IS_INT(retval)); diff --git a/js/src/jsapi-tests/testBug604087.cpp b/js/src/jsapi-tests/testBug604087.cpp index 778c5e1fb4c5..58c788a6e3ac 100644 --- a/js/src/jsapi-tests/testBug604087.cpp +++ b/js/src/jsapi-tests/testBug604087.cpp @@ -38,7 +38,7 @@ wrap(JSContext *cx, JS::HandleObject toWrap, JS::HandleObject target) JSAutoCompartment ac(cx, target); JS::RootedObject wrapper(cx, toWrap); if (!JS_WrapObject(cx, wrapper.address())) - return NULL; + return nullptr; return wrapper; } @@ -67,9 +67,9 @@ BEGIN_TEST(testBug604087) { JS::RootedObject outerObj(cx, js::Wrapper::New(cx, global, global->getProto(), global, &OuterWrapper::singleton)); - JS::RootedObject compartment2(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook)); - JS::RootedObject compartment3(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook)); - JS::RootedObject compartment4(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook)); + JS::RootedObject compartment2(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook)); + JS::RootedObject compartment3(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook)); + JS::RootedObject compartment4(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook)); JS::RootedObject c2wrapper(cx, wrap(cx, outerObj, compartment2)); CHECK(c2wrapper); @@ -82,7 +82,7 @@ BEGIN_TEST(testBug604087) JS::RootedObject c4wrapper(cx, wrap(cx, outerObj, compartment4)); CHECK(c4wrapper); c4wrapper->as().setExtra(0, js::Int32Value(4)); - compartment4 = c4wrapper = NULL; + compartment4 = c4wrapper = nullptr; JS::RootedObject next(cx); { diff --git a/js/src/jsapi-tests/testCallNonGenericMethodOnProxy.cpp b/js/src/jsapi-tests/testCallNonGenericMethodOnProxy.cpp index 4c390e96b5b8..bc9dfc612cf6 100644 --- a/js/src/jsapi-tests/testCallNonGenericMethodOnProxy.cpp +++ b/js/src/jsapi-tests/testCallNonGenericMethodOnProxy.cpp @@ -44,10 +44,10 @@ CustomMethod(JSContext *cx, unsigned argc, Value *vp) BEGIN_TEST(test_CallNonGenericMethodOnProxy) { // Create the first global object and compartment - JS::RootedObject globalA(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook)); + JS::RootedObject globalA(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook)); CHECK(globalA); - JS::RootedObject customA(cx, JS_NewObject(cx, &CustomClass, NULL, NULL)); + JS::RootedObject customA(cx, JS_NewObject(cx, &CustomClass, nullptr, nullptr)); CHECK(customA); JS_SetReservedSlot(customA, CUSTOM_SLOT, Int32Value(17)); @@ -55,17 +55,17 @@ BEGIN_TEST(test_CallNonGenericMethodOnProxy) CHECK(customMethodA); JS::RootedValue rval(cx); - CHECK(JS_CallFunction(cx, customA, customMethodA, 0, NULL, rval.address())); + CHECK(JS_CallFunction(cx, customA, customMethodA, 0, nullptr, rval.address())); CHECK_SAME(rval, Int32Value(17)); // Now create the second global object and compartment... { - JS::RootedObject globalB(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook)); + JS::RootedObject globalB(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook)); CHECK(globalB); // ...and enter it. JSAutoCompartment enter(cx, globalB); - JS::RootedObject customB(cx, JS_NewObject(cx, &CustomClass, NULL, NULL)); + JS::RootedObject customB(cx, JS_NewObject(cx, &CustomClass, nullptr, nullptr)); CHECK(customB); JS_SetReservedSlot(customB, CUSTOM_SLOT, Int32Value(42)); @@ -73,14 +73,14 @@ BEGIN_TEST(test_CallNonGenericMethodOnProxy) CHECK(customMethodB); JS::RootedValue rval(cx); - CHECK(JS_CallFunction(cx, customB, customMethodB, 0, NULL, rval.address())); + CHECK(JS_CallFunction(cx, customB, customMethodB, 0, nullptr, rval.address())); CHECK_SAME(rval, Int32Value(42)); JS::RootedObject wrappedCustomA(cx, customA); CHECK(JS_WrapObject(cx, wrappedCustomA.address())); JS::RootedValue rval2(cx); - CHECK(JS_CallFunction(cx, wrappedCustomA, customMethodB, 0, NULL, rval2.address())); + CHECK(JS_CallFunction(cx, wrappedCustomA, customMethodB, 0, nullptr, rval2.address())); CHECK_SAME(rval, Int32Value(42)); } diff --git a/js/src/jsapi-tests/testChromeBuffer.cpp b/js/src/jsapi-tests/testChromeBuffer.cpp index 0cb825d3a363..091abd636a38 100644 --- a/js/src/jsapi-tests/testChromeBuffer.cpp +++ b/js/src/jsapi-tests/testChromeBuffer.cpp @@ -22,8 +22,8 @@ const JSClass global_class = { JS_ConvertStub }; -JSObject *trusted_glob = NULL; -JSObject *trusted_fun = NULL; +JSObject *trusted_glob = nullptr; +JSObject *trusted_fun = nullptr; bool CallTrusted(JSContext *cx, unsigned argc, jsval *vp) @@ -34,8 +34,8 @@ CallTrusted(JSContext *cx, unsigned argc, jsval *vp) bool ok = false; { JSAutoCompartment ac(cx, trusted_glob); - ok = JS_CallFunctionValue(cx, NULL, JS::ObjectValue(*trusted_fun), - 0, NULL, vp); + ok = JS_CallFunctionValue(cx, nullptr, JS::ObjectValue(*trusted_fun), + 0, nullptr, vp); } JS_RestoreFrameChain(cx); return ok; @@ -89,7 +89,7 @@ BEGIN_TEST(testChromeBuffer) bytes, strlen(bytes), "", 0)); JS::RootedValue rval(cx); - CHECK(JS_CallFunction(cx, NULL, fun, 1, v.address(), rval.address())); + CHECK(JS_CallFunction(cx, nullptr, fun, 1, v.address(), rval.address())); CHECK(JSVAL_TO_INT(rval) == 100); } @@ -126,7 +126,7 @@ BEGIN_TEST(testChromeBuffer) bytes, strlen(bytes), "", 0)); JS::RootedValue rval(cx); - CHECK(JS_CallFunction(cx, NULL, fun, 1, v.address(), rval.address())); + CHECK(JS_CallFunction(cx, nullptr, fun, 1, v.address(), rval.address())); bool match; CHECK(JS_StringEqualsAscii(cx, JSVAL_TO_STRING(rval), "From trusted: InternalError: too much recursion", &match)); CHECK(match); @@ -142,8 +142,8 @@ BEGIN_TEST(testChromeBuffer) const char *bytes = "return 42"; JS::HandleObject global = JS::HandleObject::fromMarkedLocation(&trusted_glob); CHECK(fun = JS_CompileFunctionForPrincipals(cx, global, &system_principals, - "trusted", 0, NULL, bytes, strlen(bytes), - "", 0)); + "trusted", 0, nullptr, + bytes, strlen(bytes), "", 0)); trusted_fun = JS_GetFunctionObject(fun); } @@ -161,7 +161,7 @@ BEGIN_TEST(testChromeBuffer) JS::RootedValue arg(cx, JS::ObjectValue(*callTrusted)); JS::RootedValue rval(cx); - CHECK(JS_CallFunction(cx, NULL, fun, 1, arg.address(), rval.address())); + CHECK(JS_CallFunction(cx, nullptr, fun, 1, arg.address(), rval.address())); CHECK(JSVAL_TO_INT(rval) == 42); } diff --git a/js/src/jsapi-tests/testClassGetter.cpp b/js/src/jsapi-tests/testClassGetter.cpp index af0757ec6580..1e7b70e307da 100644 --- a/js/src/jsapi-tests/testClassGetter.cpp +++ b/js/src/jsapi-tests/testClassGetter.cpp @@ -56,14 +56,14 @@ static const JSFunctionSpec ptestFunctions[] = { BEGIN_TEST(testClassGetter_isCalled) { - CHECK(JS_InitClass(cx, global, NULL, &ptestClass, PTest, 0, - NULL, ptestFunctions, NULL, NULL)); + CHECK(JS_InitClass(cx, global, nullptr, &ptestClass, PTest, 0, + nullptr, ptestFunctions, nullptr, nullptr)); EXEC("function check() { var o = new PTest(); o.test_fn(); o.test_value1; o.test_value2; o.test_value1; }"); for (int i = 1; i < 9; i++) { JS::RootedValue rval(cx); - CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK_SAME(INT_TO_JSVAL(called_test_fn), INT_TO_JSVAL(i)); CHECK_SAME(INT_TO_JSVAL(called_test_prop_get), INT_TO_JSVAL(4 * i)); } diff --git a/js/src/jsapi-tests/testCloneScript.cpp b/js/src/jsapi-tests/testCloneScript.cpp index d122eb8d35f8..72c440157c52 100644 --- a/js/src/jsapi-tests/testCloneScript.cpp +++ b/js/src/jsapi-tests/testCloneScript.cpp @@ -33,7 +33,8 @@ BEGIN_TEST(test_cloneScript) { JSAutoCompartment a(cx, A); JSFunction *fun; - CHECK(fun = JS_CompileFunction(cx, A, "f", 0, NULL, source, strlen(source), __FILE__, 1)); + CHECK(fun = JS_CompileFunction(cx, A, "f", 0, nullptr, source, strlen(source), + __FILE__, 1)); CHECK(obj = JS_GetFunctionObject(fun)); } diff --git a/js/src/jsapi-tests/testConservativeGC.cpp b/js/src/jsapi-tests/testConservativeGC.cpp index 0a6bcf446062..be33d5dd6cdb 100644 --- a/js/src/jsapi-tests/testConservativeGC.cpp +++ b/js/src/jsapi-tests/testConservativeGC.cpp @@ -72,7 +72,7 @@ BEGIN_TEST(testDerivedValues) JS::Anchor str_anchor(str); static const jschar expected[] = { 'o', 'n', 'c', 'e' }; const jschar *ch = JS_GetStringCharsZ(cx, str); - str = NULL; + str = nullptr; /* Do a lot of allocation and collection. */ for (int i = 0; i < 3; i++) { diff --git a/js/src/jsapi-tests/testCustomIterator.cpp b/js/src/jsapi-tests/testCustomIterator.cpp index 9dd045f6ca90..b37b8ceb41b9 100644 --- a/js/src/jsapi-tests/testCustomIterator.cpp +++ b/js/src/jsapi-tests/testCustomIterator.cpp @@ -19,11 +19,11 @@ IterNext(JSContext *cx, unsigned argc, jsval *vp) static JSObject * IterHook(JSContext *cx, JS::HandleObject obj, bool keysonly) { - JS::RootedObject iterObj(cx, JS_NewObject(cx, NULL, NULL, NULL)); + JS::RootedObject iterObj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr)); if (!iterObj) - return NULL; + return nullptr; if (!JS_DefineFunction(cx, iterObj, "next", IterNext, 0, 0)) - return NULL; + return nullptr; return iterObj; } @@ -37,15 +37,15 @@ const js::Class HasCustomIterClass = { JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, - NULL, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ - NULL, /* mark */ + nullptr, + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ + nullptr, /* mark */ { - NULL, /* outerObject */ - NULL, /* innerObject */ + nullptr, /* outerObject */ + nullptr, /* innerObject */ IterHook, false /* isWrappedNative */ } @@ -63,8 +63,8 @@ IterClassConstructor(JSContext *cx, unsigned argc, jsval *vp) BEGIN_TEST(testCustomIterator_bug612523) { - CHECK(JS_InitClass(cx, global, NULL, Jsvalify(&HasCustomIterClass), - IterClassConstructor, 0, NULL, NULL, NULL, NULL)); + CHECK(JS_InitClass(cx, global, nullptr, Jsvalify(&HasCustomIterClass), + IterClassConstructor, 0, nullptr, nullptr, nullptr, nullptr)); JS::RootedValue result(cx); EVAL("var o = new HasCustomIter(); \n" diff --git a/js/src/jsapi-tests/testDebugger.cpp b/js/src/jsapi-tests/testDebugger.cpp index b5a2744ca139..4099e195ff51 100644 --- a/js/src/jsapi-tests/testDebugger.cpp +++ b/js/src/jsapi-tests/testDebugger.cpp @@ -27,7 +27,7 @@ callCountHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, bool BEGIN_TEST(testDebugger_bug519719) { CHECK(JS_SetDebugMode(cx, true)); - JS_SetCallHook(rt, callCountHook, NULL); + JS_SetCallHook(rt, callCountHook, nullptr); EXEC("function call(fn) { fn(0); }\n" "function f(g) { for (var i = 0; i < 9; i++) call(g); }\n" "f(Math.sin);\n" // record loop, starting in f @@ -48,7 +48,7 @@ nonStrictThisHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, frame.getThisValue(cx, &thisv); *allWrapped = *allWrapped && !JSVAL_IS_PRIMITIVE(thisv); } - return NULL; + return nullptr; } BEGIN_TEST(testDebugger_getThisNonStrict) @@ -87,7 +87,7 @@ strictThisHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, boo frame.getThisValue(cx, &thisv); *anyWrapped = *anyWrapped || !JSVAL_IS_PRIMITIVE(thisv); } - return NULL; + return nullptr; } BEGIN_TEST(testDebugger_getThisStrict) @@ -132,7 +132,7 @@ ThrowHook(JSContext *cx, JSScript *, jsbytecode *, jsval *rval, void *closure) BEGIN_TEST(testDebugger_throwHook) { CHECK(JS_SetDebugMode(cx, true)); - CHECK(JS_SetThrowHook(rt, ThrowHook, NULL)); + CHECK(JS_SetThrowHook(rt, ThrowHook, nullptr)); EXEC("function foo() { throw 3 };\n" "for (var i = 0; i < 10; ++i) { \n" " var x = {}\n" @@ -141,7 +141,7 @@ BEGIN_TEST(testDebugger_throwHook) " } catch(e) {}\n" "}\n"); CHECK(called); - CHECK(JS_SetThrowHook(rt, NULL, NULL)); + CHECK(JS_SetThrowHook(rt, nullptr, nullptr)); return true; } END_TEST(testDebugger_throwHook) @@ -149,7 +149,7 @@ END_TEST(testDebugger_throwHook) BEGIN_TEST(testDebugger_debuggerObjectVsDebugMode) { CHECK(JS_DefineDebuggerObject(cx, global)); - JS::RootedObject debuggee(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook)); + JS::RootedObject debuggee(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook)); CHECK(debuggee); { @@ -189,7 +189,7 @@ BEGIN_TEST(testDebugger_newScriptHook) { // Test that top-level indirect eval fires the newScript hook. CHECK(JS_DefineDebuggerObject(cx, global)); - JS::RootedObject g(cx, JS_NewGlobalObject(cx, getGlobalClass(), NULL, JS::FireOnNewGlobalHook)); + JS::RootedObject g(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook)); CHECK(g); { JSAutoCompartment ae(cx, g); @@ -240,7 +240,7 @@ END_TEST(testDebugger_newScriptHook) BEGIN_TEST(testDebugger_singleStepThrow) { CHECK(JS_SetDebugModeForCompartment(cx, cx->compartment(), true)); - CHECK(JS_SetInterrupt(rt, onStep, NULL)); + CHECK(JS_SetInterrupt(rt, onStep, nullptr)); CHECK(JS_DefineFunction(cx, global, "setStepMode", setStepMode, 0, 0)); EXEC("var e;\n" @@ -255,7 +255,7 @@ BEGIN_TEST(testDebugger_singleStepThrow) setStepMode(JSContext *cx, unsigned argc, jsval *vp) { JS::RootedScript script(cx); - JS_DescribeScriptedCaller(cx, &script, NULL); + JS_DescribeScriptedCaller(cx, &script, nullptr); JS_ASSERT(script); if (!JS_SetSingleStepMode(cx, script, true)) diff --git a/js/src/jsapi-tests/testDefineGetterSetterNonEnumerable.cpp b/js/src/jsapi-tests/testDefineGetterSetterNonEnumerable.cpp index 94e684c584f0..1851ad03529e 100644 --- a/js/src/jsapi-tests/testDefineGetterSetterNonEnumerable.cpp +++ b/js/src/jsapi-tests/testDefineGetterSetterNonEnumerable.cpp @@ -18,16 +18,16 @@ static const char PROPERTY_NAME[] = "foo"; BEGIN_TEST(testDefineGetterSetterNonEnumerable) { JS::RootedValue vobj(cx); - JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL)); + JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr)); CHECK(obj); vobj = OBJECT_TO_JSVAL(obj); - JSFunction *funGet = JS_NewFunction(cx, native, 0, 0, NULL, "get"); + JSFunction *funGet = JS_NewFunction(cx, native, 0, 0, nullptr, "get"); CHECK(funGet); JS::RootedObject funGetObj(cx, JS_GetFunctionObject(funGet)); JS::RootedValue vget(cx, OBJECT_TO_JSVAL(funGetObj)); - JSFunction *funSet = JS_NewFunction(cx, native, 1, 0, NULL, "set"); + JSFunction *funSet = JS_NewFunction(cx, native, 1, 0, nullptr, "set"); CHECK(funSet); JS::RootedObject funSetObj(cx, JS_GetFunctionObject(funSet)); JS::RootedValue vset(cx, OBJECT_TO_JSVAL(funSetObj)); diff --git a/js/src/jsapi-tests/testDefineProperty.cpp b/js/src/jsapi-tests/testDefineProperty.cpp index 493d231d33ba..3987e4500a6a 100644 --- a/js/src/jsapi-tests/testDefineProperty.cpp +++ b/js/src/jsapi-tests/testDefineProperty.cpp @@ -17,7 +17,7 @@ BEGIN_TEST(testDefineProperty_bug564344) JS::RootedObject obj(cx, JSVAL_TO_OBJECT(x)); for (int i = 0; i < 2; i++) - CHECK(JS_DefineProperty(cx, obj, "q", JSVAL_VOID, NULL, NULL, JSPROP_SHARED)); + CHECK(JS_DefineProperty(cx, obj, "q", JSVAL_VOID, nullptr, nullptr, JSPROP_SHARED)); return true; } END_TEST(testDefineProperty_bug564344) diff --git a/js/src/jsapi-tests/testEnclosingFunction.cpp b/js/src/jsapi-tests/testEnclosingFunction.cpp index e6976c37f815..2f2657926afa 100644 --- a/js/src/jsapi-tests/testEnclosingFunction.cpp +++ b/js/src/jsapi-tests/testEnclosingFunction.cpp @@ -14,7 +14,7 @@ using namespace js; -JSScript *found = NULL; +JSScript *found = nullptr; bool CheckEnclosing(JSContext *cx, unsigned argc, Value *vp) @@ -32,24 +32,27 @@ BEGIN_TEST(test_enclosingFunction) CHECK(JS_DefineFunction(cx, global, "checkEnclosing", CheckEnclosing, 0, 0)); EXEC("checkEnclosing()"); - CHECK(found == NULL); + CHECK(found == nullptr); RootedFunction fun(cx); const char s1chars[] = "checkEnclosing()"; - fun = JS_CompileFunction(cx, global, "s1", 0, NULL, s1chars, strlen(s1chars), __FILE__, __LINE__); + fun = JS_CompileFunction(cx, global, "s1", 0, nullptr, s1chars, strlen(s1chars), + __FILE__, __LINE__); CHECK(fun); EXEC("s1()"); CHECK(found == JS_GetFunctionScript(cx, fun)); const char s2chars[] = "return function() { checkEnclosing() }"; - fun = JS_CompileFunction(cx, global, "s2", 0, NULL, s2chars, strlen(s2chars), __FILE__, __LINE__); + fun = JS_CompileFunction(cx, global, "s2", 0, nullptr, s2chars, strlen(s2chars), + __FILE__, __LINE__); CHECK(fun); EXEC("s2()()"); CHECK(found == JS_GetFunctionScript(cx, fun)); const char s3chars[] = "return function() { let (x) { function g() { checkEnclosing() } return g() } }"; - fun = JS_CompileFunction(cx, global, "s3", 0, NULL, s3chars, strlen(s3chars), __FILE__, __LINE__); + fun = JS_CompileFunction(cx, global, "s3", 0, nullptr, s3chars, strlen(s3chars), + __FILE__, __LINE__); CHECK(fun); EXEC("s3()()"); CHECK(found == JS_GetFunctionScript(cx, fun)); diff --git a/js/src/jsapi-tests/testErrorCopying.cpp b/js/src/jsapi-tests/testErrorCopying.cpp index fb5ffcf43b71..75af7d92b54f 100644 --- a/js/src/jsapi-tests/testErrorCopying.cpp +++ b/js/src/jsapi-tests/testErrorCopying.cpp @@ -26,7 +26,7 @@ BEGIN_TEST(testErrorCopying_columnCopied) JS::RootedValue rval(cx); JS_SetErrorReporter(cx, my_ErrorReporter); - CHECK(!JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(!JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK(column == 27); return true; } diff --git a/js/src/jsapi-tests/testFindSCCs.cpp b/js/src/jsapi-tests/testFindSCCs.cpp index b09cb9b7759d..2400bce04880 100644 --- a/js/src/jsapi-tests/testFindSCCs.cpp +++ b/js/src/jsapi-tests/testFindSCCs.cpp @@ -135,7 +135,7 @@ void setup(unsigned count) vertex_count = count; for (unsigned i = 0; i < MaxVertices; ++i) { TestNode &v = Vertex[i]; - v.gcNextGraphNode = NULL; + v.gcNextGraphNode = nullptr; v.index = i; memset(&v.hasEdge, 0, sizeof(v.hasEdge)); } @@ -161,14 +161,14 @@ bool group(int vertex, ...) va_list ap; va_start(ap, vertex); while (vertex != -1) { - CHECK(v != NULL); + CHECK(v != nullptr); CHECK(v->index == unsigned(vertex)); v = v->nextNodeInGroup(); vertex = va_arg(ap, int); } va_end(ap); - CHECK(v == NULL); + CHECK(v == nullptr); resultsList = resultsList->nextGroup(); return true; } @@ -180,24 +180,24 @@ bool remaining(int vertex, ...) va_list ap; va_start(ap, vertex); while (vertex != -1) { - CHECK(v != NULL); + CHECK(v != nullptr); CHECK(v->index == unsigned(vertex)); v = (TestNode *)v->gcNextGraphNode; vertex = va_arg(ap, int); } va_end(ap); - CHECK(v == NULL); - resultsList = NULL; + CHECK(v == nullptr); + resultsList = nullptr; return true; } bool end() { - CHECK(resultsList == NULL); + CHECK(resultsList == nullptr); delete finder; - finder = NULL; + finder = nullptr; return true; } END_TEST(testFindSCCs) @@ -207,7 +207,7 @@ struct TestNode2 : public GraphNodeBase TestNode2 *edge; TestNode2() : - edge(NULL) + edge(nullptr) { } diff --git a/js/src/jsapi-tests/testFuncCallback.cpp b/js/src/jsapi-tests/testFuncCallback.cpp index 15d110daf528..bad8063f02d8 100644 --- a/js/src/jsapi-tests/testFuncCallback.cpp +++ b/js/src/jsapi-tests/testFuncCallback.cpp @@ -36,7 +36,7 @@ funcTransition2(const JSFunction *, const JSScript*, const JSContext*, int) } static int overlays = 0; -static JSFunctionCallback innerCallback = NULL; +static JSFunctionCallback innerCallback = nullptr; static void funcTransitionOverlay(const JSFunction *fun, const JSScript *script, @@ -78,7 +78,7 @@ BEGIN_TEST(testFuncCallback_bug507012) CHECK_EQUAL(enters, 777); // Check whether we can turn off function tracing - JS_SetFunctionCallback(cx, NULL); + JS_SetFunctionCallback(cx, nullptr); EXEC("f(1)"); CHECK_EQUAL(enters, 777); interpreted = enters = leaves = depth = 0; diff --git a/js/src/jsapi-tests/testGCExactRooting.cpp b/js/src/jsapi-tests/testGCExactRooting.cpp index b16c84d6983b..48f56bce7e33 100644 --- a/js/src/jsapi-tests/testGCExactRooting.cpp +++ b/js/src/jsapi-tests/testGCExactRooting.cpp @@ -9,14 +9,14 @@ BEGIN_TEST(testGCExactRooting) { - JS::RootedObject rootCx(cx, JS_NewObject(cx, NULL, NULL, NULL)); - JS::RootedObject rootRt(cx->runtime(), JS_NewObject(cx, NULL, NULL, NULL)); + JS::RootedObject rootCx(cx, JS_NewObject(cx, nullptr, nullptr, nullptr)); + JS::RootedObject rootRt(cx->runtime(), JS_NewObject(cx, nullptr, nullptr, nullptr)); JS_GC(cx->runtime()); /* Use the objects we just created to ensure that they are still alive. */ - JS_DefineProperty(cx, rootCx, "foo", JS::DoubleValue(0), NULL, NULL, 0); - JS_DefineProperty(cx, rootRt, "foo", JS::DoubleValue(0), NULL, NULL, 0); + JS_DefineProperty(cx, rootCx, "foo", JS::DoubleValue(0), nullptr, nullptr, 0); + JS_DefineProperty(cx, rootRt, "foo", JS::DoubleValue(0), nullptr, nullptr, 0); return true; } diff --git a/js/src/jsapi-tests/testGCFinalizeCallback.cpp b/js/src/jsapi-tests/testGCFinalizeCallback.cpp index 06e2d201bfb2..f50a7af14e75 100644 --- a/js/src/jsapi-tests/testGCFinalizeCallback.cpp +++ b/js/src/jsapi-tests/testGCFinalizeCallback.cpp @@ -126,7 +126,7 @@ BEGIN_TEST(testGCFinalizeCallback) CHECK(JS_IsGlobalObject(global2)); CHECK(JS_IsGlobalObject(global3)); - JS_SetFinalizeCallback(rt, NULL); + JS_SetFinalizeCallback(rt, nullptr); return true; } diff --git a/js/src/jsapi-tests/testGCOutOfMemory.cpp b/js/src/jsapi-tests/testGCOutOfMemory.cpp index d7a14fafbcc7..25c3473795ff 100644 --- a/js/src/jsapi-tests/testGCOutOfMemory.cpp +++ b/js/src/jsapi-tests/testGCOutOfMemory.cpp @@ -55,7 +55,7 @@ BEGIN_TEST(testGCOutOfMemory) virtual JSRuntime * createRuntime() { JSRuntime *rt = JS_NewRuntime(768 * 1024, JS_USE_HELPER_THREADS); if (!rt) - return NULL; + return nullptr; setNativeStackQuota(rt); return rt; } diff --git a/js/src/jsapi-tests/testIndexToString.cpp b/js/src/jsapi-tests/testIndexToString.cpp index bce421dc41c2..8f26a1c9a0b1 100644 --- a/js/src/jsapi-tests/testIndexToString.cpp +++ b/js/src/jsapi-tests/testIndexToString.cpp @@ -97,7 +97,7 @@ BEGIN_TEST(testStringToPropertyName) JSFlatString *hiStr = NewString(cx, hiChars); CHECK(hiStr); CHECK(!hiStr->isIndex(&index)); - CHECK(hiStr->toPropertyName(cx) != NULL); + CHECK(hiStr->toPropertyName(cx) != nullptr); static const jschar maxChars[] = { '4', '2', '9', '4', '9', '6', '7', '2', '9', '5' }; JSFlatString *maxStr = NewString(cx, maxChars); @@ -109,7 +109,7 @@ BEGIN_TEST(testStringToPropertyName) JSFlatString *maxPlusOneStr = NewString(cx, maxPlusOneChars); CHECK(maxPlusOneStr); CHECK(!maxPlusOneStr->isIndex(&index)); - CHECK(maxPlusOneStr->toPropertyName(cx) != NULL); + CHECK(maxPlusOneStr->toPropertyName(cx) != nullptr); return true; } diff --git a/js/src/jsapi-tests/testJSEvaluateScript.cpp b/js/src/jsapi-tests/testJSEvaluateScript.cpp index f34996385006..bfc6e5a47ff1 100644 --- a/js/src/jsapi-tests/testJSEvaluateScript.cpp +++ b/js/src/jsapi-tests/testJSEvaluateScript.cpp @@ -6,7 +6,7 @@ BEGIN_TEST(testJSEvaluateScript) { - JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, global)); + JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, global)); CHECK(obj); uint32_t options = JS_GetOptions(cx); diff --git a/js/src/jsapi-tests/testLookup.cpp b/js/src/jsapi-tests/testLookup.cpp index 46db0cb9b35a..edbe4bfce683 100644 --- a/js/src/jsapi-tests/testLookup.cpp +++ b/js/src/jsapi-tests/testLookup.cpp @@ -63,16 +63,17 @@ document_resolve(JSContext *cx, JS::HandleObject obj, JS::HandleId id, unsigned if (!flatStr) return false; if (JS_FlatStringEqualsAscii(flatStr, "all")) { - JS::Rooted docAll(cx, JS_NewObject(cx, &DocumentAllClass, NULL, NULL)); + JS::Rooted docAll(cx, + JS_NewObject(cx, &DocumentAllClass, nullptr, nullptr)); if (!docAll) return false; JS::Rooted allValue(cx, ObjectValue(*docAll)); - bool ok = JS_DefinePropertyById(cx, obj, id, allValue, NULL, NULL, 0); - objp.set(ok ? obj.get() : NULL); + bool ok = JS_DefinePropertyById(cx, obj, id, allValue, nullptr, nullptr, 0); + objp.set(ok ? obj.get() : nullptr); return ok; } } - objp.set(NULL); + objp.set(nullptr); return true; } @@ -84,9 +85,9 @@ static const JSClass document_class = { BEGIN_TEST(testLookup_bug570195) { - JS::RootedObject obj(cx, JS_NewObject(cx, &document_class, NULL, NULL)); + JS::RootedObject obj(cx, JS_NewObject(cx, &document_class, nullptr, nullptr)); CHECK(obj); - CHECK(JS_DefineProperty(cx, global, "document", OBJECT_TO_JSVAL(obj), NULL, NULL, 0)); + CHECK(JS_DefineProperty(cx, global, "document", OBJECT_TO_JSVAL(obj), nullptr, nullptr, 0)); JS::RootedValue v(cx); EVAL("document.all ? true : false", v.address()); CHECK_SAME(v, JSVAL_FALSE); diff --git a/js/src/jsapi-tests/testNewObject.cpp b/js/src/jsapi-tests/testNewObject.cpp index 207cd2297b02..0dd379d86318 100644 --- a/js/src/jsapi-tests/testNewObject.cpp +++ b/js/src/jsapi-tests/testNewObject.cpp @@ -17,7 +17,7 @@ constructHook(JSContext *cx, unsigned argc, jsval *vp) // Check that arguments were passed properly from JS_New. - JS::RootedObject obj(cx, JS_NewObject(cx, js::Jsvalify(&JSObject::class_), NULL, NULL)); + JS::RootedObject obj(cx, JS_NewObject(cx, js::Jsvalify(&JSObject::class_), nullptr, nullptr)); if (!obj) { JS_ReportError(cx, "test failed, could not construct object"); return false; @@ -66,7 +66,7 @@ BEGIN_TEST(testNewObject_1) JS::RootedObject Array(cx, JSVAL_TO_OBJECT(v)); // With no arguments. - JS::RootedObject obj(cx, JS_New(cx, Array, 0, NULL)); + JS::RootedObject obj(cx, JS_New(cx, Array, 0, nullptr)); CHECK(obj); JS::RootedValue rt(cx, OBJECT_TO_JSVAL(obj)); CHECK(JS_IsArrayObject(cx, obj)); @@ -100,10 +100,10 @@ BEGIN_TEST(testNewObject_1) "testNewObject_1", 0, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, - JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, NULL, - NULL, NULL, NULL, constructHook + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, nullptr, + nullptr, nullptr, nullptr, constructHook }; - JS::RootedObject ctor(cx, JS_NewObject(cx, &cls, NULL, NULL)); + JS::RootedObject ctor(cx, JS_NewObject(cx, &cls, nullptr, nullptr)); CHECK(ctor); JS::RootedValue rt2(cx, OBJECT_TO_JSVAL(ctor)); obj = JS_New(cx, ctor, 3, argv); diff --git a/js/src/jsapi-tests/testOOM.cpp b/js/src/jsapi-tests/testOOM.cpp index 0ca0e6c7f2b8..c0a1dea7fe82 100644 --- a/js/src/jsapi-tests/testOOM.cpp +++ b/js/src/jsapi-tests/testOOM.cpp @@ -18,7 +18,7 @@ virtual JSRuntime * createRuntime() { JSRuntime *rt = JS_NewRuntime(0, JS_USE_HELPER_THREADS); if (!rt) - return NULL; + return nullptr; JS_SetGCParameter(rt, JSGC_MAX_BYTES, (uint32_t)-1); setNativeStackQuota(rt); return rt; diff --git a/js/src/jsapi-tests/testObjectEmulatingUndefined.cpp b/js/src/jsapi-tests/testObjectEmulatingUndefined.cpp index 764a494e8b22..69a66f8aad63 100644 --- a/js/src/jsapi-tests/testObjectEmulatingUndefined.cpp +++ b/js/src/jsapi-tests/testObjectEmulatingUndefined.cpp @@ -28,8 +28,9 @@ ObjectEmulatingUndefinedConstructor(JSContext *cx, unsigned argc, jsval *vp) BEGIN_TEST(testObjectEmulatingUndefined_truthy) { - CHECK(JS_InitClass(cx, global, NULL, &ObjectEmulatingUndefinedClass, - ObjectEmulatingUndefinedConstructor, 0, NULL, NULL, NULL, NULL)); + CHECK(JS_InitClass(cx, global, nullptr, &ObjectEmulatingUndefinedClass, + ObjectEmulatingUndefinedConstructor, 0, + nullptr, nullptr, nullptr, nullptr)); JS::RootedValue result(cx); @@ -53,8 +54,9 @@ END_TEST(testObjectEmulatingUndefined_truthy) BEGIN_TEST(testObjectEmulatingUndefined_equal) { - CHECK(JS_InitClass(cx, global, NULL, &ObjectEmulatingUndefinedClass, - ObjectEmulatingUndefinedConstructor, 0, NULL, NULL, NULL, NULL)); + CHECK(JS_InitClass(cx, global, nullptr, &ObjectEmulatingUndefinedClass, + ObjectEmulatingUndefinedConstructor, 0, + nullptr, nullptr, nullptr, nullptr)); JS::RootedValue result(cx); diff --git a/js/src/jsapi-tests/testOps.cpp b/js/src/jsapi-tests/testOps.cpp index 53154b209ff4..a950e1116f9f 100644 --- a/js/src/jsapi-tests/testOps.cpp +++ b/js/src/jsapi-tests/testOps.cpp @@ -33,7 +33,7 @@ createMyObject(JSContext* context, unsigned argc, jsval *vp) //JS_GC(context); //<- if we make GC here, all is ok - JSObject* myObject = JS_NewObject(context, &myClass, NULL, NULL); + JSObject* myObject = JS_NewObject(context, &myClass, nullptr, nullptr); *vp = OBJECT_TO_JSVAL(myObject); JS_EndRequest(context); @@ -55,7 +55,7 @@ BEGIN_TEST(testOps_bug559006) for (int i = 0; i < 9; i++) { JS::RootedValue rval(cx); - CHECK(JS_CallFunctionName(cx, global, "main", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "main", 0, nullptr, rval.address())); CHECK_SAME(rval, INT_TO_JSVAL(123)); } return true; diff --git a/js/src/jsapi-tests/testOriginPrincipals.cpp b/js/src/jsapi-tests/testOriginPrincipals.cpp index 50808c721819..5d930dd6d2c3 100644 --- a/js/src/jsapi-tests/testOriginPrincipals.cpp +++ b/js/src/jsapi-tests/testOriginPrincipals.cpp @@ -5,7 +5,7 @@ #include "js/OldDebugAPI.h" #include "jsapi-tests/tests.h" -JSPrincipals *sOriginPrincipalsInErrorReporter = NULL; +JSPrincipals *sOriginPrincipalsInErrorReporter = nullptr; static void ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report) diff --git a/js/src/jsapi-tests/testParseJSON.cpp b/js/src/jsapi-tests/testParseJSON.cpp index 6e8d9ce5a528..a9cb6d79688c 100644 --- a/js/src/jsapi-tests/testParseJSON.cpp +++ b/js/src/jsapi-tests/testParseJSON.cpp @@ -19,7 +19,7 @@ class AutoInflatedString { size_t length_; public: - AutoInflatedString(JSContext *cx) : cx(cx), chars_(NULL), length_(0) { } + AutoInflatedString(JSContext *cx) : cx(cx), chars_(nullptr), length_(0) { } ~AutoInflatedString() { JS_free(cx, chars_); } @@ -190,7 +190,7 @@ Error(JSContext *cx, const char (&input)[N]) JSErrorReporter old = JS_SetErrorReporter(cx, reportJSONEror); bool ok = JS_ParseJSON(cx, str.chars(), str.length(), &dummy); JS_SetErrorReporter(cx, old); - JS_SetContextPrivate(cx, NULL); + JS_SetContextPrivate(cx, nullptr); CHECK(!ok); CHECK(!p.unexpectedErrorCount); diff --git a/js/src/jsapi-tests/testProfileStrings.cpp b/js/src/jsapi-tests/testProfileStrings.cpp index d5bf37b45a67..4ab464947685 100644 --- a/js/src/jsapi-tests/testProfileStrings.cpp +++ b/js/src/jsapi-tests/testProfileStrings.cpp @@ -42,7 +42,7 @@ test_fn2(JSContext *cx, unsigned argc, jsval *vp) { jsval r; JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx)); - return JS_CallFunctionName(cx, global, "d", 0, NULL, &r); + return JS_CallFunctionName(cx, global, "d", 0, nullptr, &r); } static bool @@ -82,8 +82,8 @@ initialize(JSContext *cx) { js::SetRuntimeProfilingStack(cx->runtime(), pstack, &psize, 10); JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx)); - return JS_InitClass(cx, global, NULL, &ptestClass, Prof, 0, - NULL, ptestFunctions, NULL, NULL); + return JS_InitClass(cx, global, nullptr, &ptestClass, Prof, 0, + nullptr, ptestFunctions, nullptr, nullptr); } BEGIN_TEST(testProfileStrings_isCalledWithInterpreter) @@ -104,13 +104,13 @@ BEGIN_TEST(testProfileStrings_isCalledWithInterpreter) { JS::RootedValue rval(cx); /* Make sure the stack resets and we have an entry for each stack */ - CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK(psize == 0); CHECK(max_stack >= 8); CHECK(cx->runtime()->spsProfiler.stringsCount() == 8); /* Make sure the stack resets and we added no new entries */ max_stack = 0; - CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK(psize == 0); CHECK(max_stack >= 8); CHECK(cx->runtime()->spsProfiler.stringsCount() == 8); @@ -118,7 +118,7 @@ BEGIN_TEST(testProfileStrings_isCalledWithInterpreter) reset(cx); { JS::RootedValue rval(cx); - CHECK(JS_CallFunctionName(cx, global, "check2", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check2", 0, nullptr, rval.address())); CHECK(cx->runtime()->spsProfiler.stringsCount() == 5); CHECK(max_stack >= 6); CHECK(psize == 0); @@ -129,7 +129,7 @@ BEGIN_TEST(testProfileStrings_isCalledWithInterpreter) { JS::RootedValue rval(cx); pstack[3].setLabel((char*) 1234); - CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK((size_t) pstack[3].label() == 1234); CHECK(max_stack >= 8); CHECK(psize == 0); @@ -157,14 +157,14 @@ BEGIN_TEST(testProfileStrings_isCalledWithJIT) { JS::RootedValue rval(cx); /* Make sure the stack resets and we have an entry for each stack */ - CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK(psize == 0); CHECK(max_stack >= 8); /* Make sure the stack resets and we added no new entries */ uint32_t cnt = cx->runtime()->spsProfiler.stringsCount(); max_stack = 0; - CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK(psize == 0); CHECK(cx->runtime()->spsProfiler.stringsCount() == cnt); CHECK(max_stack >= 8); @@ -177,7 +177,7 @@ BEGIN_TEST(testProfileStrings_isCalledWithJIT) /* Limit the size of the stack and make sure we don't overflow */ JS::RootedValue rval(cx); pstack[3].setLabel((char*) 1234); - CHECK(JS_CallFunctionName(cx, global, "check", 0, NULL, rval.address())); + CHECK(JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address())); CHECK(psize == 0); CHECK(max_stack >= 8); CHECK((size_t) pstack[3].label() == 1234); @@ -198,7 +198,7 @@ BEGIN_TEST(testProfileStrings_isCalledWhenError) { JS::RootedValue rval(cx); /* Make sure the stack resets and we have an entry for each stack */ - bool ok = JS_CallFunctionName(cx, global, "check2", 0, NULL, rval.address()); + bool ok = JS_CallFunctionName(cx, global, "check2", 0, nullptr, rval.address()); CHECK(!ok); CHECK(psize == 0); CHECK(cx->runtime()->spsProfiler.stringsCount() == 1); @@ -221,7 +221,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly) { /* enable it in the middle of JS and make sure things check out */ JS::RootedValue rval(cx); - JS_CallFunctionName(cx, global, "a", 0, NULL, rval.address()); + JS_CallFunctionName(cx, global, "a", 0, nullptr, rval.address()); CHECK(psize == 0); CHECK(max_stack >= 1); CHECK(cx->runtime()->spsProfiler.stringsCount() == 1); @@ -233,7 +233,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly) { /* now disable in the middle of js */ JS::RootedValue rval(cx); - JS_CallFunctionName(cx, global, "c", 0, NULL, rval.address()); + JS_CallFunctionName(cx, global, "c", 0, nullptr, rval.address()); CHECK(psize == 0); } @@ -242,7 +242,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly) { /* now disable in the middle of js, but re-enable before final exit */ JS::RootedValue rval(cx); - JS_CallFunctionName(cx, global, "e", 0, NULL, rval.address()); + JS_CallFunctionName(cx, global, "e", 0, nullptr, rval.address()); CHECK(psize == 0); CHECK(max_stack >= 3); } @@ -256,7 +256,7 @@ BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly) JS::RootedValue rval(cx); /* disable, and make sure that if we try to re-enter the JIT the pop * will still happen */ - JS_CallFunctionName(cx, global, "f", 0, NULL, rval.address()); + JS_CallFunctionName(cx, global, "f", 0, nullptr, rval.address()); CHECK(psize == 0); } return true; diff --git a/js/src/jsapi-tests/testPropCache.cpp b/js/src/jsapi-tests/testPropCache.cpp index e474b8e3c453..7c1b51259521 100644 --- a/js/src/jsapi-tests/testPropCache.cpp +++ b/js/src/jsapi-tests/testPropCache.cpp @@ -27,7 +27,7 @@ BEGIN_TEST(testPropCache_bug505798) { g_counter = 0; EXEC("var x = {};"); - CHECK(JS_DefineObject(cx, global, "y", &CounterClass, NULL, JSPROP_ENUMERATE)); + CHECK(JS_DefineObject(cx, global, "y", &CounterClass, nullptr, JSPROP_ENUMERATE)); EXEC("var arr = [x, y];\n" "for (var i = 0; i < arr.length; i++)\n" " arr[i].p = 1;\n"); diff --git a/js/src/jsapi-tests/testRegExpInstanceProperties.cpp b/js/src/jsapi-tests/testRegExpInstanceProperties.cpp index c193759c0083..a4344bf7929c 100644 --- a/js/src/jsapi-tests/testRegExpInstanceProperties.cpp +++ b/js/src/jsapi-tests/testRegExpInstanceProperties.cpp @@ -23,7 +23,7 @@ BEGIN_TEST(testRegExpInstanceProperties) JS_GC(cx); - CHECK_EQUAL(regexpProto->compartment()->initialRegExpShape, NULL); + CHECK_EQUAL(regexpProto->compartment()->initialRegExpShape, nullptr); jsval regexp; EVAL("/foopy/", ®exp); diff --git a/js/src/jsapi-tests/testResolveRecursion.cpp b/js/src/jsapi-tests/testResolveRecursion.cpp index 2c1e8b8d9a4e..a34435b651f0 100644 --- a/js/src/jsapi-tests/testResolveRecursion.cpp +++ b/js/src/jsapi-tests/testResolveRecursion.cpp @@ -27,19 +27,19 @@ BEGIN_TEST(testResolveRecursion) JS_ConvertStub }; - obj1 = obj2 = NULL; + obj1 = obj2 = nullptr; JS_AddObjectRoot(cx, &obj1); JS_AddObjectRoot(cx, &obj2); - obj1 = JS_NewObject(cx, &my_resolve_class, NULL, NULL); + obj1 = JS_NewObject(cx, &my_resolve_class, nullptr, nullptr); CHECK(obj1); - obj2 = JS_NewObject(cx, &my_resolve_class, NULL, NULL); + obj2 = JS_NewObject(cx, &my_resolve_class, nullptr, nullptr); CHECK(obj2); JS_SetPrivate(obj1, this); JS_SetPrivate(obj2, this); - CHECK(JS_DefineProperty(cx, global, "obj1", OBJECT_TO_JSVAL(obj1), NULL, NULL, 0)); - CHECK(JS_DefineProperty(cx, global, "obj2", OBJECT_TO_JSVAL(obj2), NULL, NULL, 0)); + CHECK(JS_DefineProperty(cx, global, "obj1", OBJECT_TO_JSVAL(obj1), nullptr, nullptr, 0)); + CHECK(JS_DefineProperty(cx, global, "obj2", OBJECT_TO_JSVAL(obj2), nullptr, nullptr, 0)); resolveEntryCount = 0; resolveExitCount = 0; @@ -92,19 +92,19 @@ doResolve(JS::HandleObject obj, JS::HandleId id, unsigned flags, JS::MutableHand CHECK_EQUAL(resolveEntryCount, 1); EVAL("obj2.y = true", v.address()); CHECK_SAME(v, JSVAL_TRUE); - CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_FALSE, NULL, NULL, 0)); + CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_FALSE, nullptr, nullptr, 0)); objp.set(obj); return true; } if (obj == obj2) { CHECK_EQUAL(resolveEntryCount, 4); - objp.set(NULL); + objp.set(nullptr); return true; } } else if (JS_FlatStringEqualsAscii(str, "y")) { if (obj == obj2) { CHECK_EQUAL(resolveEntryCount, 2); - CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_NULL, NULL, NULL, 0)); + CHECK(JS_DefinePropertyById(cx, obj, id, JSVAL_NULL, nullptr, nullptr, 0)); EVAL("obj1.x", v.address()); CHECK(JSVAL_IS_VOID(v)); EVAL("obj1.y", v.address()); diff --git a/js/src/jsapi-tests/testScriptObject.cpp b/js/src/jsapi-tests/testScriptObject.cpp index 6629bda0f356..561a028599fc 100644 --- a/js/src/jsapi-tests/testScriptObject.cpp +++ b/js/src/jsapi-tests/testScriptObject.cpp @@ -54,7 +54,7 @@ END_FIXTURE_TEST(ScriptObjectFixture, bug438633_CompileScript_empty) BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_CompileScriptForPrincipals) { - return tryScript(global, JS_CompileScriptForPrincipals(cx, global, NULL, + return tryScript(global, JS_CompileScriptForPrincipals(cx, global, nullptr, code, code_size, __FILE__, __LINE__)); } @@ -78,7 +78,7 @@ END_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScript_empty) BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileUCScriptForPrincipals) { - return tryScript(global, JS_CompileUCScriptForPrincipals(cx, global, NULL, + return tryScript(global, JS_CompileUCScriptForPrincipals(cx, global, nullptr, uc_code, code_size, __FILE__, __LINE__)); } @@ -145,7 +145,7 @@ BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFileHandleForPrincip CHECK(fseek(script_stream, 0, SEEK_SET) != EOF); JS::CompileOptions options(cx); options.setFileAndLine("temporary file", 1) - .setPrincipals(NULL); + .setPrincipals(nullptr); return tryScript(global, JS::Compile(cx, global, options, script_stream)); } END_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFileHandleForPrincipals) diff --git a/js/src/jsapi-tests/testSetProperty.cpp b/js/src/jsapi-tests/testSetProperty.cpp index d59025eca328..f3febaf144f4 100644 --- a/js/src/jsapi-tests/testSetProperty.cpp +++ b/js/src/jsapi-tests/testSetProperty.cpp @@ -16,7 +16,7 @@ nativeGet(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandl BEGIN_TEST(testSetProperty_NativeGetterStubSetter) { - JS::RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL)); + JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr)); CHECK(obj); JS::RootedValue vobj(cx, OBJECT_TO_JSVAL(obj)); @@ -73,7 +73,7 @@ BEGIN_TEST(testSetProperty_InheritedGlobalSetter) // shell can't. JS_ASSERT(JS_GetClass(global)->resolve == &JS_ResolveStub); - CHECK(JS_DefineProperty(cx, global, "HOTLOOP", INT_TO_JSVAL(8), NULL, NULL, 0)); + CHECK(JS_DefineProperty(cx, global, "HOTLOOP", INT_TO_JSVAL(8), nullptr, nullptr, 0)); EXEC("var n = 0;\n" "var global = this;\n" "function f() { n++; }\n" diff --git a/js/src/jsapi-tests/testSourcePolicy.cpp b/js/src/jsapi-tests/testSourcePolicy.cpp index 9b1d7218c787..0d9b57a0cfc7 100644 --- a/js/src/jsapi-tests/testSourcePolicy.cpp +++ b/js/src/jsapi-tests/testSourcePolicy.cpp @@ -16,8 +16,8 @@ BEGIN_TEST(testBug795104) s[0] = '"'; memset(s + 1, 'x', strLen - 2); s[strLen - 1] = '"'; - CHECK(JS::Evaluate(cx, global, opts, s, strLen, NULL)); - CHECK(JS::CompileFunction(cx, global, opts, "f", 0, NULL, s, strLen)); + CHECK(JS::Evaluate(cx, global, opts, s, strLen, nullptr)); + CHECK(JS::CompileFunction(cx, global, opts, "f", 0, nullptr, s, strLen)); JS_free(cx, s); return true; @@ -39,9 +39,9 @@ BEGIN_TEST(testScriptSourceReentrant) JS::CompileOptions opts(cx); bool match = false; JS_SetNewScriptHook(rt, newScriptHook, &match); - CHECK(JS::Evaluate(cx, global, opts, simpleSource, strlen(simpleSource), NULL)); + CHECK(JS::Evaluate(cx, global, opts, simpleSource, strlen(simpleSource), nullptr)); CHECK(match); - JS_SetNewScriptHook(rt, NULL, NULL); + JS_SetNewScriptHook(rt, nullptr, nullptr); return true; } diff --git a/js/src/jsapi-tests/testStructuredClone.cpp b/js/src/jsapi-tests/testStructuredClone.cpp index e60600981062..869cb3363a7e 100644 --- a/js/src/jsapi-tests/testStructuredClone.cpp +++ b/js/src/jsapi-tests/testStructuredClone.cpp @@ -19,7 +19,7 @@ BEGIN_TEST(testStructuredClone_object) JSAutoCompartment ac(cx, g1); JS::RootedValue prop(cx, JS::Int32Value(1337)); - v1 = JS::ObjectOrNullValue(JS_NewObject(cx, NULL, NULL, NULL)); + v1 = JS::ObjectOrNullValue(JS_NewObject(cx, nullptr, nullptr, nullptr)); CHECK(v1.isObject()); CHECK(JS_SetProperty(cx, &v1.toObject(), "prop", prop)); } @@ -28,7 +28,7 @@ BEGIN_TEST(testStructuredClone_object) JSAutoCompartment ac(cx, g2); JS::RootedValue v2(cx); - CHECK(JS_StructuredClone(cx, v1, v2.address(), NULL, NULL)); + CHECK(JS_StructuredClone(cx, v1, v2.address(), nullptr, nullptr)); CHECK(v2.isObject()); JS::RootedValue prop(cx); @@ -64,7 +64,7 @@ BEGIN_TEST(testStructuredClone_string) JSAutoCompartment ac(cx, g2); JS::RootedValue v2(cx); - CHECK(JS_StructuredClone(cx, v1, v2.address(), NULL, NULL)); + CHECK(JS_StructuredClone(cx, v1, v2.address(), nullptr, nullptr)); CHECK(v2.isString()); CHECK(v2.toString()); diff --git a/js/src/jsapi-tests/testValueABI.cpp b/js/src/jsapi-tests/testValueABI.cpp index f8b3b38049d9..ae1c2fda025e 100644 --- a/js/src/jsapi-tests/testValueABI.cpp +++ b/js/src/jsapi-tests/testValueABI.cpp @@ -31,7 +31,7 @@ BEGIN_TEST(testValueABI_retparam) { JS::RootedObject obj(cx, JS::CurrentGlobalOrNull(cx)); jsval v = OBJECT_TO_JSVAL(obj); - obj = NULL; + obj = nullptr; CHECK(C_ValueToObject(cx, v, obj.address())); bool equal; CHECK(JS_StrictlyEqual(cx, v, OBJECT_TO_JSVAL(obj), &equal)); diff --git a/js/src/jsapi-tests/testXDR.cpp b/js/src/jsapi-tests/testXDR.cpp index 7e1fff2edb22..69e96d931a65 100644 --- a/js/src/jsapi-tests/testXDR.cpp +++ b/js/src/jsapi-tests/testXDR.cpp @@ -20,11 +20,11 @@ CompileScriptForPrincipalsVersionOrigin(JSContext *cx, JS::HandleObject obj, JSVersion version) { size_t nchars; - if (!JS_DecodeBytes(cx, bytes, nbytes, NULL, &nchars)) - return NULL; + if (!JS_DecodeBytes(cx, bytes, nbytes, nullptr, &nchars)) + return nullptr; jschar *chars = static_cast(JS_malloc(cx, nchars * sizeof(jschar))); if (!chars) - return NULL; + return nullptr; JS_ALWAYS_TRUE(JS_DecodeBytes(cx, bytes, nbytes, chars, &nchars)); JS::CompileOptions options(cx); options.setPrincipals(principals) @@ -43,7 +43,7 @@ FreezeThaw(JSContext *cx, JS::HandleScript script) uint32_t nbytes; void *memory = JS_EncodeScript(cx, script, &nbytes); if (!memory) - return NULL; + return nullptr; // thaw JSScript *script2 = JS_DecodeScript(cx, memory, nbytes, @@ -65,7 +65,7 @@ FreezeThaw(JSContext *cx, JS::HandleObject funobj) uint32_t nbytes; void *memory = JS_EncodeInterpretedFunction(cx, funobj, &nbytes); if (!memory) - return NULL; + return nullptr; // thaw JSScript *script = GetScript(cx, funobj); @@ -89,7 +89,7 @@ BEGIN_TEST(testXDR_principals) // Appease the new JSAPI assertions. The stuff being tested here is // going away anyway. JS_SetCompartmentPrincipals(compartment, &testPrincipals[0]); - script = createScriptViaXDR(&testPrincipals[0], NULL, i); + script = createScriptViaXDR(&testPrincipals[0], nullptr, i); CHECK(script); CHECK(JS_GetScriptPrincipals(script) == &testPrincipals[0]); CHECK(JS_GetScriptOriginPrincipals(script) == &testPrincipals[0]); @@ -127,12 +127,12 @@ JSScript *createScriptViaXDR(JSPrincipals *prin, JSPrincipals *orig, int testCas src, strlen(src), "test", 1, JSVERSION_DEFAULT)); if (!script) - return NULL; + return nullptr; if (testCase == TEST_SCRIPT || testCase == TEST_SERIALIZED_FUNCTION) { script = FreezeThaw(cx, script); if (!script) - return NULL; + return nullptr; if (testCase == TEST_SCRIPT) return script; } @@ -140,12 +140,12 @@ JSScript *createScriptViaXDR(JSPrincipals *prin, JSPrincipals *orig, int testCas JS::RootedValue v(cx); bool ok = JS_ExecuteScript(cx, global, script, v.address()); if (!ok || !v.isObject()) - return NULL; + return nullptr; JS::RootedObject funobj(cx, &v.toObject()); if (testCase == TEST_FUNCTION) { funobj = FreezeThaw(cx, funobj); if (!funobj) - return NULL; + return nullptr; } return GetScript(cx, funobj); } @@ -194,7 +194,7 @@ BEGIN_TEST(testXDR_bug516827) CHECK(script); // execute with null result meaning no result wanted - CHECK(JS_ExecuteScript(cx, global, script, NULL)); + CHECK(JS_ExecuteScript(cx, global, script, nullptr)); return true; } END_TEST(testXDR_bug516827) @@ -205,7 +205,7 @@ BEGIN_TEST(testXDR_source) // This can't possibly fail to compress well, can it? "function f(x) { return x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x + x }", "short", - NULL + nullptr }; for (const char **s = samples; *s; s++) { JS::RootedScript script(cx, JS_CompileScript(cx, global, *s, strlen(*s), __FILE__, __LINE__)); @@ -227,7 +227,7 @@ BEGIN_TEST(testXDR_sourceMap) const char *sourceMaps[] = { "http://example.com/source-map.json", "file:///var/source-map.json", - NULL + nullptr }; JS::RootedScript script(cx); for (const char **sm = sourceMaps; *sm; sm++) { diff --git a/js/src/jsapi-tests/tests.cpp b/js/src/jsapi-tests/tests.cpp index a0895038ece3..038a20e01413 100644 --- a/js/src/jsapi-tests/tests.cpp +++ b/js/src/jsapi-tests/tests.cpp @@ -56,7 +56,7 @@ JSObject * JSAPITest::createGlobal(JSPrincipals *principals) options.setVersion(JSVERSION_LATEST); global = JS_NewGlobalObject(cx, getGlobalClass(), principals, JS::FireOnNewGlobalHook, options); if (!global) - return NULL; + return nullptr; JS_AddNamedObjectRoot(cx, &global, "test-global"); JS::HandleObject globalHandle = JS::HandleObject::fromMarkedLocation(&global); @@ -65,7 +65,7 @@ JSObject * JSAPITest::createGlobal(JSPrincipals *principals) /* Populate the global object with the standard globals, like Object and Array. */ if (!JS_InitStandardClasses(cx, globalHandle)) - return NULL; + return nullptr; return global; } @@ -73,7 +73,7 @@ int main(int argc, char *argv[]) { int total = 0; int failures = 0; - const char *filter = (argc == 2) ? argv[1] : NULL; + const char *filter = (argc == 2) ? argv[1] : nullptr; if (!JS_Init()) { printf("TEST-UNEXPECTED-FAIL | jsapi-tests | JS_Init() failed.\n"); @@ -82,7 +82,7 @@ int main(int argc, char *argv[]) for (JSAPITest *test = JSAPITest::list; test; test = test->next) { const char *name = test->name(); - if (filter && strstr(name, filter) == NULL) + if (filter && strstr(name, filter) == nullptr) continue; total += 1; diff --git a/js/src/jsapi-tests/tests.h b/js/src/jsapi-tests/tests.h index a1053249d5ff..94db8b5eaee1 100644 --- a/js/src/jsapi-tests/tests.h +++ b/js/src/jsapi-tests/tests.h @@ -59,7 +59,8 @@ class JSAPITest JSAPITestString msgs; JSCompartment *oldCompartment; - JSAPITest() : rt(NULL), cx(NULL), global(NULL), knownFail(false), oldCompartment(NULL) { + JSAPITest() : rt(nullptr), cx(nullptr), global(nullptr), + knownFail(false), oldCompartment(nullptr) { next = list; list = this; } @@ -71,18 +72,18 @@ class JSAPITest virtual void uninit() { if (oldCompartment) { JS_LeaveCompartment(cx, oldCompartment); - oldCompartment = NULL; + oldCompartment = nullptr; } if (cx) { JS_RemoveObjectRoot(cx, &global); - JS_LeaveCompartment(cx, NULL); + JS_LeaveCompartment(cx, nullptr); JS_EndRequest(cx); JS_DestroyContext(cx); - cx = NULL; + cx = nullptr; } if (rt) { destroyRuntime(); - rt = NULL; + rt = nullptr; } } @@ -277,7 +278,7 @@ class JSAPITest virtual JSRuntime * createRuntime() { JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024, JS_USE_HELPER_THREADS); if (!rt) - return NULL; + return nullptr; setNativeStackQuota(rt); return rt; } @@ -298,7 +299,7 @@ class JSAPITest virtual JSContext * createContext() { JSContext *cx = JS_NewContext(rt, 8192); if (!cx) - return NULL; + return nullptr; JS_SetOptions(cx, JSOPTION_VAROBJFIX); JS_SetErrorReporter(cx, &reportError); return cx; @@ -308,7 +309,7 @@ class JSAPITest return basicGlobalClass(); } - virtual JSObject * createGlobal(JSPrincipals *principals = NULL); + virtual JSObject * createGlobal(JSPrincipals *principals = nullptr); }; #define BEGIN_TEST(testname) \ @@ -384,7 +385,7 @@ class TempFile { name, strerror(errno)); exit(1); } - stream = NULL; + stream = nullptr; } /* Delete the temporary file. */ @@ -394,7 +395,7 @@ class TempFile { name, strerror(errno)); exit(1); } - name = NULL; + name = nullptr; } }; diff --git a/js/src/jsapi.cpp b/js/src/jsapi.cpp index 7fdbd811890b..abd4238305a0 100644 --- a/js/src/jsapi.cpp +++ b/js/src/jsapi.cpp @@ -230,7 +230,8 @@ JS_ConvertArgumentsVA(JSContext *cx, unsigned argc, jsval *argv, const char *for JS_snprintf(numBuf, sizeof numBuf, "%u", argc); JSAutoByteString funNameBytes; if (const char *name = GetFunctionNameBytes(cx, fun, &funNameBytes)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, + JSMSG_MORE_ARGS_NEEDED, name, numBuf, (argc == 1) ? "" : "s"); } } @@ -309,7 +310,7 @@ JS_ConvertArgumentsVA(JSContext *cx, unsigned argc, jsval *argv, const char *for case '*': break; default: - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_CHAR, format); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_CHAR, format); return false; } sp++; @@ -346,11 +347,11 @@ JS_ConvertValue(JSContext *cx, HandleValue value, JSType type, MutableHandleValu case JSTYPE_FUNCTION: vp.set(value); obj = ReportIfNotFunction(cx, vp); - ok = (obj != NULL); + ok = (obj != nullptr); break; case JSTYPE_STRING: str = ToString(cx, value); - ok = (str != NULL); + ok = (str != nullptr); if (ok) vp.setString(str); break; @@ -365,7 +366,7 @@ JS_ConvertValue(JSContext *cx, HandleValue value, JSType type, MutableHandleValu default: { char numBuf[12]; JS_snprintf(numBuf, sizeof numBuf, "%d", (int)type); - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_TYPE, numBuf); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_TYPE, numBuf); ok = false; break; } @@ -537,7 +538,7 @@ JS_PUBLIC_API(const char *) JS_GetTypeName(JSContext *cx, JSType type) { if ((unsigned)type >= (unsigned)JSTYPE_LIMIT) - return NULL; + return nullptr; return TypeStrings[type]; } @@ -714,11 +715,11 @@ JS_NewRuntime(uint32_t maxbytes, JSUseHelperThreads useHelperThreads) JSRuntime *rt = js_new(useHelperThreads); if (!rt) - return NULL; + return nullptr; if (!rt->init(maxbytes)) { JS_DestroyRuntime(rt); - return NULL; + return nullptr; } return rt; @@ -739,7 +740,7 @@ JS_SetICUMemoryFunctions(JS_ICUAllocFn allocFn, JS_ICUReallocFn reallocFn, JS_IC #if EXPOSE_INTL_API UErrorCode status = U_ZERO_ERROR; - u_setMemoryFunctions(/* context = */ NULL, allocFn, reallocFn, freeFn, &status); + u_setMemoryFunctions(/* context = */ nullptr, allocFn, reallocFn, freeFn, &status); return U_SUCCESS(status); #else return true; @@ -919,7 +920,7 @@ static const struct v2smap { {JSVERSION_DEFAULT, "1.3"}, {JSVERSION_DEFAULT, "1.4"}, {JSVERSION_DEFAULT, "1.5"}, - {JSVERSION_UNKNOWN, NULL}, /* must be last, NULL is sentinel */ + {JSVERSION_UNKNOWN, nullptr}, /* must be last, nullptr is sentinel */ }; JS_PUBLIC_API(const char *) @@ -1382,7 +1383,7 @@ static const JSStdName standard_class_atoms[] = { #ifdef ENABLE_BINARYDATA {js_InitTypedObjectClasses, EAGER_ATOM_AND_CLASP(Type)}, #endif - {NULL, 0, NULL} + {nullptr, 0, nullptr} }; /* @@ -1449,7 +1450,7 @@ static const JSStdName standard_class_names[] = { {js_InitTypedObjectClasses, EAGER_CLASS_ATOM(ArrayType), &js::ArrayType::class_}, {js_InitTypedObjectClasses, EAGER_CLASS_ATOM(StructType), &js::StructType::class_}, #endif - {NULL, 0, NULL} + {nullptr, 0, nullptr} }; static const JSStdName object_prototype_names[] = { @@ -1475,7 +1476,7 @@ static const JSStdName object_prototype_names[] = { {js_InitObjectClass, EAGER_ATOM(lookupSetter), &JSObject::class_}, #endif - {NULL, 0, NULL} + {nullptr, 0, nullptr} }; #undef CLASP @@ -1515,7 +1516,7 @@ JS_ResolveStandardClass(JSContext *cx, HandleObject obj, HandleId id, bool *reso } /* Try for class constructors/prototypes named by well-known atoms. */ - stdnm = NULL; + stdnm = nullptr; for (i = 0; standard_class_atoms[i].init; i++) { JS_ASSERT(standard_class_atoms[i].clasp); atom = OFFSET_TO_NAME(rt, standard_class_atoms[i].atomOffset); @@ -1699,7 +1700,7 @@ JS::CurrentGlobalOrNull(JSContext *cx) AssertHeapIsIdleOrIterating(cx); CHECK_REQUEST(cx); if (!cx->compartment()) - return NULL; + return nullptr; return cx->global(); } @@ -1768,7 +1769,7 @@ JS_strdup(JSRuntime *rt, const char *s) size_t n = strlen(s) + 1; void *p = rt->malloc_(n); if (!p) - return NULL; + return nullptr; return static_cast(js_memcpy(p, s, n)); } @@ -1779,7 +1780,7 @@ JS_AddValueRoot(JSContext *cx, jsval *vp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); - return AddValueRoot(cx, vp, NULL); + return AddValueRoot(cx, vp, nullptr); } JS_PUBLIC_API(bool) @@ -1787,7 +1788,7 @@ JS_AddStringRoot(JSContext *cx, JSString **rp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); - return AddStringRoot(cx, rp, NULL); + return AddStringRoot(cx, rp, nullptr); } JS_PUBLIC_API(bool) @@ -1795,7 +1796,7 @@ JS_AddObjectRoot(JSContext *cx, JSObject **rp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); - return AddObjectRoot(cx, rp, NULL); + return AddObjectRoot(cx, rp, nullptr); } JS_PUBLIC_API(bool) @@ -1991,7 +1992,7 @@ DumpNotify(JSTracer *trc, void **thingp, JSGCTraceKind kind) node->thing = thing; node->kind = kind; - node->next = NULL; + node->next = nullptr; node->parent = dtrc->parentNode; js_memcpy(node->edgeName, edgeName, edgeNameSize); @@ -2020,7 +2021,7 @@ DumpNode(JSDumpingTracer *dtrc, FILE* fp, JSHeapDumpNode *node) * chain order. */ chainLimit = MAX_PARENTS_TO_PRINT; - prev = NULL; + prev = nullptr; for (;;) { following = node->parent; node->parent = prev; @@ -2080,8 +2081,8 @@ JS_DumpHeap(JSRuntime *rt, FILE *fp, void* startThing, JSGCTraceKind startKind, dtrc.startThing = startThing; dtrc.thingToFind = thingToFind; dtrc.thingToIgnore = thingToIgnore; - dtrc.parentNode = NULL; - JSHeapDumpNode *node = NULL; + dtrc.parentNode = nullptr; + JSHeapDumpNode *node = nullptr; dtrc.lastNodep = &node; if (!startThing) { JS_ASSERT(startKind == JSTRACE_OBJECT); @@ -2102,7 +2103,7 @@ JS_DumpHeap(JSRuntime *rt, FILE *fp, void* startThing, JSGCTraceKind startKind, * so far. */ if (dtrc.ok) { - if (thingToFind == NULL || thingToFind == node->thing) + if (thingToFind == nullptr || thingToFind == node->thing) dtrc.ok = DumpNode(&dtrc, fp, node); /* Descend into children. */ @@ -2110,12 +2111,12 @@ JS_DumpHeap(JSRuntime *rt, FILE *fp, void* startThing, JSGCTraceKind startKind, depth < maxDepth && (thingToFind != node->thing || !thingToFindWasTraced)) { dtrc.parentNode = node; - children = NULL; + children = nullptr; dtrc.lastNodep = &children; JS_TraceChildren(&dtrc.base, node->thing, node->kind); if (thingToFind == node->thing) thingToFindWasTraced = true; - if (children != NULL) { + if (children != nullptr) { ++depth; node = children; continue; @@ -2454,7 +2455,7 @@ JS_DefaultValue(JSContext *cx, JSObject *objArg, JSType hint, jsval *vp) RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); - JS_ASSERT(obj != NULL); + JS_ASSERT(obj != nullptr); JS_ASSERT(hint == JSTYPE_VOID || hint == JSTYPE_STRING || hint == JSTYPE_NUMBER); RootedValue value(cx); @@ -2583,7 +2584,7 @@ JS_GetInstancePrivate(JSContext *cx, JSObject *objArg, const JSClass *clasp, jsv { RootedObject obj(cx, objArg); if (!JS_InstanceOf(cx, obj, clasp, argv)) - return NULL; + return nullptr; return obj->getPrivate(); } @@ -2637,12 +2638,12 @@ JS_GetConstructor(JSContext *cx, JSObject *protoArg) JSAutoResolveFlags rf(cx, 0); if (!JSObject::getProperty(cx, proto, proto, cx->names().constructor, &cval)) - return NULL; + return nullptr; } if (!IsFunctionObject(cval)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NO_CONSTRUCTOR, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR, proto->getClass()->name); - return NULL; + return nullptr; } return &cval.toObject(); } @@ -2710,13 +2711,13 @@ JS_NewGlobalObject(JSContext *cx, const JSClass *clasp, JSPrincipals *principals if (options.zoneSpecifier() == JS::SystemZone) zone = rt->systemZone; else if (options.zoneSpecifier() == JS::FreshZone) - zone = NULL; + zone = nullptr; else zone = static_cast(options.zonePointer()); JSCompartment *compartment = NewCompartment(cx, zone, principals, options); if (!compartment) - return NULL; + return nullptr; // Lazily create the system zone. if (!rt->systemZone && options.zoneSpecifier() == JS::SystemZone) { @@ -2733,7 +2734,7 @@ JS_NewGlobalObject(JSContext *cx, const JSClass *clasp, JSPrincipals *principals } if (!global) - return NULL; + return nullptr; if (hookOption == JS::FireOnNewGlobalHook) JS_FireOnNewGlobalObject(cx, global); @@ -3004,7 +3005,7 @@ JS_HasPropertyById(JSContext *cx, JSObject *objArg, jsid idArg, bool *foundp) RootedObject obj2(cx); RootedShape prop(cx); bool ok = LookupPropertyById(cx, obj, id, 0, &obj2, &prop); - *foundp = (prop != NULL); + *foundp = (prop != nullptr); return ok; } @@ -3101,7 +3102,7 @@ GetterWrapper(JSPropertyOp getter) { JSPropertyOpWrapper ret; ret.op = getter; - ret.info = NULL; + ret.info = nullptr; return ret; } @@ -3110,7 +3111,7 @@ SetterWrapper(JSStrictPropertyOp setter) { JSStrictPropertyOpWrapper ret; ret.op = setter; - ret.info = NULL; + ret.info = nullptr; return ret; } @@ -3158,7 +3159,7 @@ DefinePropertyById(JSContext *cx, HandleObject obj, HandleId id, HandleValue val } if (setter) { // Root just the getter, since the setter is not yet a JSObject. - AutoRooterGetterSetter getRoot(cx, JSPROP_GETTER, &getter, NULL); + AutoRooterGetterSetter getRoot(cx, JSPROP_GETTER, &getter, nullptr); RootedObject global(cx, (JSObject*) &obj->global()); JSFunction *setobj = NewFunction(cx, NullPtr(), (Native) setter, 1, zeroFlags, global, atom); @@ -3179,10 +3180,10 @@ DefinePropertyById(JSContext *cx, HandleObject obj, HandleId id, HandleValue val assertSameCompartment(cx, obj, id, value, (attrs & JSPROP_GETTER) ? JS_FUNC_TO_DATA_PTR(JSObject *, getter) - : NULL, + : nullptr, (attrs & JSPROP_SETTER) ? JS_FUNC_TO_DATA_PTR(JSObject *, setter) - : NULL); + : nullptr); JSAutoResolveFlags rf(cx, 0); if (flags != 0 && obj->isNative()) { @@ -3326,12 +3327,12 @@ JS_DefineObject(JSContext *cx, JSObject *objArg, const char *name, const JSClass RootedObject nobj(cx, NewObjectWithClassProto(cx, clasp, proto, obj)); if (!nobj) - return NULL; + return nullptr; - if (!DefineProperty(cx, obj, name, ObjectValue(*nobj), GetterWrapper(NULL), - SetterWrapper(NULL), attrs, 0, 0)) + if (!DefineProperty(cx, obj, name, ObjectValue(*nobj), GetterWrapper(nullptr), + SetterWrapper(nullptr), attrs, 0, 0)) { - return NULL; + return nullptr; } return nobj; @@ -3346,8 +3347,8 @@ JS_DefineConstDoubles(JSContext *cx, JSObject *objArg, const JSConstDoubleSpec * AssertHeapIsIdle(cx); CHECK_REQUEST(cx); - JSPropertyOpWrapper noget = GetterWrapper(NULL); - JSStrictPropertyOpWrapper noset = SetterWrapper(NULL); + JSPropertyOpWrapper noget = GetterWrapper(nullptr); + JSStrictPropertyOpWrapper noset = SetterWrapper(nullptr); for (ok = true; cds->name; cds++) { Value value = DoubleValue(cds->dval); attrs = cds->flags; @@ -3410,8 +3411,8 @@ GetPropertyDescriptorById(JSContext *cx, HandleObject obj, HandleId id, unsigned } if (!JSObject::getGenericAttributes(cx, obj2, id, &desc.attributesRef())) return false; - JS_ASSERT(desc.getter() == NULL); - JS_ASSERT(desc.setter() == NULL); + JS_ASSERT(desc.getter() == nullptr); + JS_ASSERT(desc.setter() == nullptr); JS_ASSERT(desc.value().isUndefined()); } return true; @@ -3690,7 +3691,7 @@ LastConfigurableShape(JSObject *obj) if (shape->configurable()) return shape; } - return NULL; + return nullptr; } JS_PUBLIC_API(void) @@ -3755,7 +3756,7 @@ JS_Enumerate(JSContext *cx, JSObject *objArg) AutoIdVector props(cx); JSIdArray *ida; if (!GetPropertyNames(cx, obj, JSITER_OWNONLY, &props) || !VectorToIdArray(cx, props, &ida)) - return NULL; + return nullptr; return ida; } @@ -3816,10 +3817,10 @@ static const Class prop_iter_class = { JS_ResolveStub, JS_ConvertStub, prop_iter_finalize, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ prop_iter_trace }; @@ -3832,9 +3833,9 @@ JS_NewPropertyIterator(JSContext *cx, JSObject *objArg) CHECK_REQUEST(cx); assertSameCompartment(cx, obj); - RootedObject iterobj(cx, NewObjectWithClassProto(cx, &prop_iter_class, NULL, obj)); + RootedObject iterobj(cx, NewObjectWithClassProto(cx, &prop_iter_class, nullptr, obj)); if (!iterobj) - return NULL; + return nullptr; int index; if (obj->isNative()) { @@ -3845,7 +3846,7 @@ JS_NewPropertyIterator(JSContext *cx, JSObject *objArg) /* Non-native case: enumerate a JSIdArray and keep it via private. */ JSIdArray *ida = JS_Enumerate(cx, obj); if (!ida) - return NULL; + return nullptr; iterobj->setPrivate((void *)ida); index = ida->length; } @@ -4003,7 +4004,7 @@ JS_SetSecurityCallbacks(JSRuntime *rt, const JSSecurityCallbacks *scb) JS_PUBLIC_API(const JSSecurityCallbacks *) JS_GetSecurityCallbacks(JSRuntime *rt) { - return (rt->securityCallbacks != &NullSecurityCallbacks) ? rt->securityCallbacks : NULL; + return (rt->securityCallbacks != &NullSecurityCallbacks) ? rt->securityCallbacks : nullptr; } JS_PUBLIC_API(void) @@ -4035,7 +4036,7 @@ JS_NewFunction(JSContext *cx, JSNative native, unsigned nargs, unsigned flags, if (name) { atom = Atomize(cx, name, strlen(name)); if (!atom) - return NULL; + return nullptr; } JSFunction::Flags funFlags = JSAPIToJSFunctionFlags(flags); @@ -4093,7 +4094,7 @@ JS_CloneFunctionObject(JSContext *cx, JSObject *funobjArg, JSObject *parentArg) if (!funobj->is()) { AutoCompartment ac(cx, funobj); ReportIsNotFunction(cx, ObjectValue(*funobj)); - return NULL; + return nullptr; } /* @@ -4104,23 +4105,23 @@ JS_CloneFunctionObject(JSContext *cx, JSObject *funobjArg, JSObject *parentArg) if (fun->isInterpretedLazy()) { AutoCompartment ac(cx, funobj); if (!fun->getOrCreateScript(cx)) - return NULL; + return nullptr; } if (fun->isInterpreted() && (fun->nonLazyScript()->enclosingStaticScope() || (fun->nonLazyScript()->compileAndGo && !parent->is()))) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_CLONE_FUNOBJ_SCOPE); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_CLONE_FUNOBJ_SCOPE); + return nullptr; } if (fun->isBoundFunction()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CLONE_OBJECT); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); + return nullptr; } if (fun->isNative() && IsAsmJSModuleNative(fun->native())) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CLONE_OBJECT); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); + return nullptr; } return CloneFunctionObject(cx, fun, parent, fun->getAllocKind()); @@ -4182,7 +4183,7 @@ JS_BindCallable(JSContext *cx, JSObject *targetArg, JSObject *newThis) { RootedObject target(cx, targetArg); RootedValue thisArg(cx, ObjectValue(*newThis)); - return js_fun_bind(cx, target, thisArg, NULL, 0); + return js_fun_bind(cx, target, thisArg, nullptr, 0); } static bool @@ -4268,7 +4269,7 @@ JS_DefineFunctions(JSContext *cx, JSObject *objArg, const JSFunctionSpec *fs) /* * Delay cloning self-hosted functions until they are called. This is - * achieved by passing DefineFunction a NULL JSNative which + * achieved by passing DefineFunction a nullptr JSNative which * produces an interpreted JSFunction where !hasScript. Interpreted * call paths then call InitializeLazyFunctionScript if !hasScript. */ @@ -4291,7 +4292,7 @@ JS_DefineFunctions(JSContext *cx, JSObject *objArg, const JSFunctionSpec *fs) RootedValue funVal(cx); if (!cx->global()->getSelfHostedFunction(cx, shName, atom, fs->nargs, &funVal)) return false; - if (!JSObject::defineGeneric(cx, obj, id, funVal, NULL, NULL, flags)) + if (!JSObject::defineGeneric(cx, obj, id, funVal, nullptr, nullptr, flags)) return false; } else { JSFunction *fun = DefineFunction(cx, obj, id, fs->call.op, fs->nargs, flags); @@ -4315,7 +4316,7 @@ JS_DefineFunction(JSContext *cx, JSObject *objArg, const char *name, JSNative ca assertSameCompartment(cx, obj); JSAtom *atom = Atomize(cx, name, strlen(name)); if (!atom) - return NULL; + return nullptr; Rooted id(cx, AtomToId(atom)); return DefineFunction(cx, obj, id, call, nargs, attrs); } @@ -4332,7 +4333,7 @@ JS_DefineUCFunction(JSContext *cx, JSObject *objArg, assertSameCompartment(cx, obj); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); if (!atom) - return NULL; + return nullptr; Rooted id(cx, AtomToId(atom)); return DefineFunction(cx, obj, id, call, nargs, attrs); } @@ -4419,7 +4420,7 @@ class AutoFile FILE *fp_; public: AutoFile() - : fp_(NULL) + : fp_(nullptr) {} ~AutoFile() { @@ -4438,7 +4439,7 @@ class AutoFile } /* anonymous namespace */ /* - * Open a source file for reading. Supports "-" and NULL to mean stdin. The + * Open a source file for reading. Supports "-" and nullptr to mean stdin. The * return value must be fclosed unless it is stdin. */ bool @@ -4449,7 +4450,7 @@ AutoFile::open(JSContext *cx, const char *filename) } else { fp_ = fopen(filename, "r"); if (!fp_) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_OPEN, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_OPEN, filename, "No such file or directory"); return false; } @@ -4459,13 +4460,13 @@ AutoFile::open(JSContext *cx, const char *filename) JS::CompileOptions::CompileOptions(JSContext *cx, JSVersion version) - : principals_(NULL), - originPrincipals_(NULL), + : principals_(nullptr), + originPrincipals_(nullptr), version(version != JSVERSION_UNKNOWN ? version : cx->findVersion()), versionSet(false), utf8(false), - filename(NULL), - sourceMapURL(NULL), + filename(nullptr), + sourceMapURL(nullptr), lineno(1), column(0), element(NullPtr()), @@ -4512,7 +4513,7 @@ JS::Compile(JSContext *cx, HandleObject obj, CompileOptions options, else chars = InflateString(cx, bytes, &length); if (!chars) - return NULL; + return nullptr; JSScript *script = Compile(cx, obj, options, chars, length); js_free(chars); @@ -4524,7 +4525,7 @@ JS::Compile(JSContext *cx, HandleObject obj, CompileOptions options, FILE *fp) { FileContents buffer(cx); if (!ReadCompleteFile(cx, fp, buffer)) - return NULL; + return nullptr; JSScript *script = Compile(cx, obj, options, buffer.begin(), buffer.length()); return script; @@ -4535,7 +4536,7 @@ JS::Compile(JSContext *cx, HandleObject obj, CompileOptions options, const char { AutoFile file; if (!file.open(cx, filename)) - return NULL; + return nullptr; options = options.setFileAndLine(filename, 1); JSScript *script = Compile(cx, obj, options, file.fp()); return script; @@ -4568,7 +4569,7 @@ JS::CanCompileOffThread(JSContext *cx, const CompileOptions &options) "chrome://browser/content/newtab/newTab.js", "chrome://browser/content/places/browserPlacesViews.js", #endif - NULL + nullptr }; const char *filename = options.filename; @@ -4682,8 +4683,8 @@ JS_BufferIsCompilableUnit(JSContext *cx, JSObject *objArg, const char *utf8, siz options.setCompileAndGo(false); Parser parser(cx, &cx->tempLifoAlloc(), options, chars, length, - /* foldConstants = */ true, NULL, NULL); - older = JS_SetErrorReporter(cx, NULL); + /* foldConstants = */ true, nullptr, nullptr); + older = JS_SetErrorReporter(cx, nullptr); if (!parser.parse(obj) && parser.isUnexpectedEOF()) { /* * We ran into an error. If it was because we ran out of @@ -4722,29 +4723,29 @@ JS::CompileFunction(JSContext *cx, HandleObject obj, CompileOptions options, if (name) { funAtom = Atomize(cx, name, strlen(name)); if (!funAtom) - return NULL; + return nullptr; } AutoNameVector formals(cx); for (unsigned i = 0; i < nargs; i++) { RootedAtom argAtom(cx, Atomize(cx, argnames[i], strlen(argnames[i]))); if (!argAtom || !formals.append(argAtom->asPropertyName())) - return NULL; + return nullptr; } - RootedFunction fun(cx, NewFunction(cx, NullPtr(), NULL, 0, JSFunction::INTERPRETED, obj, + RootedFunction fun(cx, NewFunction(cx, NullPtr(), nullptr, 0, JSFunction::INTERPRETED, obj, funAtom, JSFunction::FinalizeKind, TenuredObject)); if (!fun) - return NULL; + return nullptr; if (!frontend::CompileFunctionBody(cx, &fun, options, formals, chars, length)) - return NULL; + return nullptr; if (obj && funAtom) { Rooted id(cx, AtomToId(funAtom)); RootedValue value(cx, ObjectValue(*fun)); - if (!JSObject::defineGeneric(cx, obj, id, value, NULL, NULL, JSPROP_ENUMERATE)) - return NULL; + if (!JSObject::defineGeneric(cx, obj, id, value, nullptr, nullptr, JSPROP_ENUMERATE)) + return nullptr; } return fun; @@ -4761,7 +4762,7 @@ JS::CompileFunction(JSContext *cx, HandleObject obj, CompileOptions options, else chars = InflateString(cx, bytes, &length); if (!chars) - return NULL; + return nullptr; JSFunction *fun = CompileFunction(cx, obj, options, name, nargs, argnames, chars, length); js_free(chars); @@ -4822,7 +4823,7 @@ JS_DecompileScript(JSContext *cx, JSScript *scriptArg, const char *name, unsigne return JS_DecompileFunction(cx, fun, indent); bool haveSource = script->scriptSource()->hasSourceData(); if (!haveSource && !JSScript::loadSource(cx, script->scriptSource(), &haveSource)) - return NULL; + return nullptr; return haveSource ? script->sourceData(cx) : js_NewStringCopyZ(cx, "[no source]"); } @@ -4908,7 +4909,7 @@ JS::Evaluate(JSContext *cx, HandleObject obj, CompileOptions options, SourceCompressionTask sct(cx); RootedScript script(cx, frontend::CompileScript(cx, &cx->tempLifoAlloc(), obj, NullPtr(), options, - chars, length, NULL, 0, &sct)); + chars, length, nullptr, 0, &sct)); if (!script) return false; @@ -4924,7 +4925,7 @@ JS::Evaluate(JSContext *cx, HandleObject obj, CompileOptions options, // to clear out this analysis data before anything happens to inhibit the // flushing of this memory (such as setting requestAnimationFrame). if (script->length > LARGE_SCRIPT_LENGTH) { - script = NULL; + script = nullptr; PrepareZoneForGC(cx->zone()); GC(cx->runtime(), GC_NORMAL, gcreason::FINISH_LARGE_EVALUTE); } @@ -5154,14 +5155,14 @@ JS_New(JSContext *cx, JSObject *ctorArg, unsigned argc, jsval *argv) // among other details. InvokeConstructor does the hard work. InvokeArgs args(cx); if (!args.init(argc)) - return NULL; + return nullptr; args.setCallee(ObjectValue(*ctor)); args.setThis(NullValue()); PodCopy(args.array(), argv, argc); if (!InvokeConstructor(cx, args)) - return NULL; + return nullptr; if (!args.rval().isObject()) { /* @@ -5170,10 +5171,10 @@ JS_New(JSContext *cx, JSObject *ctorArg, unsigned argc, jsval *argv) */ JSAutoByteString bytes; if (js_ValueToPrintable(cx, args.rval(), &bytes)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_NEW_RESULT, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_NEW_RESULT, bytes.ptr()); } - return NULL; + return nullptr; } return &args.rval().toObject(); @@ -5258,7 +5259,7 @@ JS_NewStringCopyZ(JSContext *cx, const char *s) n = strlen(s); js = InflateString(cx, s, &n); if (!js) - return NULL; + return nullptr; str = js_NewString(cx, js, n); if (!str) js_free(js); @@ -5379,7 +5380,7 @@ JS_GetStringCharsZAndLength(JSContext *cx, JSString *str, size_t *plength) CHECK_REQUEST(cx); JSFlatString *flat = str->ensureFlat(cx); if (!flat) - return NULL; + return nullptr; *plength = flat->length(); return flat->chars(); } @@ -5393,7 +5394,7 @@ JS_GetStringCharsAndLength(JSContext *cx, JSString *str, size_t *plength) assertSameCompartment(cx, str); JSLinearString *linear = str->ensureLinear(cx); if (!linear) - return NULL; + return nullptr; *plength = linear->length(); return linear->chars(); } @@ -5402,9 +5403,9 @@ JS_PUBLIC_API(const jschar *) JS_GetInternedStringChars(JSString *str) { JS_ASSERT(str->isAtom()); - JSFlatString *flat = str->ensureFlat(NULL); + JSFlatString *flat = str->ensureFlat(nullptr); if (!flat) - return NULL; + return nullptr; return flat->chars(); } @@ -5413,9 +5414,9 @@ JS_GetInternedStringCharsAndLength(JSString *str, size_t *plength) { JS_ASSERT(str->isAtom()); JS_ASSERT(plength); - JSFlatString *flat = str->ensureFlat(NULL); + JSFlatString *flat = str->ensureFlat(nullptr); if (!flat) - return NULL; + return nullptr; *plength = flat->length(); return flat->chars(); } @@ -5428,7 +5429,7 @@ JS_FlattenString(JSContext *cx, JSString *str) assertSameCompartment(cx, str); JSFlatString *flat = str->ensureFlat(cx); if (!flat) - return NULL; + return nullptr; return flat; } @@ -5485,7 +5486,7 @@ JS_PutEscapedString(JSContext *cx, char *buffer, size_t size, JSString *str, cha JS_PUBLIC_API(bool) JS_FileEscapedString(FILE *fp, JSString *str, char quote) { - JSLinearString *linearStr = str->ensureLinear(NULL); + JSLinearString *linearStr = str->ensureLinear(nullptr); return linearStr && FileEscapedString(fp, linearStr, quote); } @@ -5522,7 +5523,7 @@ JS_DecodeBytes(JSContext *cx, const char *src, size_t srclen, jschar *dst, size_ InflateStringToBuffer(src, dstlen, dst); AutoSuppressGC suppress(cx); - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BUFFER_TOO_SMALL); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BUFFER_TOO_SMALL); return false; } @@ -5539,7 +5540,7 @@ JS_EncodeString(JSContext *cx, JSString *str) JSLinearString *linear = str->ensureLinear(cx); if (!linear) - return NULL; + return nullptr; return LossyTwoByteCharsToNewLatin1CharsZ(cx, linear->range()).c_str(); } @@ -5552,7 +5553,7 @@ JS_EncodeStringToUTF8(JSContext *cx, JSString *str) JSLinearString *linear = str->ensureLinear(cx); if (!linear) - return NULL; + return nullptr; return TwoByteCharsToNewUTF8CharsZ(cx, linear->range()).c_str(); } @@ -5581,10 +5582,10 @@ JS_EncodeStringToBuffer(JSContext *cx, JSString *str, char *buffer, size_t lengt * error. */ size_t writtenLength = length; - const jschar *chars = str->getChars(NULL); + const jschar *chars = str->getChars(nullptr); if (!chars) return size_t(-1); - if (DeflateStringToBuffer(NULL, chars, str->length(), buffer, &writtenLength)) { + if (DeflateStringToBuffer(nullptr, chars, str->length(), buffer, &writtenLength)) { JS_ASSERT(writtenLength <= length); return writtenLength; } @@ -5808,11 +5809,11 @@ JS_NewRegExpObject(JSContext *cx, HandleObject obj, char *bytes, size_t length, CHECK_REQUEST(cx); jschar *chars = InflateString(cx, bytes, &length); if (!chars) - return NULL; + return nullptr; RegExpStatics *res = obj->as().getRegExpStatics(); RegExpObject *reobj = RegExpObject::create(cx, res, chars, length, - RegExpFlag(flags), NULL); + RegExpFlag(flags), nullptr); js_free(chars); return reobj; } @@ -5825,7 +5826,7 @@ JS_NewUCRegExpObject(JSContext *cx, HandleObject obj, jschar *chars, size_t leng CHECK_REQUEST(cx); RegExpStatics *res = obj->as().getRegExpStatics(); return RegExpObject::create(cx, res, chars, length, - RegExpFlag(flags), NULL); + RegExpFlag(flags), nullptr); } JS_PUBLIC_API(void) @@ -5868,9 +5869,9 @@ JS_NewRegExpObjectNoStatics(JSContext *cx, char *bytes, size_t length, unsigned CHECK_REQUEST(cx); jschar *chars = InflateString(cx, bytes, &length); if (!chars) - return NULL; + return nullptr; RegExpObject *reobj = RegExpObject::createNoStatics(cx, chars, length, - RegExpFlag(flags), NULL); + RegExpFlag(flags), nullptr); js_free(chars); return reobj; } @@ -5881,7 +5882,7 @@ JS_NewUCRegExpObjectNoStatics(JSContext *cx, jschar *chars, size_t length, unsig AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return RegExpObject::createNoStatics(cx, chars, length, - RegExpFlag(flags), NULL); + RegExpFlag(flags), nullptr); } JS_PUBLIC_API(bool) @@ -5891,8 +5892,8 @@ JS_ExecuteRegExpNoStatics(JSContext *cx, HandleObject obj, jschar *chars, size_t AssertHeapIsIdle(cx); CHECK_REQUEST(cx); - return ExecuteRegExpLegacy(cx, NULL, obj->as(), NullPtr(), chars, length, indexp, - test, rval); + return ExecuteRegExpLegacy(cx, nullptr, obj->as(), NullPtr(), chars, length, + indexp, test, rval); } JS_PUBLIC_API(bool) @@ -6064,7 +6065,7 @@ JS_ThrowReportedError(JSContext *cx, const char *message, { AssertHeapIsIdle(cx); return JS_IsRunning(cx) && - js_ErrorToException(cx, message, reportp, NULL, NULL); + js_ErrorToException(cx, message, reportp, nullptr, nullptr); } JS_PUBLIC_API(bool) @@ -6207,7 +6208,7 @@ JS_IsIdentifier(JSContext *cx, HandleString str, bool *isIdentifier) JS_PUBLIC_API(bool) JS_DescribeScriptedCaller(JSContext *cx, MutableHandleScript script, unsigned *lineno) { - script.set(NULL); + script.set(nullptr); if (lineno) *lineno = 0; @@ -6279,7 +6280,7 @@ JS_EncodeScript(JSContext *cx, HandleScript scriptArg, uint32_t *lengthp) XDREncoder encoder(cx); RootedScript script(cx, scriptArg); if (!encoder.codeScript(&script)) - return NULL; + return nullptr; return encoder.forgetData(lengthp); } @@ -6289,7 +6290,7 @@ JS_EncodeInterpretedFunction(JSContext *cx, HandleObject funobjArg, uint32_t *le XDREncoder encoder(cx); RootedObject funobj(cx, funobjArg); if (!encoder.codeFunction(&funobj)) - return NULL; + return nullptr; return encoder.forgetData(lengthp); } @@ -6300,7 +6301,7 @@ JS_DecodeScript(JSContext *cx, const void *data, uint32_t length, XDRDecoder decoder(cx, data, length, principals, originPrincipals); RootedScript script(cx); if (!decoder.codeScript(&script)) - return NULL; + return nullptr; return script; } @@ -6311,7 +6312,7 @@ JS_DecodeInterpretedFunction(JSContext *cx, const void *data, uint32_t length, XDRDecoder decoder(cx, data, length, principals, originPrincipals); RootedObject funobj(cx); if (!decoder.codeFunction(&funobj)) - return NULL; + return nullptr; return funobj; } @@ -6340,7 +6341,7 @@ JSAutoByteString::encodeLatin1(ExclusiveContext *cx, JSString *str) { JSLinearString *linear = str->ensureLinear(cx); if (!linear) - return NULL; + return nullptr; mBytes = LossyTwoByteCharsToNewLatin1CharsZ(cx, linear->range()).c_str(); return mBytes; diff --git a/js/src/jsapi.h b/js/src/jsapi.h index 9a5d09454a48..efc93220cd47 100644 --- a/js/src/jsapi.h +++ b/js/src/jsapi.h @@ -150,7 +150,7 @@ class JS_PUBLIC_API(AutoGCRooter) { class AutoStringRooter : private AutoGCRooter { public: - AutoStringRooter(JSContext *cx, JSString *str = NULL + AutoStringRooter(JSContext *cx, JSString *str = nullptr MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : AutoGCRooter(cx, STRING), str_(str) { @@ -802,10 +802,10 @@ typedef bool * 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-NULL, 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. + * 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::Handle existing, JS::Handle obj, @@ -1329,7 +1329,7 @@ JS_DestroyRuntime(JSRuntime *rt); // These are equivalent to ICU's |UMemAllocFn|, |UMemReallocFn|, and // |UMemFreeFn| types. The first argument (called |context| in the ICU docs) -// will always be NULL, and should be ignored. +// 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); @@ -1589,7 +1589,7 @@ extern JS_PUBLIC_API(bool) JS_RefreshCrossCompartmentWrappers(JSContext *cx, JSObject *ob); /* - * At any time, a JSContext has a current (possibly-NULL) compartment. + * At any time, a JSContext has a current (possibly-nullptr) compartment. * Compartments are described in: * * developer.mozilla.org/en-US/docs/SpiderMonkey/SpiderMonkey_compartments @@ -1633,7 +1633,7 @@ class JS_PUBLIC_API(JSAutoCompartment) ~JSAutoCompartment(); }; -/* NB: This API is infallible; a NULL return value does not indicate error. */ +/* NB: This API is infallible; a nullptr return value does not indicate error. */ extern JS_PUBLIC_API(JSCompartment *) JS_EnterCompartment(JSContext *cx, JSObject *target); @@ -1718,8 +1718,8 @@ extern JS_PUBLIC_API(bool) JS_IsGlobalObject(JSObject *obj); /* - * May return NULL, if |c| never had a global (e.g. the atoms compartment), or - * if |c|'s global has been collected. + * 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); @@ -1767,7 +1767,7 @@ typedef char * /* * Set of function pointers that ctypes can use for various internal functions. - * See JS_SetCTypesCallbacks below. Providing NULL for a function is safe, + * See JS_SetCTypesCallbacks below. Providing nullptr for a function is safe, * and will result in the applicable ctypes functionality not being available. */ struct JSCTypesCallbacks { @@ -1805,7 +1805,7 @@ JS_realloc(JSContext *cx, void *p, size_t nbytes); /* * A wrapper for js_free(p) that may delay js_free(p) invocation as a * performance optimization. - * cx may be NULL. + * cx may be nullptr. */ extern JS_PUBLIC_API(void) JS_free(JSContext *cx, void *p); @@ -2153,8 +2153,8 @@ extern JS_PUBLIC_API(bool) JS_IsExternalString(JSString *str); /* - * Return the 'closure' arg passed to JS_NewExternalStringWithClosure or NULL - * if the external string was created via JS_NewExternalString. + * Return the 'closure' arg passed to JS_NewExternalStringWithClosure or + * nullptr if the external string was created via JS_NewExternalString. */ extern JS_PUBLIC_API(const JSStringFinalizer *) JS_GetExternalStringFinalizer(JSString *str); @@ -2221,7 +2221,7 @@ class AutoIdArray : private AutoGCRooter JSIdArray *steal() { JSIdArray *copy = idArray; - idArray = NULL; + idArray = nullptr; return copy; } @@ -2318,8 +2318,8 @@ typedef struct JSNativeWrapper { * Macro static initializers which make it easy to pass no JSJitInfo as part of a * JSPropertySpec or JSFunctionSpec. */ -#define JSOP_WRAPPER(op) {op, NULL} -#define JSOP_NULLWRAPPER JSOP_WRAPPER(NULL) +#define JSOP_WRAPPER(op) {op, nullptr} +#define JSOP_NULLWRAPPER JSOP_WRAPPER(nullptr) /* * To define an array element rather than a named property member, cast the @@ -2387,7 +2387,7 @@ struct JSFunctionSpec { * 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(NULL,NULL,0,0) +#define JS_FS_END JS_FS(nullptr,nullptr,0,0) /* * Initializer macros for a JSFunctionSpec array element. JS_FN (whose name pays @@ -2655,8 +2655,8 @@ struct JSPropertyDescriptor { JSStrictPropertyOp setter; JS::Value value; - JSPropertyDescriptor() : obj(NULL), attrs(0), shortid(0), getter(NULL), - setter(NULL), value(JSVAL_VOID) + JSPropertyDescriptor() : obj(nullptr), attrs(0), shortid(0), getter(nullptr), + setter(nullptr), value(JSVAL_VOID) {} void trace(JSTracer *trc); @@ -2712,11 +2712,11 @@ class MutablePropertyDescriptorOperations : public PropertyDescriptorOperations< public: void clear() { - object().set(NULL); + object().set(nullptr); setAttributes(0); setShortId(0); - setGetter(NULL); - setSetter(NULL); + setGetter(nullptr); + setSetter(nullptr); value().setUndefined(); } @@ -2985,9 +2985,9 @@ extern JS_PUBLIC_API(bool) JS_AllocateArrayBufferContents(JSContext *cx, uint32_t nbytes, void **contents, uint8_t **data); /* - * Reallocate memory allocated by JS_AllocateArrayBufferContents, growing or shrinking it - * as appropriate. The new data pointer will be returned in data. If *contents is NULL, - * behaves like JS_AllocateArrayBufferContents. + * Reallocate memory allocated by JS_AllocateArrayBufferContents, growing or + * shrinking it as appropriate. The new data pointer will be returned in data. + * If *contents is nullptr, behaves like JS_AllocateArrayBufferContents. */ extern JS_PUBLIC_API(bool) JS_ReallocateArrayBufferContents(JSContext *cx, uint32_t nbytes, void **contents, uint8_t **data); @@ -3084,7 +3084,7 @@ JS_GetSecurityCallbacks(JSRuntime *rt); * there is no available JSContext. Instead, the caller must ensure that the * given principals stays valid for as long as 'rt' may point to it. If the * principals would be destroyed before 'rt', JS_SetTrustedPrincipals must be - * called again, passing NULL for 'prin'. + * called again, passing nullptr for 'prin'. */ extern JS_PUBLIC_API(void) JS_SetTrustedPrincipals(JSRuntime *rt, const JSPrincipals *prin); @@ -3137,8 +3137,8 @@ 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 NULL if a useful display name could not be inferred. The same - * restrictions on rooting as those in JS_GetFunctionId apply. + * 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); @@ -3171,7 +3171,7 @@ JS_IsConstructor(JSFunction *fun); /* * Bind the given callable to use the given object as "this". * - * If |callable| is not callable, will throw and return NULL. + * If |callable| is not callable, will throw and return nullptr. */ extern JS_PUBLIC_API(JSObject*) JS_BindCallable(JSContext *cx, JSObject *callable, JSObject *newThis); @@ -3332,8 +3332,8 @@ CanCompileOffThread(JSContext *cx, const CompileOptions &options); * for the compilation. The callback will be invoked while off the main thread, * so must ensure that its operations are thread safe. Afterwards, * FinishOffThreadScript must be invoked on the main thread to get the result - * script or NULL. If maybecx is specified, this method will also report any - * error or warnings generated during the parse. + * script or nullptr. If maybecx is specified, this method will also report + * any error or warnings generated during the parse. * * The characters passed in to CompileOffThread must remain live until the * callback is invoked, and the resulting script will be rooted until the call @@ -3763,10 +3763,10 @@ 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 jschars actually stored. * To determine the necessary destination buffer size, make a sizing call that - * passes NULL for dst. + * 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 NULL, no + * 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 jschar after the @@ -3820,7 +3820,7 @@ class JSAutoByteString } JSAutoByteString(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) - : mBytes(NULL) + : mBytes(nullptr) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; } @@ -3853,7 +3853,7 @@ class JSAutoByteString void clear() { js_free(mBytes); - mBytes = NULL; + mBytes = nullptr; } char *ptr() const { @@ -3933,14 +3933,14 @@ struct JSLocaleCallbacks { /* * Establish locale callbacks. The pointer must persist as long as the - * JSRuntime. Passing NULL restores the default behaviour. + * JSRuntime. Passing nullptr restores the default behaviour. */ extern JS_PUBLIC_API(void) JS_SetLocaleCallbacks(JSRuntime *rt, JSLocaleCallbacks *callbacks); /* * Return the address of the current locale callbacks struct, which may - * be NULL. + * be nullptr. */ extern JS_PUBLIC_API(JSLocaleCallbacks *) JS_GetLocaleCallbacks(JSRuntime *rt); @@ -4182,9 +4182,9 @@ JS_DropExceptionState(JSContext *cx, JSExceptionState *state); /* * If the given value is an exception object that originated from an error, * the exception will contain an error report struct, and this API will return - * the address of that struct. Otherwise, it returns NULL. The lifetime of - * the error report struct that might be returned is the same as the lifetime - * of the exception object. + * 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::HandleValue v); diff --git a/js/src/jsarray.cpp b/js/src/jsarray.cpp index 620aaafb58dc..8a383b4c9568 100644 --- a/js/src/jsarray.cpp +++ b/js/src/jsarray.cpp @@ -277,7 +277,7 @@ SetArrayElement(JSContext *cx, HandleObject obj, double index, HandleValue v) break; uint32_t idx = uint32_t(index); if (idx >= arr->length() && !arr->lengthIsWritable()) { - JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, NULL, + JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, nullptr, JSMSG_CANT_REDEFINE_ARRAY_LENGTH); return false; } @@ -393,7 +393,7 @@ array_length_setter(JSContext *cx, HandleObject obj, HandleId id, bool strict, M { if (!obj->is()) { return JSObject::defineProperty(cx, obj, cx->names().length, vp, - NULL, NULL, JSPROP_ENUMERATE); + nullptr, nullptr, JSPROP_ENUMERATE); } Rooted arr(cx, &obj->as()); @@ -424,7 +424,8 @@ js::CanonicalizeArrayLengthValue(JSContext *cx, HandleValue v, uint32_t *newLen) return true; if (cx->isJSContext()) - JS_ReportErrorNumber(cx->asJSContext(), js_GetErrorMessage, NULL, JSMSG_BAD_ARRAY_LENGTH); + JS_ReportErrorNumber(cx->asJSContext(), js_GetErrorMessage, nullptr, + JSMSG_BAD_ARRAY_LENGTH); return false; } @@ -479,7 +480,7 @@ js::ArraySetLength(JSContext *cx, Handle arr, HandleId id, unsigne if (setterIsStrict) { return JS_ReportErrorFlagsAndNumber(cx->asJSContext(), - JSREPORT_ERROR, js_GetErrorMessage, NULL, + JSREPORT_ERROR, js_GetErrorMessage, nullptr, JSMSG_CANT_REDEFINE_ARRAY_LENGTH); } @@ -708,7 +709,7 @@ js::WouldDefinePastNonwritableLength(ExclusiveContext *cx, // Error in strict mode code or warn with strict option. // XXX include the index and maybe array length in the error message unsigned flags = strict ? JSREPORT_ERROR : (JSREPORT_STRICT | JSREPORT_WARNING); - return JS_ReportErrorFlagsAndNumber(ncx, flags, js_GetErrorMessage, NULL, + return JS_ReportErrorFlagsAndNumber(ncx, flags, js_GetErrorMessage, nullptr, JSMSG_CANT_DEFINE_PAST_ARRAY_LENGTH); } @@ -750,7 +751,7 @@ js::ObjectMayHaveExtraIndexedProperties(JSObject *obj) * exists. If we hit the end of the prototype chain, it's safe to set the * element on the original object. */ - while ((obj = obj->getProto()) != NULL) { + while ((obj = obj->getProto()) != nullptr) { /* * If the prototype is a non-native object (possibly a dense array), or * a native object (possibly a slow array) that has indexed properties, @@ -777,16 +778,16 @@ const Class ArrayObject::class_ = { JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, - NULL, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ - NULL, /* trace */ + nullptr, + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ + nullptr, /* trace */ { - NULL, /* outerObject */ - NULL, /* innerObject */ - NULL, /* iteratorObject */ + nullptr, /* outerObject */ + nullptr, /* innerObject */ + nullptr, /* iteratorObject */ false, /* isWrappedNative */ } }; @@ -977,7 +978,7 @@ ArrayJoinKernel(JSContext *cx, SeparatorOp sepOp, HandleObject obj, uint32_t len if (!robj) return false; RootedId id(cx, NameToId(cx->names().toLocaleString)); - if (!robj->callMethod(cx, id, 0, NULL, &v)) + if (!robj->callMethod(cx, id, 0, nullptr, &v)) return false; } if (!ValueToStringBuffer(cx, v, sb)) @@ -1020,7 +1021,7 @@ ArrayJoin(JSContext *cx, CallArgs &args) return false; // Steps 4 and 5 - RootedString sepstr(cx, NULL); + RootedString sepstr(cx, nullptr); if (!Locale && args.hasDefined(0)) { sepstr = ToString(cx, args[0]); if (!sepstr) @@ -1557,8 +1558,8 @@ typedef bool (*ComparatorNumeric)(const NumericElement &a, const NumericElement bool *lessOrEqualp); ComparatorNumeric SortComparatorNumerics[] = { - NULL, - NULL, + nullptr, + nullptr, ComparatorNumericLeftMinusRight, ComparatorNumericRightMinusLeft }; @@ -1580,8 +1581,8 @@ ComparatorInt32RightMinusLeft(const Value &a, const Value &b, bool *lessOrEqualp typedef bool (*ComparatorInt32)(const Value &a, const Value &b, bool *lessOrEqualp); ComparatorInt32 SortComparatorInt32s[] = { - NULL, - NULL, + nullptr, + nullptr, ComparatorInt32LeftMinusRight, ComparatorInt32RightMinusLeft }; @@ -1781,7 +1782,7 @@ js::array_sort(JSContext *cx, unsigned argc, Value *vp) if (args.hasDefined(0)) { if (args[0].isPrimitive()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_SORT_ARG); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_SORT_ARG); return false; } fval = args[0]; /* non-default compare function */ @@ -2934,7 +2935,7 @@ js_Array(JSContext *cx, unsigned argc, Value *vp) if (args[0].isInt32()) { int32_t i = args[0].toInt32(); if (i < 0) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_ARRAY_LENGTH); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_ARRAY_LENGTH); return false; } length = uint32_t(i); @@ -2942,7 +2943,7 @@ js_Array(JSContext *cx, unsigned argc, Value *vp) double d = args[0].toDouble(); length = ToUint32(d); if (d != double(length)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_ARRAY_LENGTH); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_ARRAY_LENGTH); return false; } } @@ -2980,15 +2981,15 @@ js_InitArrayClass(JSContext *cx, HandleObject obj) RootedObject proto(cx, global->getOrCreateObjectPrototype(cx)); if (!proto) - return NULL; + return nullptr; RootedTypeObject type(cx, cx->getNewType(&ArrayObject::class_, proto.get())); if (!type) - return NULL; + return nullptr; - JSObject *metadata = NULL; + JSObject *metadata = nullptr; if (!NewObjectMetadata(cx, &metadata)) - return NULL; + return nullptr; RootedShape shape(cx, EmptyShape::getInitialShape(cx, &ArrayObject::class_, TaggedProto(proto), proto->getParent(), metadata, @@ -2996,12 +2997,12 @@ js_InitArrayClass(JSContext *cx, HandleObject obj) RootedObject arrayProto(cx, JSObject::createArray(cx, gc::FINALIZE_OBJECT4, gc::TenuredHeap, shape, type, 0)); if (!arrayProto || !JSObject::setSingletonType(cx, arrayProto) || !AddLengthProperty(cx, arrayProto)) - return NULL; + return nullptr; RootedFunction ctor(cx); ctor = global->createConstructor(cx, js_Array, cx->names().Array, 1); if (!ctor) - return NULL; + return nullptr; /* * The default 'new' type of Array.prototype is required by type inference @@ -3010,19 +3011,19 @@ js_InitArrayClass(JSContext *cx, HandleObject obj) * be used without updating the indexed type set for such default arrays. */ if (!JSObject::setNewTypeUnknown(cx, &ArrayObject::class_, arrayProto)) - return NULL; + return nullptr; if (!LinkConstructorAndPrototype(cx, ctor, arrayProto)) - return NULL; + return nullptr; - if (!DefinePropertiesAndBrand(cx, arrayProto, NULL, array_methods) || - !DefinePropertiesAndBrand(cx, ctor, NULL, array_static_methods)) + if (!DefinePropertiesAndBrand(cx, arrayProto, nullptr, array_methods) || + !DefinePropertiesAndBrand(cx, ctor, nullptr, array_static_methods)) { - return NULL; + return nullptr; } if (!DefineConstructorAndPrototype(cx, global, JSProto_Array, ctor, arrayProto)) - return NULL; + return nullptr; return arrayProto; } @@ -3072,7 +3073,7 @@ NewArray(ExclusiveContext *cxArg, uint32_t length, arr->setFixedElements(); ArrayObject::setLength(cx, arr, length); if (allocateCapacity && !EnsureNewArrayElements(cx, arr, length)) - return NULL; + return nullptr; return arr; } } @@ -3083,15 +3084,15 @@ NewArray(ExclusiveContext *cxArg, uint32_t length, JS::PoisonPtr(&protoArg); if (!proto && !FindProto(cxArg, &ArrayObject::class_, &proto)) - return NULL; + return nullptr; RootedTypeObject type(cxArg, cxArg->getNewType(&ArrayObject::class_, proto.get())); if (!type) - return NULL; + return nullptr; - JSObject *metadata = NULL; + JSObject *metadata = nullptr; if (!NewObjectMetadata(cxArg, &metadata)) - return NULL; + return nullptr; /* * Get a shape with zero fixed slots, regardless of the size class. @@ -3101,23 +3102,23 @@ NewArray(ExclusiveContext *cxArg, uint32_t length, TaggedProto(proto), cxArg->global(), metadata, gc::FINALIZE_OBJECT0)); if (!shape) - return NULL; + return nullptr; Rooted arr(cxArg, JSObject::createArray(cxArg, allocKind, GetInitialHeap(newKind, &ArrayObject::class_), shape, type, length)); if (!arr) - return NULL; + return nullptr; if (shape->isEmptyShape()) { if (!AddLengthProperty(cxArg, arr)) - return NULL; + return nullptr; shape = arr->lastProperty(); EmptyShape::insertInitialShape(cxArg, shape, proto); } if (newKind == SingletonObject && !JSObject::setSingletonType(cxArg, arr)) - return NULL; + return nullptr; if (entry != -1) { cxArg->asJSContext()->runtime()->newObjectCache.fillGlobal(entry, &ArrayObject::class_, @@ -3125,28 +3126,28 @@ NewArray(ExclusiveContext *cxArg, uint32_t length, } if (allocateCapacity && !EnsureNewArrayElements(cxArg, arr, length)) - return NULL; + return nullptr; Probes::createObject(cxArg, arr); return arr; } ArrayObject * JS_FASTCALL -js::NewDenseEmptyArray(JSContext *cx, JSObject *proto /* = NULL */, +js::NewDenseEmptyArray(JSContext *cx, JSObject *proto /* = nullptr */, NewObjectKind newKind /* = GenericObject */) { return NewArray(cx, 0, proto, newKind); } ArrayObject * JS_FASTCALL -js::NewDenseAllocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto /* = NULL */, +js::NewDenseAllocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto /* = nullptr */, NewObjectKind newKind /* = GenericObject */) { return NewArray(cx, length, proto, newKind); } ArrayObject * JS_FASTCALL -js::NewDenseUnallocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto /* = NULL */, +js::NewDenseUnallocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto /* = nullptr */, NewObjectKind newKind /* = GenericObject */) { return NewArray(cx, length, proto, newKind); @@ -3154,13 +3155,13 @@ js::NewDenseUnallocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *pr ArrayObject * js::NewDenseCopiedArray(JSContext *cx, uint32_t length, HandleObject src, uint32_t elementOffset, - JSObject *proto /* = NULL */) + JSObject *proto /* = nullptr */) { JS_ASSERT(!src->isIndexed()); ArrayObject* arr = NewArray(cx, length, proto); if (!arr) - return NULL; + return nullptr; JS_ASSERT(arr->getDenseCapacity() >= length); @@ -3176,11 +3177,11 @@ js::NewDenseCopiedArray(JSContext *cx, uint32_t length, HandleObject src, uint32 // values must point at already-rooted Value objects ArrayObject * js::NewDenseCopiedArray(JSContext *cx, uint32_t length, const Value *values, - JSObject *proto /* = NULL */, NewObjectKind newKind /* = GenericObject */) + JSObject *proto /* = nullptr */, NewObjectKind newKind /* = GenericObject */) { ArrayObject* arr = NewArray(cx, length, proto); if (!arr) - return NULL; + return nullptr; JS_ASSERT(arr->getDenseCapacity() >= length); diff --git a/js/src/jsarray.h b/js/src/jsarray.h index a6b68a4b38ae..34210c14bc77 100644 --- a/js/src/jsarray.h +++ b/js/src/jsarray.h @@ -45,12 +45,12 @@ class ArrayObject; /* Create a dense array with no capacity allocated, length set to 0. */ extern ArrayObject * JS_FASTCALL -NewDenseEmptyArray(JSContext *cx, JSObject *proto = NULL, +NewDenseEmptyArray(JSContext *cx, JSObject *proto = nullptr, NewObjectKind newKind = GenericObject); /* Create a dense array with length and capacity == 'length', initialized length set to 0. */ extern ArrayObject * JS_FASTCALL -NewDenseAllocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto = NULL, +NewDenseAllocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto = nullptr, NewObjectKind newKind = GenericObject); /* @@ -58,16 +58,16 @@ NewDenseAllocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto = * contents. This is useful, e.g., when accepting length from the user. */ extern ArrayObject * JS_FASTCALL -NewDenseUnallocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto = NULL, +NewDenseUnallocatedArray(ExclusiveContext *cx, uint32_t length, JSObject *proto = nullptr, NewObjectKind newKind = GenericObject); /* Create a dense array with a copy of the dense array elements in src. */ extern ArrayObject * -NewDenseCopiedArray(JSContext *cx, uint32_t length, HandleObject src, uint32_t elementOffset, JSObject *proto = NULL); +NewDenseCopiedArray(JSContext *cx, uint32_t length, HandleObject src, uint32_t elementOffset, JSObject *proto = nullptr); /* Create a dense array from the given array values, which must be rooted */ extern ArrayObject * -NewDenseCopiedArray(JSContext *cx, uint32_t length, const Value *values, JSObject *proto = NULL, +NewDenseCopiedArray(JSContext *cx, uint32_t length, const Value *values, JSObject *proto = nullptr, NewObjectKind newKind = GenericObject); /* diff --git a/js/src/jsatom.cpp b/js/src/jsatom.cpp index 23f45fda1ec3..36cede3c9ef3 100644 --- a/js/src/jsatom.cpp +++ b/js/src/jsatom.cpp @@ -40,7 +40,7 @@ js::AtomToPrintableString(ExclusiveContext *cx, JSAtom *atom, JSAutoByteString * { JSString *str = js_QuoteString(cx, atom, 0); if (!str) - return NULL; + return nullptr; return bytes->encodeLatin1(cx, str); } @@ -170,7 +170,7 @@ js::InitCommonNames(JSContext *cx) void js::FinishCommonNames(JSRuntime *rt) { - rt->emptyString = NULL; + rt->emptyString = nullptr; #ifdef DEBUG memset(&rt->atomState, JS_FREE_PATTERN, sizeof(JSAtomState)); #endif @@ -265,7 +265,7 @@ AtomizeAndTakeOwnership(ExclusiveContext *cx, jschar *tbchars, size_t length, In JSFlatString *flat = js_NewString(cx, tbchars, length); if (!flat) { js_free(tbchars); - return NULL; + return nullptr; } JSAtom *atom = flat->morphAtomizedStringIntoAtom(); @@ -273,7 +273,7 @@ AtomizeAndTakeOwnership(ExclusiveContext *cx, jschar *tbchars, size_t length, In if (!atoms.relookupOrAdd(p, AtomHasher::Lookup(tbchars, length), AtomStateEntry(atom, bool(ib)))) { js_ReportOutOfMemory(cx); /* SystemAllocPolicy does not report OOM. */ - return NULL; + return nullptr; } return atom; @@ -310,7 +310,7 @@ AtomizeAndCopyChars(ExclusiveContext *cx, const jschar *tbchars, size_t length, JSFlatString *flat = js_NewStringCopyN(cx, tbchars, length); if (!flat) - return NULL; + return nullptr; JSAtom *atom = flat->morphAtomizedStringIntoAtom(); @@ -318,7 +318,7 @@ AtomizeAndCopyChars(ExclusiveContext *cx, const jschar *tbchars, size_t length, AtomStateEntry(atom, bool(ib)))) { if (allowGC) js_ReportOutOfMemory(cx); /* SystemAllocPolicy does not report OOM. */ - return NULL; + return nullptr; } return atom; @@ -347,17 +347,17 @@ js::AtomizeString(ExclusiveContext *cx, JSString *str, const jschar *chars = str->getChars(cx); if (!chars) - return NULL; + return nullptr; if (JSAtom *atom = AtomizeAndCopyChars(cx, chars, str->length(), ib)) return atom; if (!cx->isJSContext() || !allowGC) - return NULL; + return nullptr; JSLinearString *linear = str->ensureLinear(cx->asJSContext()); if (!linear) - return NULL; + return nullptr; JS_ASSERT(linear->length() <= JSString::MAX_LENGTH); return AtomizeAndCopyChars(cx, linear->chars(), linear->length(), ib); @@ -376,7 +376,7 @@ js::AtomizeMaybeGC(ExclusiveContext *cx, const char *bytes, size_t length, Inter CHECK_REQUEST(cx); if (!JSString::validateLength(cx, length)) - return NULL; + return nullptr; static const unsigned ATOMIZE_BUF_MAX = 32; if (length < ATOMIZE_BUF_MAX) { @@ -394,7 +394,7 @@ js::AtomizeMaybeGC(ExclusiveContext *cx, const char *bytes, size_t length, Inter jschar *tbcharsZ = InflateString(cx, bytes, &length); if (!tbcharsZ) - return NULL; + return nullptr; return AtomizeAndTakeOwnership(cx, tbcharsZ, length, ib); } @@ -419,7 +419,7 @@ js::AtomizeChars(ExclusiveContext *cx, const jschar *chars, size_t length, Inter CHECK_REQUEST(cx); if (!JSString::validateLength(cx, length)) - return NULL; + return nullptr; return AtomizeAndCopyChars(cx, chars, length, ib); } @@ -466,10 +466,10 @@ ToAtomSlow(ExclusiveContext *cx, typename MaybeRooted::HandleTyp Value v = arg; if (!v.isPrimitive()) { if (!cx->shouldBeJSContext() || !allowGC) - return NULL; + return nullptr; RootedValue v2(cx, v); if (!ToPrimitive(cx->asJSContext(), JSTYPE_STRING, &v2)) - return NULL; + return nullptr; v = v2; } diff --git a/js/src/jsatom.h b/js/src/jsatom.h index 9efd02decfe0..860da0401724 100644 --- a/js/src/jsatom.h +++ b/js/src/jsatom.h @@ -89,7 +89,7 @@ struct AtomHasher size_t length; const JSAtom *atom; /* Optional. */ - Lookup(const jschar *chars, size_t length) : chars(chars), length(length), atom(NULL) {} + Lookup(const jschar *chars, size_t length) : chars(chars), length(length), atom(nullptr) {} inline Lookup(const JSAtom *atom); }; diff --git a/js/src/jsatominlines.h b/js/src/jsatominlines.h index c4fe0572a4ff..15a73a5f82e4 100644 --- a/js/src/jsatominlines.h +++ b/js/src/jsatominlines.h @@ -154,7 +154,7 @@ IdToString(JSContext *cx, jsid id) RootedValue idv(cx, IdToValue(id)); JSString *str = ToStringSlow(cx, idv); if (!str) - return NULL; + return nullptr; return str->ensureFlat(cx); } diff --git a/js/src/jsbool.cpp b/js/src/jsbool.cpp index c6aef36fb4f8..71c61bb8feec 100644 --- a/js/src/jsbool.cpp +++ b/js/src/jsbool.cpp @@ -142,35 +142,35 @@ js_InitBooleanClass(JSContext *cx, HandleObject obj) RootedObject booleanProto (cx, global->createBlankPrototype(cx, &BooleanObject::class_)); if (!booleanProto) - return NULL; + return nullptr; booleanProto->setFixedSlot(BooleanObject::PRIMITIVE_VALUE_SLOT, BooleanValue(false)); RootedFunction ctor(cx, global->createConstructor(cx, Boolean, cx->names().Boolean, 1)); if (!ctor) - return NULL; + return nullptr; if (!LinkConstructorAndPrototype(cx, ctor, booleanProto)) - return NULL; + return nullptr; - if (!DefinePropertiesAndBrand(cx, booleanProto, NULL, boolean_methods)) - return NULL; + if (!DefinePropertiesAndBrand(cx, booleanProto, nullptr, boolean_methods)) + return nullptr; Handle valueOfName = cx->names().valueOf; RootedFunction valueOf(cx, NewFunction(cx, NullPtr(), bool_valueOf, 0, JSFunction::NATIVE_FUN, global, valueOfName)); if (!valueOf) - return NULL; + return nullptr; RootedValue value(cx, ObjectValue(*valueOf)); if (!JSObject::defineProperty(cx, booleanProto, valueOfName, value, JS_PropertyStub, JS_StrictPropertyStub, 0)) { - return NULL; + return nullptr; } if (!DefineConstructorAndPrototype(cx, global, JSProto_Boolean, ctor, booleanProto)) - return NULL; + return nullptr; return booleanProto; } diff --git a/js/src/jscntxt.cpp b/js/src/jscntxt.cpp index 7be1fbd7eae8..7e691056fdbf 100644 --- a/js/src/jscntxt.cpp +++ b/js/src/jscntxt.cpp @@ -122,7 +122,7 @@ js::CloneFunctionAtCallsite(JSContext *cx, HandleFunction fun, HandleScript scri Table &table = cx->compartment()->callsiteClones; if (!table.initialized() && !table.init()) - return NULL; + return nullptr; uint32_t offset = pc - script->code; void* originalScript = script; @@ -138,7 +138,7 @@ js::CloneFunctionAtCallsite(JSContext *cx, HandleFunction fun, HandleScript scri RootedObject parent(cx, fun->environment()); RootedFunction clone(cx, CloneFunctionObject(cx, fun, parent)); if (!clone) - return NULL; + return nullptr; /* * Store a link back to the original for function.caller and avoid cloning @@ -157,7 +157,7 @@ js::CloneFunctionAtCallsite(JSContext *cx, HandleFunction fun, HandleScript scri } if (!table.relookupOrAdd(p, key, clone.get())) - return NULL; + return nullptr; return clone; } @@ -169,11 +169,11 @@ js::NewContext(JSRuntime *rt, size_t stackChunkSize) JSContext *cx = js_new(rt); if (!cx) - return NULL; + return nullptr; if (!cx->cycleDetectorSet.init()) { js_delete(cx); - return NULL; + return nullptr; } /* @@ -204,7 +204,7 @@ js::NewContext(JSRuntime *rt, size_t stackChunkSize) #endif if (!ok) { DestroyContext(cx, DCM_NEW_FAILED); - return NULL; + return nullptr; } rt->haveCreatedContext = true; } @@ -212,7 +212,7 @@ js::NewContext(JSRuntime *rt, size_t stackChunkSize) JSContextCallback cxCallback = rt->cxCallback; if (cxCallback && !cxCallback(cx, JSCONTEXT_NEW, rt->cxCallbackData)) { DestroyContext(cx, DCM_NEW_FAILED); - return NULL; + return nullptr; } return cx; @@ -231,7 +231,7 @@ js::DestroyContext(JSContext *cx, DestroyContextMode mode) #if (defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING)) && defined(DEBUG) for (int i = 0; i < THING_ROOT_LIMIT; ++i) - JS_ASSERT(cx->thingGCRooters[i] == NULL); + JS_ASSERT(cx->thingGCRooters[i] == nullptr); #endif if (mode != DCM_NEW_FAILED) { @@ -362,7 +362,7 @@ js_ReportOutOfMemory(ThreadSafeContext *cxArg) /* Get the message for this error, but we don't expand any arguments. */ const JSErrorFormatString *efs = - js_GetLocalizedErrorMessage(cx, NULL, NULL, JSMSG_OUT_OF_MEMORY); + js_GetLocalizedErrorMessage(cx, nullptr, nullptr, JSMSG_OUT_OF_MEMORY); const char *msg = efs ? efs->format : "Out of memory"; /* Fill out the report, but don't do anything that requires allocation. */ @@ -406,7 +406,7 @@ js_ReportOverRecursed(JSContext *maybecx) fprintf(stderr, "js_ReportOverRecursed called\n"); #endif if (maybecx) - JS_ReportErrorNumber(maybecx, js_GetErrorMessage, NULL, JSMSG_OVER_RECURSED); + JS_ReportErrorNumber(maybecx, js_GetErrorMessage, nullptr, JSMSG_OVER_RECURSED); } void @@ -423,7 +423,7 @@ js_ReportAllocationOverflow(ThreadSafeContext *cxArg) JSContext *cx = cxArg->asJSContext(); AutoSuppressGC suppressGC(cx); - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_ALLOC_OVERFLOW); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_ALLOC_OVERFLOW); } /* @@ -486,7 +486,7 @@ js_ReportErrorVA(JSContext *cx, unsigned flags, const char *format, va_list ap) warning = JSREPORT_IS_WARNING(report.flags); - ReportError(cx, message, &report, NULL, NULL); + ReportError(cx, message, &report, nullptr, nullptr); js_free(message); js_free(ucmessage); return warning; @@ -534,7 +534,7 @@ js::PrintError(JSContext *cx, FILE *file, const char *message, JSErrorReport *re if (JSREPORT_IS_WARNING(report->flags) && !reportWarnings) return false; - char *prefix = NULL; + char *prefix = nullptr; if (report->filename) prefix = JS_smprintf("%s:", report->filename); if (report->lineno) { @@ -598,7 +598,7 @@ js_strdup(ExclusiveContext *cx, const char *s) size_t n = strlen(s) + 1; void *p = cx->malloc_(n); if (!p) - return NULL; + return nullptr; return (char *)js_memcpy(p, s, n); } @@ -624,13 +624,13 @@ js_ExpandErrorArguments(ExclusiveContext *cx, JSErrorCallback callback, int argCount; bool messageArgsPassed = !!reportp->messageArgs; - *messagep = NULL; + *messagep = nullptr; - /* Most calls supply js_GetErrorMessage; if this is so, assume NULL. */ + /* Most calls supply js_GetErrorMessage; if this is so, assume nullptr. */ if (!callback || callback == js_GetErrorMessage) - efs = js_GetLocalizedErrorMessage(cx, userRef, NULL, errorNumber); + efs = js_GetLocalizedErrorMessage(cx, userRef, nullptr, errorNumber); else - efs = callback(userRef, NULL, errorNumber); + efs = callback(userRef, nullptr, errorNumber); if (efs) { reportp->exnType = efs->exnType; @@ -651,8 +651,8 @@ js_ExpandErrorArguments(ExclusiveContext *cx, JSErrorCallback callback, reportp->messageArgs = cx->pod_malloc(argCount + 1); if (!reportp->messageArgs) return false; - /* NULL-terminate for easy copying. */ - reportp->messageArgs[argCount] = NULL; + /* nullptr-terminate for easy copying. */ + reportp->messageArgs[argCount] = nullptr; } for (i = 0; i < argCount; i++) { if (messageArgsPassed) { @@ -741,7 +741,7 @@ js_ExpandErrorArguments(ExclusiveContext *cx, JSErrorCallback callback, } } } - if (*messagep == NULL) { + if (*messagep == nullptr) { /* where's the right place for this ??? */ const char *defaultErrorMessage = "No error message available for error number %d"; @@ -762,15 +762,15 @@ error: js_free((void *)reportp->messageArgs[i++]); } js_free((void *)reportp->messageArgs); - reportp->messageArgs = NULL; + reportp->messageArgs = nullptr; } if (reportp->ucmessage) { js_free((void *)reportp->ucmessage); - reportp->ucmessage = NULL; + reportp->ucmessage = nullptr; } if (*messagep) { js_free((void *)*messagep); - *messagep = NULL; + *messagep = nullptr; } return false; } @@ -866,7 +866,7 @@ js_ReportErrorAgain(JSContext *cx, const char *message, JSErrorReport *reportp) if (onError) { JSDebugErrorHook hook = cx->runtime()->debugHooks.debugErrorHook; if (hook && !hook(cx, message, reportp, cx->runtime()->debugHooks.debugErrorHookData)) - onError = NULL; + onError = nullptr; } if (onError) onError(cx, message, reportp); @@ -875,7 +875,7 @@ js_ReportErrorAgain(JSContext *cx, const char *message, JSErrorReport *reportp) void js_ReportIsNotDefined(JSContext *cx, const char *name) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_DEFINED, name); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_DEFINED, name); } bool @@ -892,20 +892,20 @@ js_ReportIsNullOrUndefined(JSContext *cx, int spindex, HandleValue v, if (strcmp(bytes, js_undefined_str) == 0 || strcmp(bytes, js_null_str) == 0) { ok = JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_NO_PROPERTIES, bytes, - NULL, NULL); + nullptr, nullptr); } else if (v.isUndefined()) { ok = JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, bytes, - js_undefined_str, NULL); + js_undefined_str, nullptr); } else { JS_ASSERT(v.isNull()); ok = JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, bytes, - js_null_str, NULL); + js_null_str, nullptr); } js_free(bytes); @@ -920,7 +920,7 @@ js_ReportMissingArg(JSContext *cx, HandleValue v, unsigned arg) RootedAtom atom(cx); JS_snprintf(argbuf, sizeof argbuf, "%u", arg); - bytes = NULL; + bytes = nullptr; if (IsFunctionObject(v)) { atom = v.toObject().as().atom(); bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, @@ -928,7 +928,7 @@ js_ReportMissingArg(JSContext *cx, HandleValue v, unsigned arg) if (!bytes) return; } - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MISSING_FUN_ARG, argbuf, bytes ? bytes : ""); js_free(bytes); @@ -949,7 +949,7 @@ js_ReportValueErrorFlags(JSContext *cx, unsigned flags, const unsigned errorNumb return false; ok = JS_ReportErrorFlagsAndNumber(cx, flags, js_GetErrorMessage, - NULL, errorNumber, bytes, arg1, arg2); + nullptr, errorNumber, bytes, arg1, arg2); js_free(bytes); return ok; } @@ -966,7 +966,7 @@ js_GetErrorMessage(void *userRef, const char *locale, const unsigned errorNumber { if ((errorNumber > 0) && (errorNumber < JSErr_Limit)) return &js_ErrorFormatString[errorNumber]; - return NULL; + return nullptr; } bool @@ -1024,7 +1024,7 @@ js::ThreadSafeContext::ThreadSafeContext(JSRuntime *rt, PerThreadData *pt, Conte : ContextFriendFields(rt), contextKind_(kind), perThreadData(pt), - allocator_(NULL) + allocator_(nullptr) { } bool @@ -1046,14 +1046,14 @@ JSContext::JSContext(JSRuntime *rt) exception(UndefinedValue()), options_(0), reportGranularity(JS_DEFAULT_JITREPORT_GRANULARITY), - resolvingList(NULL), + resolvingList(nullptr), generatingError(false), savedFrameChains_(), - defaultCompartmentObject_(NULL), + defaultCompartmentObject_(nullptr), cycleDetectorSet(MOZ_THIS_IN_INITIALIZER_LIST()), - errorReporter(NULL), - data(NULL), - data2(NULL), + errorReporter(nullptr), + data(nullptr), + data2(nullptr), #ifdef JS_THREADSAFE outstandingRequests(0), #endif @@ -1061,9 +1061,9 @@ JSContext::JSContext(JSRuntime *rt) iterValue(MagicValue(JS_NO_ITER_VALUE)), jitIsBroken(false), #ifdef MOZ_TRACE_JSCALLS - functionCallback(NULL), + functionCallback(nullptr), #endif - innermostGenerator_(NULL) + innermostGenerator_(nullptr) { #ifdef DEBUG stackIterAssertionEnabled = true; @@ -1107,7 +1107,7 @@ JSContext::leaveGenerator(JSGenerator *gen) { JS_ASSERT(innermostGenerator_ == gen); innermostGenerator_ = innermostGenerator_->prevGenerator; - gen->prevGenerator = NULL; + gen->prevGenerator = nullptr; } @@ -1126,7 +1126,7 @@ JSContext::saveFrameChain() if (Activation *act = mainThread().activation()) act->saveFrameChain(); - setCompartment(NULL); + setCompartment(nullptr); enterCompartmentDepth_ = 0; return true; @@ -1197,7 +1197,7 @@ ComputeIsJITBroken() "SCH-I500", // Samsung i9000, Fascinate device "SPH-D700", // Samsung i9000, Epic device "GT-I9000", // Samsung i9000, UK/Europe device - NULL + nullptr }; for (const char* const* hw = &blacklist[0]; *hw; ++hw) { if (line.npos != line.find(*hw)) { @@ -1267,7 +1267,7 @@ JSContext::mark(JSTracer *trc) JSVersion JSContext::findVersion() const { - if (JSScript *script = currentScript(NULL, ALLOW_CROSS_COMPARTMENT)) + if (JSScript *script = currentScript(nullptr, ALLOW_CROSS_COMPARTMENT)) return script->getVersion(); if (compartment() && compartment()->options().version() != JSVERSION_UNKNOWN) diff --git a/js/src/jscntxt.h b/js/src/jscntxt.h index d9b82ed90e46..40c1cede420f 100644 --- a/js/src/jscntxt.h +++ b/js/src/jscntxt.h @@ -162,13 +162,13 @@ struct ThreadSafeContext : ContextFriendFields, JSContext *maybeJSContext() const { if (isJSContext()) return (JSContext *) this; - return NULL; + return nullptr; } JSContext *asJSContext() const { // Note: there is no way to perform an unchecked coercion from a // ThreadSafeContext to a JSContext. This ensures that trying to use - // the context as a JSContext off the main thread will NULL crash + // the context as a JSContext off the main thread will nullptr crash // rather than race. JS_ASSERT(isJSContext()); return maybeJSContext(); @@ -193,7 +193,7 @@ struct ThreadSafeContext : ContextFriendFields, ExclusiveContext *maybeExclusiveContext() const { if (isExclusiveContext()) return (ExclusiveContext *) this; - return NULL; + return nullptr; } ExclusiveContext *asExclusiveContext() const { @@ -302,7 +302,7 @@ class ExclusiveContext : public ThreadSafeContext ExclusiveContext(JSRuntime *rt, PerThreadData *pt, ContextKind kind) : ThreadSafeContext(rt, pt, kind), - workerThread_(NULL), + workerThread_(nullptr), enterCompartmentDepth_(0) {} @@ -358,7 +358,7 @@ class ExclusiveContext : public ThreadSafeContext // Zone local methods that can be used freely from an ExclusiveContext. inline bool typeInferenceEnabled() const; - types::TypeObject *getNewType(const Class *clasp, TaggedProto proto, JSFunction *fun = NULL); + types::TypeObject *getNewType(const Class *clasp, TaggedProto proto, JSFunction *fun = nullptr); types::TypeObject *getLazyType(const Class *clasp, TaggedProto proto); inline js::LifoAlloc &typeLifoAlloc(); @@ -534,14 +534,14 @@ struct JSContext : public js::ExclusiveContext, /* * Get the topmost script and optional pc on the stack. By default, this * function only returns a JSScript in the current compartment, returning - * NULL if the current script is in a different compartment. This behavior - * can be overridden by passing ALLOW_CROSS_COMPARTMENT. + * nullptr if the current script is in a different compartment. This + * behavior can be overridden by passing ALLOW_CROSS_COMPARTMENT. */ enum MaybeAllowCrossCompartment { DONT_ALLOW_CROSS_COMPARTMENT = false, ALLOW_CROSS_COMPARTMENT = true }; - inline JSScript *currentScript(jsbytecode **pc = NULL, + inline JSScript *currentScript(jsbytecode **pc = nullptr, MaybeAllowCrossCompartment = DONT_ALLOW_CROSS_COMPARTMENT) const; #ifdef MOZ_TRACE_JSCALLS @@ -765,10 +765,10 @@ extern void ReportUsageError(JSContext *cx, HandleObject callee, const char *msg); /* - * Prints a full report and returns true if the given report is non-NULL and - * the report doesn't have the JSREPORT_WARNING flag set or reportWarnings is - * true. - * Returns false otherwise, printing just the message if the report is NULL. + * Prints a full report and returns true if the given report is non-nullptr + * and the report doesn't have the JSREPORT_WARNING flag set or reportWarnings + * is true. + * Returns false otherwise, printing just the message if the report is nullptr. */ extern bool PrintError(JSContext *cx, FILE *file, const char *message, JSErrorReport *report, @@ -807,11 +807,11 @@ js_ReportValueErrorFlags(JSContext *cx, unsigned flags, const unsigned errorNumb #define js_ReportValueError(cx,errorNumber,spindex,v,fallback) \ ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \ - spindex, v, fallback, NULL, NULL)) + spindex, v, fallback, nullptr, nullptr)) #define js_ReportValueError2(cx,errorNumber,spindex,v,fallback,arg1) \ ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \ - spindex, v, fallback, arg1, NULL)) + spindex, v, fallback, arg1, nullptr)) #define js_ReportValueError3(cx,errorNumber,spindex,v,fallback,arg1,arg2) \ ((void)js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, \ diff --git a/js/src/jscntxtinlines.h b/js/src/jscntxtinlines.h index 682fbfdaefc3..98e7ae153b3e 100644 --- a/js/src/jscntxtinlines.h +++ b/js/src/jscntxtinlines.h @@ -387,7 +387,7 @@ class AutoLockForExclusiveAccess if (runtime->numExclusiveThreads) { JS_ASSERT(runtime->exclusiveAccessOwner == PR_GetCurrentThread()); #ifdef DEBUG - runtime->exclusiveAccessOwner = NULL; + runtime->exclusiveAccessOwner = nullptr; #endif PR_Unlock(runtime->exclusiveAccessLock); } else { @@ -501,8 +501,8 @@ js::ExclusiveContext::setCompartment(JSCompartment *comp) JS_ASSERT_IF(comp, comp->hasBeenEntered()); compartment_ = comp; - zone_ = comp ? comp->zone() : NULL; - allocator_ = zone_ ? &zone_->allocator : NULL; + zone_ = comp ? comp->zone() : nullptr; + allocator_ = zone_ ? &zone_->allocator : nullptr; } inline JSScript * @@ -510,23 +510,23 @@ JSContext::currentScript(jsbytecode **ppc, MaybeAllowCrossCompartment allowCrossCompartment) const { if (ppc) - *ppc = NULL; + *ppc = nullptr; js::Activation *act = mainThread().activation(); while (act && (act->cx() != this || (act->isJit() && !act->asJit()->isActive()))) act = act->prev(); if (!act) - return NULL; + return nullptr; JS_ASSERT(act->cx() == this); #ifdef JS_ION if (act->isJit()) { - JSScript *script = NULL; + JSScript *script = nullptr; js::jit::GetPcScript(const_cast(this), &script, ppc); if (!allowCrossCompartment && script->compartment() != compartment()) - return NULL; + return nullptr; return script; } #endif @@ -538,7 +538,7 @@ JSContext::currentScript(jsbytecode **ppc, JSScript *script = fp->script(); if (!allowCrossCompartment && script->compartment() != compartment()) - return NULL; + return nullptr; if (ppc) { *ppc = act->asInterpreter()->regs().pc; diff --git a/js/src/jscompartment.cpp b/js/src/jscompartment.cpp index 2559deb3d76e..b29c18ef5ffb 100644 --- a/js/src/jscompartment.cpp +++ b/js/src/jscompartment.cpp @@ -38,35 +38,35 @@ JSCompartment::JSCompartment(Zone *zone, const JS::CompartmentOptions &options = : options_(options), zone_(zone), runtime_(zone->runtimeFromMainThread()), - principals(NULL), + principals(nullptr), isSystem(false), marked(true), #ifdef DEBUG firedOnNewGlobalObject(false), #endif - global_(NULL), + global_(nullptr), enterCompartmentDepth(0), lastCodeRelease(0), - data(NULL), - objectMetadataCallback(NULL), + data(nullptr), + objectMetadataCallback(nullptr), lastAnimationTime(0), regExps(runtime_), typeReprs(runtime_), globalWriteBarriered(false), propertyTree(thisForCtor()), - gcIncomingGrayPointers(NULL), - gcLiveArrayBuffers(NULL), - gcWeakMapList(NULL), + gcIncomingGrayPointers(nullptr), + gcLiveArrayBuffers(nullptr), + gcWeakMapList(nullptr), debugModeBits(runtime_->debugMode ? DebugFromC : 0), rngState(0), - watchpointMap(NULL), - scriptCountsMap(NULL), - debugScriptMap(NULL), - debugScopes(NULL), - enumerators(NULL), - compartmentStats(NULL) + watchpointMap(nullptr), + scriptCountsMap(nullptr), + debugScriptMap(nullptr), + debugScopes(nullptr), + enumerators(nullptr), + compartmentStats(nullptr) #ifdef JS_ION - , ionCompartment_(NULL) + , ionCompartment_(nullptr) #endif { runtime_->numCompartments++; @@ -131,19 +131,19 @@ JSRuntime::createIonRuntime(JSContext *cx) ionRuntime_ = cx->new_(); if (!ionRuntime_) - return NULL; + return nullptr; if (!ionRuntime_->initialize(cx)) { js_delete(ionRuntime_); - ionRuntime_ = NULL; + ionRuntime_ = nullptr; JSCompartment *comp = cx->runtime()->atomsCompartment(); if (comp->ionCompartment_) { js_delete(comp->ionCompartment_); - comp->ionCompartment_ = NULL; + comp->ionCompartment_ = nullptr; } - return NULL; + return nullptr; } return ionRuntime_; @@ -168,7 +168,7 @@ JSCompartment::ensureIonCompartmentExists(JSContext *cx) if (!ionCompartment_->initialize(cx)) { js_delete(ionCompartment_); - ionCompartment_ = NULL; + ionCompartment_ = nullptr; return false; } @@ -278,7 +278,7 @@ JSCompartment::wrap(JSContext *cx, MutableHandleObject obj, HandleObject existin /* * Wrappers should really be parented to the wrapped parent of the wrapped - * object, but in that case a wrapped global object would have a NULL + * object, but in that case a wrapped global object would have a nullptr * parent without being a proper global object (JSCLASS_IS_GLOBAL). Instead, * we parent all wrappers to the global object in their home compartment. * This loses us some transparency, and is generally very cheesy. @@ -343,7 +343,7 @@ JSCompartment::wrap(JSContext *cx, MutableHandleObject obj, HandleObject existin existing->getParent() != global || obj->isCallable()) { - existing = NULL; + existing = nullptr; } } @@ -518,7 +518,7 @@ JSCompartment::sweep(FreeOp *fop, bool releaseTypes) sweepCallsiteClones(); if (global_ && IsObjectAboutToBeFinalized(global_.unsafeGet())) - global_ = NULL; + global_ = nullptr; #ifdef JS_ION if (ionCompartment_) @@ -593,7 +593,7 @@ JSCompartment::purge() void JSCompartment::clearTables() { - global_ = NULL; + global_ = nullptr; regExps.clearTables(); @@ -722,7 +722,7 @@ JSCompartment::setDebugModeFromC(JSContext *cx, bool b, AutoDebugModeGC &dmgc) if (enabledBefore != enabledAfter) { onStack = hasScriptsOnStack(); if (b && onStack) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEBUG_NOT_IDLE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEBUG_NOT_IDLE); return false; } if (enabledAfter && !CreateLazyScriptsForCompartment(cx)) diff --git a/js/src/jscompartment.h b/js/src/jscompartment.h index 62aa011cd491..d86d68e105fa 100644 --- a/js/src/jscompartment.h +++ b/js/src/jscompartment.h @@ -35,14 +35,14 @@ struct NativeIterator; class DtoaCache { double d; int base; - JSFlatString *s; // if s==NULL, d and base are not valid + JSFlatString *s; // if s==nullptr, d and base are not valid public: - DtoaCache() : s(NULL) {} - void purge() { s = NULL; } + DtoaCache() : s(nullptr) {} + void purge() { s = nullptr; } JSFlatString *lookup(int base, double d) { - return this->s && base == this->base && d == this->d ? this->s : NULL; + return this->s && base == this->base && d == this->d ? this->s : nullptr; } void cache(int base, double d, JSFlatString *s) { @@ -71,18 +71,18 @@ struct CrossCompartmentKey js::gc::Cell *wrapped; CrossCompartmentKey() - : kind(ObjectWrapper), debugger(NULL), wrapped(NULL) {} + : kind(ObjectWrapper), debugger(nullptr), wrapped(nullptr) {} CrossCompartmentKey(JSObject *wrapped) - : kind(ObjectWrapper), debugger(NULL), wrapped(wrapped) {} + : kind(ObjectWrapper), debugger(nullptr), wrapped(wrapped) {} CrossCompartmentKey(JSString *wrapped) - : kind(StringWrapper), debugger(NULL), wrapped(wrapped) {} + : kind(StringWrapper), debugger(nullptr), wrapped(wrapped) {} CrossCompartmentKey(Value wrapped) : kind(wrapped.isString() ? StringWrapper : ObjectWrapper), - debugger(NULL), + debugger(nullptr), wrapped((js::gc::Cell *)wrapped.toGCThing()) {} CrossCompartmentKey(const RootedValue &wrapped) : kind(wrapped.get().isString() ? StringWrapper : ObjectWrapper), - debugger(NULL), + debugger(nullptr), wrapped((js::gc::Cell *)wrapped.get().toGCThing()) {} CrossCompartmentKey(Kind kind, JSObject *dbg, js::gc::Cell *wrapped) : kind(kind), debugger(dbg), wrapped(wrapped) {} @@ -165,11 +165,11 @@ struct JSCompartment } /* - * Nb: global_ might be NULL, if (a) it's the atoms compartment, or (b) the - * compartment's global has been collected. The latter can happen if e.g. - * a string in a compartment is rooted but no object is, and thus the global - * isn't rooted, and thus the global can be finalized while the compartment - * lives on. + * Nb: global_ might be nullptr, if (a) it's the atoms compartment, or + * (b) the compartment's global has been collected. The latter can happen + * if e.g. a string in a compartment is rooted but no object is, and thus + * the global isn't rooted, and thus the global can be finalized while the + * compartment lives on. * * In contrast, JSObject::global() is infallible because marking a JSObject * always marks its global as well. @@ -366,10 +366,10 @@ struct JSCompartment bool addDebuggee(JSContext *cx, js::GlobalObject *global, js::AutoDebugModeGC &dmgc); void removeDebuggee(js::FreeOp *fop, js::GlobalObject *global, - js::GlobalObjectSet::Enum *debuggeesEnum = NULL); + js::GlobalObjectSet::Enum *debuggeesEnum = nullptr); void removeDebuggee(js::FreeOp *fop, js::GlobalObject *global, js::AutoDebugModeGC &dmgc, - js::GlobalObjectSet::Enum *debuggeesEnum = NULL); + js::GlobalObjectSet::Enum *debuggeesEnum = nullptr); bool setDebugModeFromC(JSContext *cx, bool b, js::AutoDebugModeGC &dmgc); void clearBreakpointsIn(js::FreeOp *fop, js::Debugger *dbg, JSObject *handler); diff --git a/js/src/jscrashreport.cpp b/js/src/jscrashreport.cpp index a2fff123e0fb..cdfdb6edd083 100644 --- a/js/src/jscrashreport.cpp +++ b/js/src/jscrashreport.cpp @@ -158,7 +158,7 @@ Stack::Stack(uint64_t id) bool Stack::snapshot() { - snaptime = time(NULL); + snaptime = time(nullptr); return GetStack(&stack_base, &stack_len, ®s, stack, sizeof(stack)); } @@ -182,7 +182,7 @@ Ring::Ring(uint64_t id) void Ring::push(uint64_t tag, void *data, size_t size) { - uint64_t t = time(NULL); + uint64_t t = time(nullptr); copyBytes(&tag, sizeof(uint64_t)); copyBytes(&t, sizeof(uint64_t)); diff --git a/js/src/jsdate.cpp b/js/src/jsdate.cpp index 3571291d2d2a..8bdcec504e51 100644 --- a/js/src/jsdate.cpp +++ b/js/src/jsdate.cpp @@ -2445,7 +2445,7 @@ date_toISOString_impl(JSContext *cx, CallArgs args) { double utctime = args.thisv().toObject().as().UTCTime().toNumber(); if (!IsFinite(utctime)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INVALID_DATE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INVALID_DATE); return false; } @@ -2496,7 +2496,7 @@ date_toJSON(JSContext *cx, unsigned argc, Value *vp) /* Step 5. */ if (!js_IsCallable(toISO)) { - JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, NULL, + JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, nullptr, JSMSG_BAD_TOISOSTRING_PROP); return false; } @@ -3036,19 +3036,19 @@ js_InitDateClass(JSContext *cx, HandleObject obj) RootedObject dateProto(cx, global->createBlankPrototype(cx, &DateObject::class_)); if (!dateProto) - return NULL; + return nullptr; dateProto->as().setUTCTime(GenericNaN()); RootedFunction ctor(cx); ctor = global->createConstructor(cx, js_Date, cx->names().Date, MAXARGS); if (!ctor) - return NULL; + return nullptr; if (!LinkConstructorAndPrototype(cx, ctor, dateProto)) - return NULL; + return nullptr; - if (!DefinePropertiesAndBrand(cx, ctor, NULL, date_static_methods)) - return NULL; + if (!DefinePropertiesAndBrand(cx, ctor, nullptr, date_static_methods)) + return nullptr; /* * Define all Date.prototype.* functions, then brand for trace-jitted code. @@ -3056,7 +3056,7 @@ js_InitDateClass(JSContext *cx, HandleObject obj) * Date.prototype.toUTCString. */ if (!JS_DefineFunctions(cx, dateProto, date_methods)) - return NULL; + return nullptr; RootedValue toUTCStringFun(cx); RootedId toUTCStringId(cx, NameToId(cx->names().toUTCString)); RootedId toGMTStringId(cx, NameToId(cx->names().toGMTString)); @@ -3064,11 +3064,11 @@ js_InitDateClass(JSContext *cx, HandleObject obj) !baseops::DefineGeneric(cx, dateProto, toGMTStringId, toUTCStringFun, JS_PropertyStub, JS_StrictPropertyStub, 0)) { - return NULL; + return nullptr; } if (!DefineConstructorAndPrototype(cx, global, JSProto_Date, ctor, dateProto)) - return NULL; + return nullptr; return dateProto; } @@ -3078,7 +3078,7 @@ js_NewDateObjectMsec(JSContext *cx, double msec_time) { JSObject *obj = NewBuiltinClassInstance(cx, &DateObject::class_); if (!obj) - return NULL; + return nullptr; obj->as().setUTCTime(msec_time); return obj; } diff --git a/js/src/jsdtoa.cpp b/js/src/jsdtoa.cpp index 9c1fbf7f1d9f..c996cbd34b9b 100644 --- a/js/src/jsdtoa.cpp +++ b/js/src/jsdtoa.cpp @@ -96,13 +96,13 @@ js_dtostr(DtoaState *state, char *buffer, size_t bufferSize, JSDToStrMode mode, dval(d) = dinput; numBegin = dtoa(PASS_STATE d, dtoaModes[mode], precision, &decPt, &sign, &numEnd); if (!numBegin) { - return NULL; + return nullptr; } nDigits = numEnd - numBegin; JS_ASSERT((size_t) nDigits <= bufferSize - 2); if ((size_t) nDigits > bufferSize - 2) { - return NULL; + return nullptr; } js_memcpy(buffer + 2, numBegin, nDigits); @@ -300,7 +300,7 @@ js_dtobasestr(DtoaState *state, int base, double dinput) dval(d) = dinput; buffer = (char*) js_malloc(DTOBASESTR_BUFFER_SIZE); if (!buffer) - return NULL; + return nullptr; p = buffer; if (dval(d) < 0.0 @@ -343,7 +343,7 @@ js_dtobasestr(DtoaState *state, int base, double dinput) nomem1: Bfree(PASS_STATE b); js_free(buffer); - return NULL; + return nullptr; } do { digit = divrem(b, base); @@ -367,7 +367,7 @@ js_dtobasestr(DtoaState *state, int base, double dinput) int32_t s2, done; Bigint *b, *s, *mlo, *mhi; - b = s = mlo = mhi = NULL; + b = s = mlo = mhi = nullptr; *p++ = '.'; b = d2b(PASS_STATE df, &e, &bbits); @@ -379,7 +379,7 @@ js_dtobasestr(DtoaState *state, int base, double dinput) Bfree(PASS_STATE mlo); Bfree(PASS_STATE mhi); js_free(buffer); - return NULL; + return nullptr; } JS_ASSERT(e < 0); /* At this point df = b * 2^e. e must be less than zero because 0 < df < 1. */ diff --git a/js/src/jsdtoa.h b/js/src/jsdtoa.h index 5e3b20399f5f..04411d23b97e 100644 --- a/js/src/jsdtoa.h +++ b/js/src/jsdtoa.h @@ -27,8 +27,8 @@ js_DestroyDtoaState(DtoaState *state); * value represented by the character string pointed to by s00. The string is * scanned up to the first unrecognized character. * - * If se is not NULL, *se receives a pointer to the character terminating the - * scan. If no number can be formed, *se receives a pointer to the first + * If se is not nullptr, *se receives a pointer to the character terminating + * the scan. If no number can be formed, *se receives a pointer to the first * unparseable character in s00, and zero is returned. * * On overflow, this function returns infinity and does not indicate an error. @@ -82,7 +82,7 @@ typedef enum JSDToStrMode { * beginning. The size of buffer is given in bufferSize, and must be at least * as large as given by the above macros. * - * Return NULL if out of memory. + * Return nullptr if out of memory. */ char * js_dtostr(DtoaState *state, char *buffer, size_t bufferSize, JSDToStrMode mode, int precision, @@ -103,7 +103,7 @@ js_dtostr(DtoaState *state, char *buffer, size_t bufferSize, JSDToStrMode mode, * would equal d (except for -0.0, which converts to "0", and NaN, which is * not equal to itself). * - * Return NULL if out of memory. If the result is not NULL, it must be + * Return nullptr if out of memory. If the result is not nullptr, it must be * released via js_free(). */ char * diff --git a/js/src/jsexn.cpp b/js/src/jsexn.cpp index a0b9e4ec7cd4..7f2514e26b8c 100644 --- a/js/src/jsexn.cpp +++ b/js/src/jsexn.cpp @@ -66,10 +66,10 @@ const Class ErrorObject::class_ = { (JSResolveOp)exn_resolve, JS_ConvertStub, exn_finalize, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ exn_trace }; @@ -156,7 +156,7 @@ CopyErrorReport(JSContext *cx, JSErrorReport *report) ucmessageSize + uclinebufSize + linebufSize + filenameSize; cursor = cx->pod_malloc(mallocSize); if (!cursor) - return NULL; + return nullptr; copy = (JSErrorReport *)cursor; memset(cursor, 0, sizeof(JSErrorReport)); @@ -171,7 +171,7 @@ CopyErrorReport(JSContext *cx, JSErrorReport *report) js_memcpy(cursor, report->messageArgs[i], argSize); cursor += argSize; } - copy->messageArgs[i] = NULL; + copy->messageArgs[i] = nullptr; JS_ASSERT(cursor == (uint8_t *)copy->messageArgs[0] + argsCopySize); } @@ -231,7 +231,7 @@ struct SuppressErrorsGuard SuppressErrorsGuard(JSContext *cx) : cx(cx), - prevReporter(JS_SetErrorReporter(cx, NULL)), + prevReporter(JS_SetErrorReporter(cx, nullptr)), prevState(JS_SaveExceptionState(cx)) {} @@ -274,11 +274,11 @@ InitExnPrivate(JSContext *cx, HandleObject exnObject, HandleString message, JSStackTraceStackElem &frame = frames.back(); if (i.isNonEvalFunctionFrame()) { JSAtom *atom = i.callee()->displayAtom(); - if (atom == NULL) + if (atom == nullptr) atom = cx->runtime()->emptyString; frame.funName = atom; } else { - frame.funName = NULL; + frame.funName = nullptr; } RootedScript script(cx, i.script()); const char *cfilename = script->filename(); @@ -315,7 +315,7 @@ InitExnPrivate(JSContext *cx, HandleObject exnObject, HandleString message, return false; } } else { - priv->errorReport = NULL; + priv->errorReport = nullptr; } priv->message.init(message); @@ -390,7 +390,7 @@ exn_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, jsval v; unsigned attrs; - objp.set(NULL); + objp.set(nullptr); priv = obj->as().getExnPrivate(); if (priv && JSID_IS_ATOM(id)) { RootedString str(cx, JSID_TO_STRING(id)); @@ -451,7 +451,7 @@ exn_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, return true; define: - if (!JS_DefineProperty(cx, obj, prop, v, NULL, NULL, attrs)) + if (!JS_DefineProperty(cx, obj, prop, v, nullptr, nullptr, attrs)) return false; objp.set(obj); return true; @@ -461,7 +461,7 @@ JSErrorReport * js_ErrorFromException(jsval exn) { if (JSVAL_IS_PRIMITIVE(exn)) - return NULL; + return nullptr; // It's ok to UncheckedUnwrap here, since all we do is get the // JSErrorReport, and consumers are careful with the information they get @@ -471,11 +471,11 @@ js_ErrorFromException(jsval exn) // will fail if they can't unwrap it. JSObject *obj = UncheckedUnwrap(JSVAL_TO_OBJECT(exn)); if (!obj->is()) - return NULL; + return nullptr; JSExnPrivate *priv = obj->as().getExnPrivate(); if (!priv) - return NULL; + return nullptr; return priv->errorReport; } @@ -497,18 +497,18 @@ StackTraceToString(JSContext *cx, JSExnPrivate *priv) if (element->funName) { if (!sb.append(element->funName)) - return NULL; + return nullptr; } if (!sb.append('@')) - return NULL; + return nullptr; if (element->filename) { if (!sb.appendInflated(element->filename, strlen(element->filename))) - return NULL; + return nullptr; } if (!sb.append(':') || !NumberValueToStringBuffer(cx, NumberValue(element->ulineno), sb) || !sb.append('\n')) { - return NULL; + return nullptr; } } @@ -541,12 +541,12 @@ Exception(JSContext *cx, unsigned argc, Value *vp) return false; if (!protov.isObject()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PROTOTYPE, "Error"); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PROTOTYPE, "Error"); return false; } RootedObject obj(cx, NewObjectWithGivenProto(cx, &ErrorObject::class_, &protov.toObject(), - NULL)); + nullptr)); if (!obj) return false; @@ -558,14 +558,14 @@ Exception(JSContext *cx, unsigned argc, Value *vp) return false; args[0].setString(message); } else { - message = NULL; + message = nullptr; } /* Find the scripted caller. */ NonBuiltinScriptFrameIter iter(cx); /* Set the 'fileName' property. */ - RootedScript script(cx, iter.done() ? NULL : iter.script()); + RootedScript script(cx, iter.done() ? nullptr : iter.script()); RootedString filename(cx); if (args.length() > 1) { filename = ToString(cx, args[1]); @@ -593,7 +593,7 @@ Exception(JSContext *cx, unsigned argc, Value *vp) } int exnType = args.callee().as().getExtendedSlot(0).toInt32(); - if (!InitExnPrivate(cx, obj, message, filename, lineno, column, NULL, exnType)) + if (!InitExnPrivate(cx, obj, message, filename, lineno, column, nullptr, exnType)) return false; args.rval().setObject(*obj); @@ -609,7 +609,7 @@ exn_toString(JSContext *cx, unsigned argc, Value *vp) /* Step 2. */ if (!args.thisv().isObject()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PROTOTYPE, "Error"); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PROTOTYPE, "Error"); return false; } @@ -782,7 +782,7 @@ InitErrorClass(JSContext *cx, Handle global, int type, HandleObje RootedObject errorProto(cx, global->createBlankPrototypeInheriting(cx, &ErrorObject::class_, *proto)); if (!errorProto) - return NULL; + return nullptr; RootedValue nameValue(cx, StringValue(name)); RootedValue zeroValue(cx, Int32Value(0)); @@ -803,21 +803,21 @@ InitErrorClass(JSContext *cx, Handle global, int type, HandleObje !DefineNativeProperty(cx, errorProto, columnNumberId, zeroValue, JS_PropertyStub, JS_StrictPropertyStub, JSPROP_ENUMERATE, 0, 0)) { - return NULL; + return nullptr; } /* Create the corresponding constructor. */ RootedFunction ctor(cx, global->createConstructor(cx, Exception, name, 1, JSFunction::ExtendedFinalizeKind)); if (!ctor) - return NULL; + return nullptr; ctor->setExtendedSlot(0, Int32Value(int32_t(type))); if (!LinkConstructorAndPrototype(cx, ctor, errorProto)) - return NULL; + return nullptr; if (!DefineConstructorAndPrototype(cx, global, key, ctor, errorProto)) - return NULL; + return nullptr; JS_ASSERT(!errorProto->getPrivate()); @@ -834,21 +834,21 @@ js_InitExceptionClasses(JSContext *cx, HandleObject obj) RootedObject objectProto(cx, global->getOrCreateObjectPrototype(cx)); if (!objectProto) - return NULL; + return nullptr; /* Initialize the base Error class first. */ RootedObject errorProto(cx, InitErrorClass(cx, global, JSEXN_ERR, objectProto)); if (!errorProto) - return NULL; + return nullptr; /* |Error.prototype| alone has method properties. */ - if (!DefinePropertiesAndBrand(cx, errorProto, NULL, exception_methods)) - return NULL; + if (!DefinePropertiesAndBrand(cx, errorProto, nullptr, exception_methods)) + return nullptr; /* Define all remaining *Error constructors. */ for (int i = JSEXN_ERR + 1; i < JSEXN_LIMIT; i++) { if (!InitErrorClass(cx, global, i, errorProto)) - return NULL; + return nullptr; } return errorProto; @@ -858,11 +858,11 @@ const JSErrorFormatString* js_GetLocalizedErrorMessage(ExclusiveContext *cx, void *userRef, const char *locale, const unsigned errorNumber) { - const JSErrorFormatString *errorString = NULL; + const JSErrorFormatString *errorString = nullptr; // The locale callbacks might not be thread safe, so don't call them if // we're not on the main thread. When used with XPConnect, - // |localeGetErrorMessage| will be NULL anyways. + // |localeGetErrorMessage| will be nullptr anyways. if (cx->isJSContext() && cx->asJSContext()->runtime()->localeCallbacks && cx->asJSContext()->runtime()->localeCallbacks->localeGetErrorMessage) @@ -886,7 +886,7 @@ js::GetErrorTypeName(JSRuntime* rt, int16_t exnType) if (exnType <= JSEXN_NONE || exnType >= JSEXN_LIMIT || exnType == JSEXN_INTERNALERR) { - return NULL; + return nullptr; } JSProtoKey key = GetExceptionProtoKey(exnType); return ClassName(key, rt)->chars(); @@ -921,9 +921,9 @@ js_ErrorToException(JSContext *cx, const char *message, JSErrorReport *reportp, /* Find the exception index associated with this error. */ errorNumber = (JSErrNum) reportp->errorNumber; if (!callback || callback == js_GetErrorMessage) - errorString = js_GetLocalizedErrorMessage(cx, NULL, NULL, errorNumber); + errorString = js_GetLocalizedErrorMessage(cx, nullptr, nullptr, errorNumber); else - errorString = callback(userRef, NULL, errorNumber); + errorString = callback(userRef, nullptr, errorNumber); exn = errorString ? (JSExnType) errorString->exnType : JSEXN_NONE; JS_ASSERT(exn < JSEXN_LIMIT); @@ -960,7 +960,8 @@ js_ErrorToException(JSContext *cx, const char *message, JSErrorReport *reportp, return false; tv[0] = OBJECT_TO_JSVAL(errProto); - RootedObject errObject(cx, NewObjectWithGivenProto(cx, &ErrorObject::class_, errProto, NULL)); + RootedObject errObject(cx, NewObjectWithGivenProto(cx, &ErrorObject::class_, + errProto, nullptr)); if (!errObject) return false; tv[1] = OBJECT_TO_JSVAL(errObject); @@ -1031,7 +1032,7 @@ js_ReportUncaughtException(JSContext *cx) */ RootedObject exnObject(cx); if (JSVAL_IS_PRIMITIVE(exn)) { - exnObject = NULL; + exnObject = nullptr; } else { exnObject = JSVAL_TO_OBJECT(exn); roots[0] = exn; @@ -1107,14 +1108,14 @@ js_ReportUncaughtException(JSContext *cx) } JSAutoByteString bytesStorage; - const char *bytes = NULL; + const char *bytes = nullptr; if (str) bytes = bytesStorage.encodeLatin1(cx, str); if (!bytes) bytes = "unknown (can't convert to string)"; if (!reportp) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNCAUGHT_EXCEPTION, bytes); } else { /* Flag the error as an exception. */ @@ -1140,24 +1141,24 @@ js_CopyErrorObject(JSContext *cx, HandleObject errobj, HandleObject scope) ScopedJSFreePtr copy(static_cast(cx->malloc_(size))); if (!copy) - return NULL; + return nullptr; if (priv->errorReport) { copy->errorReport = CopyErrorReport(cx, priv->errorReport); if (!copy->errorReport) - return NULL; + return nullptr; } else { - copy->errorReport = NULL; + copy->errorReport = nullptr; } ScopedJSFreePtr autoFreeErrorReport(copy->errorReport); copy->message.init(priv->message); if (!cx->compartment()->wrap(cx, ©->message)) - return NULL; + return nullptr; JS::Anchor messageAnchor(copy->message); copy->filename.init(priv->filename); if (!cx->compartment()->wrap(cx, ©->filename)) - return NULL; + return nullptr; JS::Anchor filenameAnchor(copy->filename); copy->lineno = priv->lineno; copy->column = priv->column; @@ -1167,10 +1168,10 @@ js_CopyErrorObject(JSContext *cx, HandleObject errobj, HandleObject scope) // Create the Error object. RootedObject proto(cx, scope->global().getOrCreateCustomErrorPrototype(cx, copy->exnType)); if (!proto) - return NULL; - RootedObject copyobj(cx, NewObjectWithGivenProto(cx, &ErrorObject::class_, proto, NULL)); + return nullptr; + RootedObject copyobj(cx, NewObjectWithGivenProto(cx, &ErrorObject::class_, proto, nullptr)); if (!copyobj) - return NULL; + return nullptr; SetExnPrivate(copyobj->as(), copy); copy.forget(); autoFreeErrorReport.forget(); diff --git a/js/src/jsexn.h b/js/src/jsexn.h index e32fef0e1be0..afe5eaa7af09 100644 --- a/js/src/jsexn.h +++ b/js/src/jsexn.h @@ -64,7 +64,7 @@ js_GetLocalizedErrorMessage(js::ExclusiveContext *cx, void *userRef, const char * cx must be in the same compartment as scope. errobj may be in a different * compartment, but it must be an Error object (not a wrapper of one) and it * must not be one of the prototype objects created by js_InitExceptionClasses - * (errobj->getPrivate() must not be NULL). + * (errobj->getPrivate() must not be nullptr). */ extern JSObject * js_CopyErrorObject(JSContext *cx, js::HandleObject errobj, js::HandleObject scope); diff --git a/js/src/jsfriendapi.cpp b/js/src/jsfriendapi.cpp index d89696b0dbae..58eb6427c5ee 100644 --- a/js/src/jsfriendapi.cpp +++ b/js/src/jsfriendapi.cpp @@ -41,7 +41,7 @@ PerThreadDataFriendFields::PerThreadDataFriendFields() PodArrayZero(thingGCRooters); #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) - skipGCRooters = NULL; + skipGCRooters = nullptr; #endif } @@ -97,7 +97,7 @@ JS_GetObjectFunction(JSObject *obj) { if (obj->is()) return &obj->as(); - return NULL; + return nullptr; } JS_FRIEND_API(bool) @@ -135,11 +135,12 @@ JS_NewObjectWithUniqueType(JSContext *cx, const JSClass *clasp, JSObject *protoA * TypeObject attached to our proto with information about our object, since * we're not going to be using that TypeObject anyway. */ - RootedObject obj(cx, NewObjectWithGivenProto(cx, (const js::Class *)clasp, NULL, parent, SingletonObject)); + RootedObject obj(cx, NewObjectWithGivenProto(cx, (const js::Class *)clasp, nullptr, + parent, SingletonObject)); if (!obj) - return NULL; + return nullptr; if (!JS_SplicePrototype(cx, obj, proto)) - return NULL; + return nullptr; return obj; } @@ -230,7 +231,7 @@ JS_SetCompartmentPrincipals(JSCompartment *compartment, JSPrincipals *principals // Clear out the old principals, if any. if (compartment->principals) { JS_DropPrincipals(compartment->runtimeFromMainThread(), compartment->principals); - compartment->principals = NULL; + compartment->principals = nullptr; // We'd like to assert that our new principals is always same-origin // with the old one, but JSPrincipals doesn't give us a way to do that. // But we can at least assert that we're not switching between system @@ -431,10 +432,10 @@ js::GetOutermostEnclosingFunctionOfScriptedCaller(JSContext *cx) { ScriptFrameIter iter(cx); if (iter.done()) - return NULL; + return nullptr; if (!iter.isFunctionFrame()) - return NULL; + return nullptr; RootedFunction scriptedCaller(cx, iter.callee()); RootedScript outermost(cx, scriptedCaller->nonLazyScript()); @@ -455,7 +456,7 @@ js::DefineFunctionWithReserved(JSContext *cx, JSObject *objArg, const char *name assertSameCompartment(cx, obj); JSAtom *atom = Atomize(cx, name, strlen(name)); if (!atom) - return NULL; + return nullptr; Rooted id(cx, AtomToId(atom)); return DefineFunction(cx, obj, id, call, nargs, attrs, JSFunction::ExtendedFinalizeKind); } @@ -474,7 +475,7 @@ js::NewFunctionWithReserved(JSContext *cx, JSNative native, unsigned nargs, unsi if (name) { atom = Atomize(cx, name, strlen(name)); if (!atom) - return NULL; + return nullptr; } JSFunction::Flags funFlags = JSAPIToJSFunctionFlags(flags); @@ -509,7 +510,7 @@ js::InitClassWithReserved(JSContext *cx, JSObject *objArg, JSObject *parent_prot CHECK_REQUEST(cx); assertSameCompartment(cx, obj, parent_proto); return js_InitClass(cx, obj, parent_proto, Valueify(clasp), constructor, - nargs, ps, fs, static_ps, static_fs, NULL, + nargs, ps, fs, static_ps, static_fs, nullptr, JSFunction::ExtendedFinalizeKind); } @@ -641,7 +642,7 @@ js::GetWeakmapKeyDelegate(JSObject *key) { if (JSWeakmapKeyDelegateOp op = key->getClass()->ext.weakmapKeyDelegateOp) return op(key); - return NULL; + return nullptr; } JS_FRIEND_API(void) @@ -1013,12 +1014,12 @@ JS::ObjectPtr::trace(JSTracer *trc, const char *name) JS_FRIEND_API(JSObject *) js::GetTestingFunctions(JSContext *cx) { - RootedObject obj(cx, JS_NewObject(cx, NULL, NULL, NULL)); + RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr)); if (!obj) - return NULL; + return nullptr; if (!DefineTestingFunctions(cx, obj)) - return NULL; + return nullptr; return obj; } @@ -1043,7 +1044,7 @@ js::GetDOMCallbacks(JSRuntime *rt) return rt->DOMcallbacks; } -static const void *gDOMProxyHandlerFamily = NULL; +static const void *gDOMProxyHandlerFamily = nullptr; static uint32_t gDOMProxyExpandoSlot = 0; static DOMProxyShadowsCheck gDOMProxyShadowsCheck; @@ -1077,7 +1078,7 @@ js::GetDOMProxyShadowsCheck() bool js::detail::IdMatchesAtom(jsid id, JSAtom *atom) { - return id == INTERNED_STRING_TO_JSID(NULL, atom); + return id == INTERNED_STRING_TO_JSID(nullptr, atom); } JS_FRIEND_API(JSContext *) diff --git a/js/src/jsfriendapi.h b/js/src/jsfriendapi.h index 4ef84b1acbcf..e61ca484103e 100644 --- a/js/src/jsfriendapi.h +++ b/js/src/jsfriendapi.h @@ -119,11 +119,11 @@ JS_GetCompartmentPrincipals(JSCompartment *compartment); extern JS_FRIEND_API(void) JS_SetCompartmentPrincipals(JSCompartment *compartment, JSPrincipals *principals); -/* Safe to call with input obj == NULL. Returns non-NULL iff obj != NULL. */ +/* Safe to call with input obj == nullptr. Returns non-nullptr iff obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToInnerObject(JSContext *cx, JSObject *obj); -/* Requires obj != NULL. */ +/* Requires obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToOuterObject(JSContext *cx, JSObject *obj); @@ -198,7 +198,7 @@ struct JSFunctionSpecWithHelp { #define JS_FN_HELP(name,call,nargs,flags,usage,help) \ {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, usage, help} #define JS_FS_HELP_END \ - {NULL, NULL, 0, 0, NULL, NULL} + {nullptr, nullptr, 0, 0, nullptr, nullptr} extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); @@ -316,7 +316,7 @@ struct WeakMapTracer; * 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 NULL if the weak map is not contained in a JS Object. + * m will be nullptr if the weak map is not contained in a JS Object. */ typedef void (* WeakMapTraceCallback)(WeakMapTracer *trc, JSObject *m, @@ -498,7 +498,7 @@ IsOriginalScriptFunction(JSFunction *fun); /* * Return the outermost enclosing function (script) of the scripted caller. - * This function returns NULL in several cases: + * 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 @@ -768,7 +768,7 @@ CastToJSFreeOp(FreeOp *fop) /* * Get an error type name from a JSExnType constant. - * Returns NULL for invalid arguments and JSEXN_INTERNALERR + * Returns nullptr for invalid arguments and JSEXN_INTERNALERR */ extern JS_FRIEND_API(const jschar*) GetErrorTypeName(JSRuntime* rt, int16_t exnType); @@ -1084,9 +1084,9 @@ extern JS_FRIEND_API(bool) JS_IsFloat64Array(JSObject *obj); /* - * Unwrap Typed arrays all at once. Return NULL without throwing if the object - * cannot be viewed as the correct typed array, or the typed array object on - * success, filling both outparameters. + * 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, int8_t **data); @@ -1263,7 +1263,7 @@ JS_GetDataViewByteOffset(JSObject *obj); * * |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 NULL, then DEBUG builds may be + * 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) @@ -1274,7 +1274,7 @@ JS_GetDataViewByteLength(JSObject *obj); * * |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 NULL, then DEBUG builds may be + * 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 *) @@ -1405,7 +1405,7 @@ struct JSJitInfo { }; #define JS_JITINFO_NATIVE_PARALLEL(op) \ - {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + {{nullptr},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) @@ -1570,7 +1570,7 @@ class JS_FRIEND_API(AutoCTypesActivityCallback) { void DoEndCallback() { if (callback) { callback(cx, endType); - callback = NULL; + callback = nullptr; } } }; diff --git a/js/src/jsfun.cpp b/js/src/jsfun.cpp index a7bb6aff8845..93bde568c217 100644 --- a/js/src/jsfun.cpp +++ b/js/src/jsfun.cpp @@ -82,12 +82,13 @@ fun_getProperty(JSContext *cx, HandleObject obj_, HandleId id, MutableHandleValu if (JSID_IS_ATOM(id, cx->names().arguments)) { if (fun->hasRest()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_FUNCTION_ARGUMENTS_AND_REST); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, + JSMSG_FUNCTION_ARGUMENTS_AND_REST); return false; } /* Warn if strict about f.arguments or equivalent unqualified uses. */ if (!JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING | JSREPORT_STRICT, js_GetErrorMessage, - NULL, JSMSG_DEPRECATED_USAGE, js_arguments_str)) { + nullptr, JSMSG_DEPRECATED_USAGE, js_arguments_str)) { return false; } @@ -134,7 +135,7 @@ fun_getProperty(JSContext *cx, HandleObject obj_, HandleId id, MutableHandleValu } else if (caller->is()) { JSFunction *callerFun = &caller->as(); if (callerFun->isInterpreted() && callerFun->strict()) { - JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, NULL, + JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, nullptr, JSMSG_CALLER_IS_STRICT); return false; } @@ -213,12 +214,12 @@ ResolveInterpretedFunctionPrototype(JSContext *cx, HandleObject obj) else objProto = obj->global().getOrCreateObjectPrototype(cx); if (!objProto) - return NULL; + return nullptr; const Class *clasp = &JSObject::class_; - RootedObject proto(cx, NewObjectWithGivenProto(cx, clasp, objProto, NULL, SingletonObject)); + RootedObject proto(cx, NewObjectWithGivenProto(cx, clasp, objProto, nullptr, SingletonObject)); if (!proto) - return NULL; + return nullptr; // Per ES5 15.3.5.2 a user-defined function's .prototype property is // initially non-configurable, non-enumerable, and writable. @@ -227,7 +228,7 @@ ResolveInterpretedFunctionPrototype(JSContext *cx, HandleObject obj) protoVal, JS_PropertyStub, JS_StrictPropertyStub, JSPROP_PERMANENT)) { - return NULL; + return nullptr; } // Per ES5 13.2 the prototype's .constructor property is configurable, @@ -239,7 +240,7 @@ ResolveInterpretedFunctionPrototype(JSContext *cx, HandleObject obj) if (!JSObject::defineProperty(cx, proto, cx->names().constructor, objVal, JS_PropertyStub, JS_StrictPropertyStub, 0)) { - return NULL; + return nullptr; } } @@ -288,7 +289,7 @@ js::fun_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, fun->nargs - fun->hasRest(); v.setInt32(length); } else { - v.setString(fun->atom() == NULL ? cx->runtime()->emptyString : fun->atom()); + v.setString(fun->atom() == nullptr ? cx->runtime()->emptyString : fun->atom()); } if (!DefineNativeProperty(cx, fun, id, v, JS_PropertyStub, JS_StrictPropertyStub, @@ -357,8 +358,8 @@ js::XDRInterpretedFunction(XDRState *xdr, HandleObject enclosingScope, Han if (!fun->isInterpreted()) { JSAutoByteString funNameBytes; if (const char *name = GetFunctionNameBytes(cx, fun, &funNameBytes)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_SCRIPTED_FUNCTION, - name); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, + JSMSG_NOT_SCRIPTED_FUNCTION, name); } return false; } @@ -378,19 +379,19 @@ js::XDRInterpretedFunction(XDRState *xdr, HandleObject enclosingScope, Han if (!xdr->codeUint32(&firstword)) return false; - JSObject *proto = NULL; + JSObject *proto = nullptr; if (firstword & IsStarGenerator) { proto = cx->global()->getOrCreateStarGeneratorFunctionPrototype(cx); if (!proto) return false; } - fun = NewFunctionWithProto(cx, NullPtr(), NULL, 0, JSFunction::INTERPRETED, + fun = NewFunctionWithProto(cx, NullPtr(), nullptr, 0, JSFunction::INTERPRETED, NullPtr(), NullPtr(), proto, JSFunction::FinalizeKind, TenuredObject); if (!fun) return false; - atom = NULL; - script = NULL; + atom = nullptr; + script = nullptr; } if ((firstword & HasAtom) && !XDRAtom(xdr, &atom)) @@ -428,22 +429,23 @@ JSObject * js::CloneFunctionAndScript(JSContext *cx, HandleObject enclosingScope, HandleFunction srcFun) { /* NB: Keep this in sync with XDRInterpretedFunction. */ - JSObject *cloneProto = NULL; + JSObject *cloneProto = nullptr; if (srcFun->isStarGenerator()) { cloneProto = cx->global()->getOrCreateStarGeneratorFunctionPrototype(cx); if (!cloneProto) - return NULL; + return nullptr; } - RootedFunction clone(cx, NewFunctionWithProto(cx, NullPtr(), NULL, 0, JSFunction::INTERPRETED, - NullPtr(), NullPtr(), cloneProto, - JSFunction::FinalizeKind, TenuredObject)); + RootedFunction clone(cx, NewFunctionWithProto(cx, NullPtr(), nullptr, 0, + JSFunction::INTERPRETED, NullPtr(), NullPtr(), + cloneProto, JSFunction::FinalizeKind, + TenuredObject)); if (!clone) - return NULL; + return nullptr; RootedScript srcScript(cx, srcFun->nonLazyScript()); RootedScript clonedScript(cx, CloneScript(cx, enclosingScope, clone, srcScript)); if (!clonedScript) - return NULL; + return nullptr; clone->nargs = srcFun->nargs; clone->flags = srcFun->flags; @@ -451,7 +453,7 @@ js::CloneFunctionAndScript(JSContext *cx, HandleObject enclosingScope, HandleFun clone->initScript(clonedScript); clonedScript->setFunction(clone); if (!JSFunction::setTypeForScriptedFunction(cx, clone)) - return NULL; + return nullptr; RootedScript cloneScript(cx, clone->nonLazyScript()); CallNewScriptHook(cx, cloneScript, clone); @@ -534,11 +536,11 @@ const Class JSFunction::class_ = { fun_enumerate, (JSResolveOp)js::fun_resolve, JS_ConvertStub, - NULL, /* finalize */ - NULL, /* checkAccess */ - NULL, /* call */ + nullptr, /* finalize */ + nullptr, /* checkAccess */ + nullptr, /* call */ fun_hasInstance, - NULL, /* construct */ + nullptr, /* construct */ fun_trace }; @@ -554,7 +556,7 @@ FindBody(JSContext *cx, HandleFunction fun, StableCharPtr chars, size_t length, options.setFileAndLine("internal-findBody", 0) .setVersion(fun->nonLazyScript()->getVersion()); AutoKeepAtoms keepAtoms(cx->perThreadData); - TokenStream ts(cx, options, chars.get(), length, NULL); + TokenStream ts(cx, options, chars.get(), length, nullptr); int nest = 0; bool onward = true; // Skip arguments list. @@ -606,7 +608,7 @@ JSString * js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lambdaParen) { if (fun->isInterpretedLazy() && !fun->getOrCreateScript(cx)) - return NULL; + return nullptr; // If the object is an automatically-bound arrow function, get the source // of the pre-binding target. @@ -627,7 +629,7 @@ js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lamb !out.append("\n [generator expression]\n") || (!bodyOnly && !out.append("}"))) { - return NULL; + return nullptr; } return out.finishString(); } @@ -636,30 +638,30 @@ js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lamb // If we're not in pretty mode, put parentheses around lambda functions. if (fun->isInterpreted() && !lambdaParen && fun->isLambda() && !fun->isArrow()) { if (!out.append("(")) - return NULL; + return nullptr; } if (!fun->isArrow()) { if (!(fun->isStarGenerator() ? out.append("function* ") : out.append("function "))) - return NULL; + return nullptr; } if (fun->atom()) { if (!out.append(fun->atom())) - return NULL; + return nullptr; } } bool haveSource = fun->isInterpreted() && !fun->isSelfHostedBuiltin(); if (haveSource && !script->scriptSource()->hasSourceData() && !JSScript::loadSource(cx, script->scriptSource(), &haveSource)) { - return NULL; + return nullptr; } if (haveSource) { RootedString srcStr(cx, script->sourceData(cx)); if (!srcStr) - return NULL; + return nullptr; Rooted src(cx, srcStr->ensureStable(cx)); if (!src) - return NULL; + return nullptr; StableCharPtr chars = src->chars(); bool exprBody = fun->isExprClosure(); @@ -692,22 +694,22 @@ js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lamb // of bug 755821 should be cobbling the arguments passed into the // Function constructor into the source string. if (!out.append("(")) - return NULL; + return nullptr; // Fish out the argument names. BindingVector *localNames = cx->new_(cx); ScopedJSDeletePtr freeNames(localNames); if (!FillBindingVector(script, localNames)) - return NULL; + return nullptr; for (unsigned i = 0; i < fun->nargs; i++) { if ((i && !out.append(", ")) || (i == unsigned(fun->nargs - 1) && fun->hasRest() && !out.append("...")) || !out.append((*localNames)[i].name())) { - return NULL; + return nullptr; } } if (!out.append(") {\n")) - return NULL; + return nullptr; } if ((bodyOnly && !funCon) || addUseStrict) { // We need to get at the body either because we're only supposed to @@ -719,7 +721,7 @@ js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lamb if (!funCon) { JS_ASSERT(!buildBody); if (!FindBody(cx, fun, chars, src->length(), &bodyStart, &bodyEnd)) - return NULL; + return nullptr; } else { bodyEnd = src->length(); } @@ -727,16 +729,16 @@ js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lamb if (addUseStrict) { // Output source up to beginning of body. if (!out.append(chars, bodyStart)) - return NULL; + return nullptr; if (exprBody) { // We can't insert a statement into a function with an // expression body. Do what the decompiler did, and insert a // comment. if (!out.append("/* use strict */ ")) - return NULL; + return nullptr; } else { if (!out.append("\n\"use strict\";\n")) - return NULL; + return nullptr; } } @@ -744,36 +746,36 @@ js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lamb // closing braces (for addUseStrict). size_t dependentEnd = bodyOnly ? bodyEnd : src->length(); if (!out.append(chars + bodyStart, dependentEnd - bodyStart)) - return NULL; + return nullptr; } else { if (!out.append(src)) - return NULL; + return nullptr; } if (buildBody) { if (!out.append("\n}")) - return NULL; + return nullptr; } if (bodyOnly) { // Slap a semicolon on the end of functions with an expression body. if (exprBody && !out.append(";")) - return NULL; + return nullptr; } else if (!lambdaParen && fun->isLambda() && !fun->isArrow()) { if (!out.append(")")) - return NULL; + return nullptr; } } else if (fun->isInterpreted() && !fun->isSelfHostedBuiltin()) { if ((!bodyOnly && !out.append("() {\n ")) || !out.append("[sourceless code]") || (!bodyOnly && !out.append("\n}"))) - return NULL; + return nullptr; if (!lambdaParen && fun->isLambda() && !fun->isArrow() && !out.append(")")) - return NULL; + return nullptr; } else { JS_ASSERT(!fun->isExprClosure()); if ((!bodyOnly && !out.append("() {\n ")) || !out.append("[native code]") || (!bodyOnly && !out.append("\n}"))) - return NULL; + return nullptr; } return out.finishString(); } @@ -784,11 +786,11 @@ fun_toStringHelper(JSContext *cx, HandleObject obj, unsigned indent) if (!obj->is()) { if (obj->is()) return Proxy::fun_toString(cx, obj, indent); - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO, js_Function_str, js_toString_str, "object"); - return NULL; + return nullptr; } RootedFunction fun(cx, &obj->as()); @@ -992,7 +994,8 @@ js_fun_apply(JSContext *cx, unsigned argc, Value *vp) } else { /* Step 3. */ if (!vp[3].isObject()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_APPLY_ARGS, js_apply_str); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, + JSMSG_BAD_APPLY_ARGS, js_apply_str); return false; } @@ -1007,7 +1010,7 @@ js_fun_apply(JSContext *cx, unsigned argc, Value *vp) /* Step 6. */ if (length > ARGS_LENGTH_MAX) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_TOO_MANY_FUN_APPLY_ARGS); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_TOO_MANY_FUN_APPLY_ARGS); return false; } @@ -1114,7 +1117,7 @@ JSFunction::createScriptForLazilyInterpretedFunction(JSContext *cx, HandleFuncti return true; } - fun->initScript(NULL); + fun->initScript(nullptr); if (fun != lazy->function()) { script = lazy->function()->getOrCreateScript(cx); @@ -1287,7 +1290,7 @@ fun_bind(JSContext *cx, unsigned argc, Value *vp) } /* Step 3. */ - Value *boundArgs = NULL; + Value *boundArgs = nullptr; unsigned argslen = 0; if (args.length() > 1) { boundArgs = args.array() + 1; @@ -1319,19 +1322,19 @@ js_fun_bind(JSContext *cx, HandleObject target, HandleValue thisArg, } /* Step 4-6, 10-11. */ - RootedAtom name(cx, target->is() ? target->as().atom() : NULL); + RootedAtom name(cx, target->is() ? target->as().atom() : nullptr); RootedObject funobj(cx, NewFunction(cx, NullPtr(), CallOrConstructBoundFunction, length, JSFunction::NATIVE_CTOR, target, name)); if (!funobj) - return NULL; + return nullptr; /* NB: Bound functions abuse |parent| to store their target. */ if (!JSObject::setParent(cx, funobj, target)) - return NULL; + return nullptr; if (!funobj->as().initBoundFunction(cx, thisArg, boundArgs, argslen)) - return NULL; + return nullptr; /* Steps 17, 19-21 are handled by fun_resolve. */ /* Step 18 is the default for new functions. */ @@ -1346,7 +1349,7 @@ static bool OnBadFormal(JSContext *cx, TokenKind tt) { if (tt != TOK_ERROR) - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_FORMAL); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_FORMAL); else JS_ASSERT(cx->isExceptionPending()); return false; @@ -1373,7 +1376,7 @@ FunctionConstructor(JSContext *cx, unsigned argc, Value *vp, GeneratorKind gener /* Block this call if security callbacks forbid it. */ Rooted global(cx, &args.callee().global()); if (!GlobalObject::isRuntimeCodeGenEnabled(cx, global)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CSP_BLOCKED_FUNCTION); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CSP_BLOCKED_FUNCTION); return false; } @@ -1476,7 +1479,7 @@ FunctionConstructor(JSContext *cx, unsigned argc, Value *vp, GeneratorKind gener * compile the function body. */ TokenStream ts(cx, options, collected_args.get(), args_length, - /* strictModeGetter = */ NULL); + /* strictModeGetter = */ nullptr); bool yieldIsValidName = ts.versionNumber() < JSVERSION_1_7 && !isStarGenerator; /* The argument string may be empty or contain no tokens. */ @@ -1560,13 +1563,13 @@ FunctionConstructor(JSContext *cx, unsigned argc, Value *vp, GeneratorKind gener * and so would a call to f from another top-level's script or function. */ RootedAtom anonymousAtom(cx, cx->names().anonymous); - JSObject *proto = NULL; + JSObject *proto = nullptr; if (isStarGenerator) { proto = global->getOrCreateStarGeneratorFunctionPrototype(cx); if (!proto) return false; } - RootedFunction fun(cx, NewFunctionWithProto(cx, NullPtr(), NULL, 0, + RootedFunction fun(cx, NewFunctionWithProto(cx, NullPtr(), nullptr, 0, JSFunction::INTERPRETED_LAMBDA, global, anonymousAtom, proto, JSFunction::FinalizeKind, TenuredObject)); @@ -1609,7 +1612,7 @@ js::NewFunction(ExclusiveContext *cx, HandleObject funobjArg, Native native, uns gc::AllocKind allocKind /* = JSFunction::FinalizeKind */, NewObjectKind newKind /* = GenericObject */) { - return NewFunctionWithProto(cx, funobjArg, native, nargs, flags, parent, atom, NULL, + return NewFunctionWithProto(cx, funobjArg, native, nargs, flags, parent, atom, nullptr, allocKind, newKind); } @@ -1638,7 +1641,7 @@ js::NewFunctionWithProto(ExclusiveContext *cx, HandleObject funobjArg, Native na funobj = NewObjectWithClassProto(cx, &JSFunction::class_, proto, SkipScopeParent(parent), allocKind, newKind); if (!funobj) - return NULL; + return nullptr; } RootedFunction fun(cx, &funobj->as()); @@ -1647,12 +1650,12 @@ js::NewFunctionWithProto(ExclusiveContext *cx, HandleObject funobjArg, Native na fun->flags = flags; if (fun->isInterpreted()) { JS_ASSERT(!native); - fun->mutableScript().init(NULL); + fun->mutableScript().init(nullptr); fun->initEnvironment(parent); } else { JS_ASSERT(fun->isNative()); JS_ASSERT(native); - fun->initNative(native, NULL); + fun->initNative(native, nullptr); } if (allocKind == JSFunction::ExtendedFinalizeKind) { fun->flags |= JSFunction::EXTENDED; @@ -1675,19 +1678,19 @@ js::CloneFunctionObject(JSContext *cx, HandleFunction fun, HandleObject parent, !types::UseNewTypeForClone(fun); if (!useSameScript && fun->isInterpretedLazy() && !fun->getOrCreateScript(cx)) - return NULL; + return nullptr; NewObjectKind newKind = useSameScript ? newKindArg : SingletonObject; - JSObject *cloneProto = NULL; + JSObject *cloneProto = nullptr; if (fun->isStarGenerator()) { cloneProto = cx->global()->getOrCreateStarGeneratorFunctionPrototype(cx); if (!cloneProto) - return NULL; + return nullptr; } JSObject *cloneobj = NewObjectWithClassProto(cx, &JSFunction::class_, cloneProto, SkipScopeParent(parent), allocKind, newKind); if (!cloneobj) - return NULL; + return nullptr; RootedFunction clone(cx, &cloneobj->as()); clone->nargs = fun->nargs; @@ -1733,7 +1736,7 @@ js::CloneFunctionObject(JSContext *cx, HandleFunction fun, HandleObject parent, * no enclosing lexical scope (only the global scope). */ if (cloneRoot->isInterpreted() && !CloneFunctionScript(cx, fun, cloneRoot, newKindArg)) - return NULL; + return nullptr; return cloneRoot; } @@ -1759,8 +1762,8 @@ js::DefineFunction(JSContext *cx, HandleObject obj, HandleId id, Native native, gop = JS_PropertyStub; sop = JS_StrictPropertyStub; } else { - gop = NULL; - sop = NULL; + gop = nullptr; + sop = nullptr; } JSFunction::Flags funFlags; @@ -1768,14 +1771,14 @@ js::DefineFunction(JSContext *cx, HandleObject obj, HandleId id, Native native, funFlags = JSFunction::INTERPRETED_LAZY; else funFlags = JSAPIToJSFunctionFlags(flags); - RootedAtom atom(cx, JSID_IS_ATOM(id) ? JSID_TO_ATOM(id) : NULL); + RootedAtom atom(cx, JSID_IS_ATOM(id) ? JSID_TO_ATOM(id) : nullptr); fun = NewFunction(cx, NullPtr(), native, nargs, funFlags, obj, atom, allocKind, newKind); if (!fun) - return NULL; + return nullptr; RootedValue funVal(cx, ObjectValue(*fun)); if (!JSObject::defineGeneric(cx, obj, id, funVal, gop, sop, flags & ~JSFUN_FLAGS_MASK)) - return NULL; + return nullptr; return fun; } @@ -1794,7 +1797,7 @@ js::IsConstructor(const Value &v) JSFunction &fun = obj.as(); return fun.isNativeConstructor() || fun.isInterpretedConstructor(); } - return obj.getClass()->construct != NULL; + return obj.getClass()->construct != nullptr; } void @@ -1822,7 +1825,7 @@ js::ReportIncompatibleMethod(JSContext *cx, CallReceiver call, const Class *clas if (JSFunction *fun = ReportIfNotFunction(cx, call.calleev())) { JSAutoByteString funNameBytes; if (const char *funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INCOMPATIBLE_PROTO, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO, clasp->name, funName, InformalValueTypeName(thisv)); } } @@ -1834,7 +1837,7 @@ js::ReportIncompatible(JSContext *cx, CallReceiver call) if (JSFunction *fun = ReportIfNotFunction(cx, call.calleev())) { JSAutoByteString funNameBytes; if (const char *funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INCOMPATIBLE_METHOD, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_METHOD, funName, "method", InformalValueTypeName(call.thisv())); } } @@ -1875,7 +1878,7 @@ CheckIsValidConstructible(Value calleev) if (callee->is()) JS_ASSERT(callee->as().isNativeConstructor()); else - JS_ASSERT(callee->getClass()->construct != NULL); + JS_ASSERT(callee->getClass()->construct != nullptr); } } // namespace detail diff --git a/js/src/jsfun.h b/js/src/jsfun.h index 40913d83845d..6438eae902df 100644 --- a/js/src/jsfun.h +++ b/js/src/jsfun.h @@ -75,7 +75,7 @@ class JSFunction : public JSObject union { JSScript *script_; /* interpreted bytecode descriptor or null; use the accessor! */ - js::LazyScript *lazy_; /* lazily compiled script, or NULL */ + js::LazyScript *lazy_; /* lazily compiled script, or nullptr */ } s; JSObject *env_; /* environment for new activations; use the accessor! */ @@ -202,14 +202,14 @@ class JSFunction : public JSObject flags |= EXPR_CLOSURE; } - JSAtom *atom() const { return hasGuessedAtom() ? NULL : atom_.get(); } - js::PropertyName *name() const { return hasGuessedAtom() || !atom_ ? NULL : atom_->asPropertyName(); } + JSAtom *atom() const { return hasGuessedAtom() ? nullptr : atom_.get(); } + js::PropertyName *name() const { return hasGuessedAtom() || !atom_ ? nullptr : atom_->asPropertyName(); } void initAtom(JSAtom *atom) { atom_.init(atom); } JSAtom *displayAtom() const { return atom_; } void setGuessedAtom(JSAtom *atom) { - JS_ASSERT(atom_ == NULL); - JS_ASSERT(atom != NULL); + JS_ASSERT(atom_ == nullptr); + JS_ASSERT(atom != nullptr); JS_ASSERT(!hasGuessedAtom()); atom_ = atom; flags |= HAS_GUESSED_ATOM; @@ -249,7 +249,7 @@ class JSFunction : public JSObject // necessary (isInterpretedLazy()). // // A lazy function will have a LazyScript if the function came from parsed - // source, or NULL if the function is a clone of a self hosted function. + // source, or nullptr if the function is a clone of a self hosted function. // // There are several methods to get the script of an interpreted function: // @@ -269,7 +269,7 @@ class JSFunction : public JSObject if (isInterpretedLazy()) { JS::RootedFunction self(cx, this); if (!createScriptForLazilyInterpretedFunction(cx, self)) - return NULL; + return nullptr; JS_ASSERT(self->hasScript()); return self->u.i.s.script_; } @@ -355,7 +355,7 @@ class JSFunction : public JSObject } JSNative maybeNative() const { - return isInterpreted() ? NULL : native(); + return isInterpreted() ? nullptr : native(); } JSParallelNative parallelNative() const { @@ -364,7 +364,7 @@ class JSFunction : public JSObject } JSParallelNative maybeParallelNative() const { - return hasParallelNative() ? parallelNative() : NULL; + return hasParallelNative() ? parallelNative() : nullptr; } void initNative(js::Native native, const JSJitInfo *jitinfo) { @@ -475,7 +475,7 @@ NewFunction(ExclusiveContext *cx, HandleObject funobj, JSNative native, unsigned gc::AllocKind allocKind = JSFunction::FinalizeKind, NewObjectKind newKind = GenericObject); -// If proto is NULL, Function.prototype is used instead. +// If proto is nullptr, Function.prototype is used instead. extern JSFunction * NewFunctionWithProto(ExclusiveContext *cx, HandleObject funobj, JSNative native, unsigned nargs, JSFunction::Flags flags, HandleObject parent, HandleAtom atom, diff --git a/js/src/jsfuninlines.h b/js/src/jsfuninlines.h index 9946e68fae9c..5be5245ffa10 100644 --- a/js/src/jsfuninlines.h +++ b/js/src/jsfuninlines.h @@ -26,7 +26,7 @@ static inline JSObject * SkipScopeParent(JSObject *parent) { if (!parent) - return NULL; + return nullptr; while (parent->is()) parent = &parent->as().enclosingScope(); return parent; @@ -70,7 +70,7 @@ CloneFunctionObjectIfNotSingleton(JSContext *cx, HandleFunction fun, HandleObjec if (CanReuseFunctionForClone(cx, fun)) { RootedObject obj(cx, SkipScopeParent(parent)); if (!JSObject::setParent(cx, fun, obj)) - return NULL; + return nullptr; fun->setEnvironment(parent); return fun; } diff --git a/js/src/jsgc.cpp b/js/src/jsgc.cpp index 8801b0be2faf..9f2717f6d523 100644 --- a/js/src/jsgc.cpp +++ b/js/src/jsgc.cpp @@ -506,7 +506,7 @@ ChunkPool::get(JSRuntime *rt) JS_ASSERT(!emptyCount); chunk = Chunk::allocate(rt); if (!chunk) - return NULL; + return nullptr; JS_ASSERT(chunk->info.numArenasFreeCommitted == ArenasPerChunk); rt->gcNumArenasFreeCommitted += ArenasPerChunk; } @@ -541,7 +541,7 @@ ChunkPool::expire(JSRuntime *rt, bool releaseAll) * without emptying the list, the older chunks will stay at the tail * and are more likely to reach the max age. */ - Chunk *freeList = NULL; + Chunk *freeList = nullptr; int freeChunkCount = 0; for (Chunk **chunkp = &emptyChunkListHead; *chunkp; ) { JS_ASSERT(emptyCount); @@ -603,7 +603,7 @@ Chunk::allocate(JSRuntime *rt) #endif if (!chunk) - return NULL; + return nullptr; chunk->init(rt); rt->gcStats.count(gcstats::STAT_NEW_CHUNK); return chunk; @@ -661,7 +661,7 @@ Chunk::init(JSRuntime *rt) arenas[i].aheader.setAsNotAllocated(); arenas[i].aheader.next = (i + 1 < ArenasPerChunk) ? &arenas[i + 1].aheader - : NULL; + : nullptr; } /* The rest of info fields are initialized in PickChunk. */ @@ -707,8 +707,8 @@ Chunk::removeFromAvailableList() JS_ASSERT(info.next->info.prevp == &info.next); info.next->info.prevp = info.prevp; } - info.prevp = NULL; - info.next = NULL; + info.prevp = nullptr; + info.next = nullptr; } /* @@ -771,7 +771,7 @@ Chunk::allocateArena(Zone *zone, AllocKind thingKind) JSRuntime *rt = zone->runtimeFromAnyThread(); if (!rt->isHeapMinorCollecting() && rt->gcBytes >= rt->gcMaxBytes) - return NULL; + return nullptr; ArenaHeader *aheader = JS_LIKELY(info.numArenasFreeCommitted > 0) ? fetchNextFreeArena(rt) @@ -845,7 +845,7 @@ PickChunk(Zone *zone) chunk = rt->gcChunkPool.get(rt); if (!chunk) - return NULL; + return nullptr; rt->gcChunkAllocationSinceLastGC = true; @@ -857,11 +857,11 @@ PickChunk(Zone *zone) JS_ASSERT(!p); if (!rt->gcChunkSet.add(p, chunk)) { Chunk::release(rt, chunk); - return NULL; + return nullptr; } - chunk->info.prevp = NULL; - chunk->info.next = NULL; + chunk->info.prevp = nullptr; + chunk->info.next = nullptr; chunk->addToAvailableList(zone); return chunk; @@ -1018,8 +1018,8 @@ js_FinishGC(JSRuntime *rt) rt->zones.clear(); - rt->gcSystemAvailableChunkListHead = NULL; - rt->gcUserAvailableChunkListHead = NULL; + rt->gcSystemAvailableChunkListHead = nullptr; + rt->gcUserAvailableChunkListHead = nullptr; for (GCChunkSet::Range r(rt->gcChunkSet.all()); !r.empty(); r.popFront()) Chunk::release(rt, r.front()); rt->gcChunkSet.clear(); @@ -1098,7 +1098,7 @@ js::AddScriptRoot(JSContext *cx, JSScript **rp, const char *name) extern JS_FRIEND_API(bool) js_AddObjectRoot(JSRuntime *rt, JSObject **objp) { - return AddRoot(rt, objp, NULL, JS_GC_ROOT_OBJECT_PTR); + return AddRoot(rt, objp, nullptr, JS_GC_ROOT_OBJECT_PTR); } extern JS_FRIEND_API(void) @@ -1215,7 +1215,7 @@ ArenaLists::allocateFromArenaInline(Zone *zone, AllocKind thingKind) * a lock. */ - Chunk *chunk = NULL; + Chunk *chunk = nullptr; ArenaList *al = &arenaLists[thingKind]; AutoLockGC maybeLock; @@ -1237,7 +1237,7 @@ ArenaLists::allocateFromArenaInline(Zone *zone, AllocKind thingKind) * Let the caller to wait for the background allocation to * finish and restart the allocation attempt. */ - return NULL; + return nullptr; } } else if (*bfs == BFS_JUST_FINISHED) { /* See comments before BackgroundFinalizeState definition. */ @@ -1281,7 +1281,7 @@ ArenaLists::allocateFromArenaInline(Zone *zone, AllocKind thingKind) maybeLock.lock(zone->runtimeFromAnyThread()); chunk = PickChunk(zone); if (!chunk) - return NULL; + return nullptr; } /* @@ -1296,7 +1296,7 @@ ArenaLists::allocateFromArenaInline(Zone *zone, AllocKind thingKind) JS_ASSERT(!*al->cursor); ArenaHeader *aheader = chunk->allocateArena(zone, thingKind); if (!aheader) - return NULL; + return nullptr; if (JS_UNLIKELY(zone->wasGCStarted())) { if (zone->needsBarrier()) { @@ -1424,7 +1424,7 @@ ArenaLists::backgroundFinalize(FreeOp *fop, ArenaHeader *listHead, bool onBackgr else lists->backgroundFinalizeState[thingKind] = BFS_DONE; - lists->arenaListsToSweep[thingKind] = NULL; + lists->arenaListsToSweep[thingKind] = nullptr; } void @@ -1509,7 +1509,7 @@ RunLastDitchGC(JSContext *cx, JS::Zone *zone, AllocKind thingKind) if (void *thing = zone->allocator.arenas.allocateFromFreeList(thingKind, thingSize)) return thing; - return NULL; + return nullptr; } template @@ -1553,7 +1553,7 @@ ArenaLists::refillFreeList(ThreadSafeContext *cx, AllocKind thingKind) } if (!cx->allowGC() || !allowGC) - return NULL; + return nullptr; /* * We failed to allocate. Run the GC if we haven't done it already. @@ -1566,7 +1566,7 @@ ArenaLists::refillFreeList(ThreadSafeContext *cx, AllocKind thingKind) JS_ASSERT(allowGC); js_ReportOutOfMemory(cx); - return NULL; + return nullptr; } template void * @@ -1586,12 +1586,12 @@ js::InitTracer(JSTracer *trc, JSRuntime *rt, JSTraceCallback callback) { trc->runtime = rt; trc->callback = callback; - trc->debugPrinter = NULL; - trc->debugPrintArg = NULL; + trc->debugPrinter = nullptr; + trc->debugPrintArg = nullptr; trc->debugPrintIndex = size_t(-1); trc->eagerlyTraceWeakMaps = TraceWeakMapValues; #ifdef JS_GC_ZEAL - trc->realLocation = NULL; + trc->realLocation = nullptr; #endif } @@ -1641,11 +1641,11 @@ GCMarker::GCMarker(JSRuntime *rt) : stack(size_t(-1)), color(BLACK), started(false), - unmarkedArenaStackTop(NULL), + unmarkedArenaStackTop(nullptr), markLaterArenas(0), grayFailed(false) { - InitTracer(this, rt, NULL); + InitTracer(this, rt, nullptr); } bool @@ -1834,7 +1834,7 @@ void GCMarker::endBufferingGrayRoots() { JS_ASSERT(callback == GrayCallback); - callback = NULL; + callback = nullptr; JS_ASSERT(IS_GC_MARKING_TRACER(this)); } @@ -2189,7 +2189,7 @@ SweepBackgroundThings(JSRuntime* rt, bool onBackgroundThread) } } - rt->gcSweepingZones = NULL; + rt->gcSweepingZones = nullptr; } #ifdef JS_THREADSAFE @@ -2257,7 +2257,7 @@ GCHelperThread::finish() #ifdef JS_THREADSAFE - PRThread *join = NULL; + PRThread *join = nullptr; { AutoLockGC lock(rt); if (thread && state != SHUTDOWN) { @@ -2482,7 +2482,7 @@ GCHelperThread::replenishAndFreeLater(void *ptr) break; freeCursor = (void **) js_malloc(FREE_ARRAY_SIZE); if (!freeCursor) { - freeCursorEnd = NULL; + freeCursorEnd = nullptr; break; } freeCursorEnd = freeCursor + FREE_ARRAY_LENGTH; @@ -2506,7 +2506,7 @@ GCHelperThread::doSweep() if (freeCursor) { void **array = freeCursorEnd - FREE_ARRAY_LENGTH; freeElementsAndArray(array, freeCursor); - freeCursor = freeCursorEnd = NULL; + freeCursor = freeCursorEnd = nullptr; } else { JS_ASSERT(!freeCursorEnd); } @@ -2730,7 +2730,7 @@ CompartmentOfCell(Cell *thing, JSGCTraceKind kind) else if (kind == JSTRACE_SCRIPT) return static_cast(thing)->compartment(); else - return NULL; + return nullptr; } static void @@ -3267,7 +3267,7 @@ FinishMarkingValidation(JSRuntime *rt) { #ifdef DEBUG js_delete(rt->gcMarkingValidator); - rt->gcMarkingValidator = NULL; + rt->gcMarkingValidator = nullptr; #endif } @@ -3415,7 +3415,7 @@ GetNextZoneGroup(JSRuntime *rt) } rt->gcAbortSweepAfterCurrentGroup = false; - rt->gcCurrentZoneGroup = NULL; + rt->gcCurrentZoneGroup = nullptr; } } @@ -3559,7 +3559,7 @@ MarkIncomingCrossCompartmentPointers(JSRuntime *rt, const uint32_t color) } if (unlinkList) - c->gcIncomingGrayPointers = NULL; + c->gcIncomingGrayPointers = nullptr; } SliceBudget budget; @@ -3605,7 +3605,7 @@ ResetGrayList(JSCompartment *comp) JSObject *src = comp->gcIncomingGrayPointers; while (src) src = NextIncomingCrossCompartmentPointer(src, true); - comp->gcIncomingGrayPointers = NULL; + comp->gcIncomingGrayPointers = nullptr; } void @@ -4805,12 +4805,12 @@ js::NewCompartment(JSContext *cx, Zone *zone, JSPrincipals *principals, if (!zone) { zone = cx->new_(rt); if (!zone) - return NULL; + return nullptr; zoneHolder.reset(zone); if (!zone->init(cx)) - return NULL; + return nullptr; zone->setGCLastBytes(8192, GC_NORMAL); @@ -4820,7 +4820,7 @@ js::NewCompartment(JSContext *cx, Zone *zone, JSPrincipals *principals, ScopedJSDeletePtr compartment(cx->new_(zone, options)); if (!compartment || !compartment->init(cx)) - return NULL; + return nullptr; // Set up the principals. JS_SetCompartmentPrincipals(compartment, principals); @@ -4829,12 +4829,12 @@ js::NewCompartment(JSContext *cx, Zone *zone, JSPrincipals *principals, if (!zone->compartments.append(compartment.get())) { js_ReportOutOfMemory(cx); - return NULL; + return nullptr; } if (zoneHolder && !rt->zones.append(zone)) { js_ReportOutOfMemory(cx); - return NULL; + return nullptr; } zoneHolder.forget(); @@ -5049,7 +5049,7 @@ ReleaseScriptCounts(FreeOp *fop) vec[i].scriptCounts.destroy(fop); fop->delete_(rt->scriptAndCountsVector); - rt->scriptAndCountsVector = NULL; + rt->scriptAndCountsVector = nullptr; } JS_FRIEND_API(void) @@ -5158,10 +5158,10 @@ ArenaLists::adoptArenas(JSRuntime *rt, ArenaLists *fromArenaLists) ArenaList *fromList = &fromArenaLists->arenaLists[thingKind]; ArenaList *toList = &arenaLists[thingKind]; - while (fromList->head != NULL) { + while (fromList->head != nullptr) { ArenaHeader *fromHeader = fromList->head; fromList->head = fromHeader->next; - fromHeader->next = NULL; + fromHeader->next = nullptr; toList->insert(fromHeader); } @@ -5175,7 +5175,7 @@ ArenaLists::containsArena(JSRuntime *rt, ArenaHeader *needle) AutoLockGC lock(rt); size_t allocKind = needle->getAllocKind(); for (ArenaHeader *aheader = arenaLists[allocKind].head; - aheader != NULL; + aheader != nullptr; aheader = aheader->next) { if (aheader == needle) diff --git a/js/src/jsgc.h b/js/src/jsgc.h index 4827d20ea718..709317723985 100644 --- a/js/src/jsgc.h +++ b/js/src/jsgc.h @@ -70,7 +70,7 @@ class ChunkPool { public: ChunkPool() - : emptyChunkListHead(NULL), + : emptyChunkListHead(nullptr), emptyCount(0) { } size_t getEmptyCount() const { @@ -359,7 +359,7 @@ struct ArenaList { } void clear() { - head = NULL; + head = nullptr; cursor = &head; } @@ -419,8 +419,8 @@ class ArenaLists for (size_t i = 0; i != FINALIZE_LIMIT; ++i) backgroundFinalizeState[i] = BFS_DONE; for (size_t i = 0; i != FINALIZE_LIMIT; ++i) - arenaListsToSweep[i] = NULL; - gcShapeArenasToSweep = NULL; + arenaListsToSweep[i] = nullptr; + gcShapeArenasToSweep = nullptr; } ~ArenaLists() { @@ -817,14 +817,14 @@ class GCHelperThread { public: GCHelperThread(JSRuntime *rt) : rt(rt), - thread(NULL), - wakeup(NULL), - done(NULL), + thread(nullptr), + wakeup(nullptr), + done(nullptr), state(IDLE), sweepFlag(false), shrinkFlag(false), - freeCursor(NULL), - freeCursorEnd(NULL), + freeCursor(nullptr), + freeCursorEnd(nullptr), backgroundAllocation(true) { } @@ -915,11 +915,11 @@ struct MarkStack { size_t sizeLimit; MarkStack(size_t sizeLimit) - : stack(NULL), - tos(NULL), - limit(NULL), - ballast(NULL), - ballastLimit(NULL), + : stack(nullptr), + tos(nullptr), + limit(nullptr), + ballast(nullptr), + ballastLimit(nullptr), sizeLimit(sizeLimit) { } ~MarkStack() { @@ -1310,7 +1310,7 @@ js_FinalizeStringRT(JSRuntime *rt, JSString *str); * Macro to test if a traversal is the marking phase of the GC. */ #define IS_GC_MARKING_TRACER(trc) \ - ((trc)->callback == NULL || (trc)->callback == GCMarker::GrayCallback) + ((trc)->callback == nullptr || (trc)->callback == GCMarker::GrayCallback) namespace js { diff --git a/js/src/jsgcinlines.h b/js/src/jsgcinlines.h index d3c849a6074a..44e2c8ec28b4 100644 --- a/js/src/jsgcinlines.h +++ b/js/src/jsgcinlines.h @@ -118,13 +118,13 @@ class ArenaIter } void init() { - aheader = NULL; - remainingHeader = NULL; + aheader = nullptr; + remainingHeader = nullptr; } void init(ArenaHeader *aheaderArg) { aheader = aheaderArg; - remainingHeader = NULL; + remainingHeader = nullptr; } void init(JS::Zone *zone, AllocKind kind) { @@ -132,7 +132,7 @@ class ArenaIter remainingHeader = zone->allocator.arenas.getFirstArenaToSweep(kind); if (!aheader) { aheader = remainingHeader; - remainingHeader = NULL; + remainingHeader = nullptr; } } @@ -148,7 +148,7 @@ class ArenaIter aheader = aheader->next; if (!aheader) { aheader = remainingHeader; - remainingHeader = NULL; + remainingHeader = nullptr; } } }; @@ -214,7 +214,7 @@ class CellIterImpl break; } if (aiter.done()) { - cell = NULL; + cell = nullptr; return; } ArenaHeader *aheader = aiter.get(); @@ -266,7 +266,7 @@ class CellIter : public CellIterImpl gc::FinishBackgroundFinalize(zone->runtimeFromMainThread()); } if (lists->isSynchronizedFreeList(kind)) { - lists = NULL; + lists = nullptr; } else { JS_ASSERT(!zone->runtimeFromMainThread()->isHeapBusy()); lists->copyFreeListToArena(kind); @@ -351,7 +351,7 @@ typedef CompartmentsIterT GCCompartmentGroupIter; #ifdef JSGC_GENERATIONAL /* * Attempt to allocate a new GC thing out of the nursery. If there is not enough - * room in the nursery or there is an OOM, this method will return NULL. + * room in the nursery or there is an OOM, this method will return nullptr. */ template inline T * @@ -376,7 +376,7 @@ TryNewNurseryGCThing(ThreadSafeContext *cxArg, size_t thingSize) return t; } } - return NULL; + return nullptr; } #endif /* JSGC_GENERATIONAL */ diff --git a/js/src/jsinfer.cpp b/js/src/jsinfer.cpp index ec26527dd6af..f6a1b198291f 100644 --- a/js/src/jsinfer.cpp +++ b/js/src/jsinfer.cpp @@ -398,7 +398,7 @@ TypeSet::add(JSContext *cx, TypeConstraint *constraint, bool callExisting) InferSpewColor(constraint), constraint, InferSpewColorReset(), constraint->kind()); - JS_ASSERT(constraint->next == NULL); + JS_ASSERT(constraint->next == nullptr); constraint->next = constraintList; constraintList = constraint; @@ -463,14 +463,14 @@ TypeSet::clone(LifoAlloc *alloc) const if (capacity) { newSet = alloc->newArray(capacity); if (!newSet) - return NULL; + return nullptr; PodCopy(newSet, objectSet, capacity); } uint32_t newFlags = flags & ~(TYPE_FLAG_STACK_SET | TYPE_FLAG_HEAP_SET); TemporaryTypeSet *res = alloc->new_(newFlags, capacity ? newSet : objectSet); if (!res) - return NULL; + return nullptr; return res; } @@ -501,20 +501,20 @@ TemporaryTypeSet::addObject(TypeObjectKey *key, LifoAlloc *alloc) TypeSet::unionSets(TypeSet *a, TypeSet *b, LifoAlloc *alloc) { TemporaryTypeSet *res = alloc->new_(a->baseFlags() | b->baseFlags(), - static_cast(NULL)); + static_cast(nullptr)); if (!res) - return NULL; + return nullptr; if (!res->unknownObject()) { for (size_t i = 0; i < a->getObjectCount() && !res->unknownObject(); i++) { TypeObjectKey *key = a->getObject(i); if (key && !res->addObject(key, alloc)) - return NULL; + return nullptr; } for (size_t i = 0; i < b->getObjectCount() && !res->unknownObject(); i++) { TypeObjectKey *key = b->getObject(i); if (key && !res->addObject(key, alloc)) - return NULL; + return nullptr; } } @@ -674,7 +674,7 @@ TypeObjectKey::newScript() if (addendum && addendum->isNewScript()) return addendum->asNewScript(); } - return NULL; + return nullptr; } bool @@ -883,7 +883,7 @@ JSObject * TemporaryTypeSet::getSingleton() { if (baseFlags() != 0 || baseObjectCount() != 1) - return NULL; + return nullptr; return getSingleObject(0); } @@ -892,7 +892,7 @@ JSObject * HeapTypeSetKey::singleton(CompilerConstraintList *constraints) { if (actualTypes->baseFlags() != 0 || actualTypes->getObjectCount() != 1) - return NULL; + return nullptr; JSObject *obj = actualTypes->getSingleObject(0); @@ -1190,9 +1190,9 @@ const Class * TemporaryTypeSet::getKnownClass() { if (unknownObject()) - return NULL; + return nullptr; - const Class *clasp = NULL; + const Class *clasp = nullptr; unsigned count = getObjectCount(); for (unsigned i = 0; i < count; i++) { @@ -1201,7 +1201,7 @@ TemporaryTypeSet::getKnownClass() continue; if (clasp && clasp != nclasp) - return NULL; + return nullptr; clasp = nclasp; } @@ -1279,9 +1279,9 @@ JSObject * TemporaryTypeSet::getCommonPrototype() { if (unknownObject()) - return NULL; + return nullptr; - JSObject *proto = NULL; + JSObject *proto = nullptr; unsigned count = getObjectCount(); for (unsigned i = 0; i < count; i++) { @@ -1295,10 +1295,10 @@ TemporaryTypeSet::getCommonPrototype() if (proto) { if (nproto != proto) - return NULL; + return nullptr; } else { if (!nproto.isObject()) - return NULL; + return nullptr; proto = nproto.toObject(); } } @@ -1398,7 +1398,7 @@ TypeCompartment::newTypeObject(ExclusiveContext *cx, const Class *clasp, Handle< TypeObject *object = gc::NewGCThing(cx, gc::FINALIZE_TYPE_OBJECT, sizeof(TypeObject), gc::TenuredHeap); if (!object) - return NULL; + return nullptr; new(object) TypeObject(clasp, proto, unknown); if (!cx->typeInferenceEnabled()) @@ -1414,7 +1414,7 @@ PreviousOpcode(HandleScript script, jsbytecode *pc) JS_ASSERT(analysis->maybeCode(pc)); if (pc == script->code) - return NULL; + return nullptr; for (pc--;; pc--) { if (analysis->maybeCode(pc)) @@ -1426,16 +1426,16 @@ PreviousOpcode(HandleScript script, jsbytecode *pc) /* * If pc is an array initializer within an outer multidimensional array - * initializer, find the opcode of the previous newarray. NULL otherwise. + * initializer, find the opcode of the previous newarray. nullptr otherwise. */ static inline jsbytecode * FindPreviousInnerInitializer(HandleScript script, jsbytecode *initpc) { if (!script->hasAnalysis()) - return NULL; + return nullptr; if (!script->analysis()->maybeCode(initpc)) - return NULL; + return nullptr; /* * Pattern match the following bytecode, which will appear between @@ -1447,15 +1447,15 @@ FindPreviousInnerInitializer(HandleScript script, jsbytecode *initpc) */ if (*initpc != JSOP_NEWARRAY) - return NULL; + return nullptr; jsbytecode *last = PreviousOpcode(script, initpc); if (!last || *last != JSOP_INITELEM_ARRAY) - return NULL; + return nullptr; last = PreviousOpcode(script, last); if (!last || *last != JSOP_ENDINIT) - return NULL; + return nullptr; /* * Find the start of the previous initializer. Keep track of initializer @@ -1477,7 +1477,7 @@ FindPreviousInnerInitializer(HandleScript script, jsbytecode *initpc) } if (!previnit || *previnit != JSOP_NEWARRAY) - return NULL; + return nullptr; return previnit; } @@ -1491,14 +1491,14 @@ TypeCompartment::addAllocationSiteTypeObject(JSContext *cx, AllocationSiteKey ke allocationSiteTable = cx->new_(); if (!allocationSiteTable || !allocationSiteTable->init()) { cx->compartment()->types.setPendingNukeTypes(cx); - return NULL; + return nullptr; } } AllocationSiteTable::AddPtr p = allocationSiteTable->lookupForAdd(key); JS_ASSERT(!p); - TypeObject *res = NULL; + TypeObject *res = nullptr; /* * If this is an array initializer nested in another array initializer, @@ -1521,14 +1521,14 @@ TypeCompartment::addAllocationSiteTypeObject(JSContext *cx, AllocationSiteKey ke if (!res) { RootedObject proto(cx); - if (!js_GetClassPrototype(cx, key.kind, &proto, NULL)) - return NULL; + if (!js_GetClassPrototype(cx, key.kind, &proto, nullptr)) + return nullptr; Rooted tagged(cx, TaggedProto(proto)); res = newTypeObject(cx, GetClassForProtoKey(key.kind), tagged); if (!res) { cx->compartment()->types.setPendingNukeTypes(cx); - return NULL; + return nullptr; } key.script = keyScript; } @@ -1542,12 +1542,12 @@ TypeCompartment::addAllocationSiteTypeObject(JSContext *cx, AllocationSiteKey ke RootedObject baseobj(cx, key.script->getObject(GET_UINT32_INDEX(pc))); if (!res->addDefiniteProperties(cx, baseobj)) - return NULL; + return nullptr; } if (!allocationSiteTable->add(p, key, res)) { cx->compartment()->types.setPendingNukeTypes(cx); - return NULL; + return nullptr; } return res; @@ -1733,7 +1733,7 @@ TypeCompartment::processPendingRecompiles(FreeOp *fop) /* Steal the list of scripts to recompile, else we will try to recursively recompile them. */ Vector *pending = pendingRecompiles; - pendingRecompiles = NULL; + pendingRecompiles = nullptr; JS_ASSERT(!pending->empty()); @@ -1780,7 +1780,7 @@ TypeZone::nukeTypes(FreeOp *fop) for (CompartmentsInZoneIter comp(zone()); !comp.done(); comp.next()) { if (comp->types.pendingRecompiles) { fop->free_(comp->types.pendingRecompiles); - comp->types.pendingRecompiles = NULL; + comp->types.pendingRecompiles = nullptr; } } @@ -1911,7 +1911,7 @@ TypeCompartment::print(JSContext *cx, bool force) gc::AutoSuppressGC suppressGC(cx); JSCompartment *compartment = this->compartment(); - AutoEnterAnalysis enter(NULL, compartment); + AutoEnterAnalysis enter(nullptr, compartment); if (!force && !InferSpewActive(ISpewResult)) return; @@ -1973,7 +1973,7 @@ struct types::ArrayTableKey : public DefaultHasher JSObject *proto; ArrayTableKey() - : type(Type::UndefinedType()), proto(NULL) + : type(Type::UndefinedType()), proto(nullptr) {} static inline uint32_t hash(const ArrayTableKey &v) { @@ -1992,7 +1992,7 @@ TypeCompartment::setTypeToHomogenousArray(ExclusiveContext *cx, if (!arrayTypeTable) { arrayTypeTable = cx->new_(); if (!arrayTypeTable || !arrayTypeTable->init()) { - arrayTypeTable = NULL; + arrayTypeTable = nullptr; cx->compartment()->types.setPendingNukeTypes(cx); return; } @@ -2159,7 +2159,7 @@ TypeCompartment::fixObjectType(ExclusiveContext *cx, JSObject *obj) if (!objectTypeTable) { objectTypeTable = cx->new_(); if (!objectTypeTable || !objectTypeTable->init()) { - objectTypeTable = NULL; + objectTypeTable = nullptr; cx->compartment()->types.setPendingNukeTypes(cx); return; } @@ -2258,9 +2258,9 @@ TypeCompartment::newTypedObject(JSContext *cx, IdValuePair *properties, size_t n if (!objectTypeTable) { objectTypeTable = cx->new_(); if (!objectTypeTable || !objectTypeTable->init()) { - objectTypeTable = NULL; + objectTypeTable = nullptr; cx->compartment()->types.setPendingNukeTypes(cx); - return NULL; + return nullptr; } } @@ -2279,7 +2279,7 @@ TypeCompartment::newTypedObject(JSContext *cx, IdValuePair *properties, size_t n * ignores objects with dense indexes. */ if (!nproperties || nproperties >= PropertyTree::MAX_HEIGHT) - return NULL; + return nullptr; gc::AllocKind allocKind = gc::GetGCObjectKind(nproperties); size_t nfixed = gc::GetGCKindSlots(allocKind, &JSObject::class_); @@ -2288,19 +2288,19 @@ TypeCompartment::newTypedObject(JSContext *cx, IdValuePair *properties, size_t n ObjectTypeTable::AddPtr p = objectTypeTable->lookupForAdd(lookup); if (!p) - return NULL; + return nullptr; RootedObject obj(cx, NewBuiltinClassInstance(cx, &JSObject::class_, allocKind)); if (!obj) { cx->clearPendingException(); - return NULL; + return nullptr; } JS_ASSERT(obj->getProto() == p->value.object->proto); RootedShape shape(cx, p->value.shape); if (!JSObject::setLastProperty(cx, obj, shape)) { cx->clearPendingException(); - return NULL; + return nullptr; } UpdateObjectTableEntryTypes(cx, p->value, properties, nproperties); @@ -2622,9 +2622,9 @@ TypeObject::clearAddendum(ExclusiveContext *cx) break; } - /* We NULL out addendum *before* freeing it so the write barrier works. */ + /* We nullptr out addendum *before* freeing it so the write barrier works. */ TypeObjectAddendum *savedAddendum = addendum; - addendum = NULL; + addendum = nullptr; js_free(savedAddendum); markStateChange(cx); @@ -3230,7 +3230,7 @@ JSScript::makeAnalysis(JSContext *cx) self->types->analysis->analyzeBytecode(cx); if (self->types->analysis->OOM()) { - self->types->analysis = NULL; + self->types->analysis = nullptr; return false; } @@ -3276,7 +3276,7 @@ JSObject::shouldSplicePrototype(JSContext *cx) * If inference is disabled we cannot determine from the object whether it * has had its __proto__ set after creation. */ - if (getProto() != NULL) + if (getProto() != nullptr) return false; return !cx->typeInferenceEnabled() || hasSingletonType(); } @@ -3306,7 +3306,7 @@ JSObject::splicePrototype(JSContext *cx, const Class *clasp, Handle Rooted type(cx, self->getType(cx)); if (!type) return false; - Rooted protoType(cx, NULL); + Rooted protoType(cx, nullptr); if (proto.isObject()) { protoType = proto.toObject()->getType(cx); if (!protoType) @@ -3337,14 +3337,14 @@ JSObject::makeLazyType(JSContext *cx, HandleObject obj) if (obj->is() && obj->as().isInterpretedLazy()) { RootedFunction fun(cx, &obj->as()); if (!fun->getOrCreateScript(cx)) - return NULL; + return nullptr; } Rooted proto(cx, obj->getTaggedProto()); TypeObject *type = cx->compartment()->types.newTypeObject(cx, obj->getClass(), proto); if (!type) { if (cx->typeInferenceEnabled()) cx->compartment()->types.setPendingNukeTypes(cx); - return NULL; + return nullptr; } if (!cx->typeInferenceEnabled()) { @@ -3473,7 +3473,7 @@ ExclusiveContext::getNewType(const Class *clasp, TaggedProto proto_, JSFunction TypeObjectSet &newTypeObjects = compartment_->newTypeObjects; if (!newTypeObjects.initialized() && !newTypeObjects.init()) - return NULL; + return nullptr; TypeObjectSet::AddPtr p = newTypeObjects.lookupForAdd(TypeObjectSet::Lookup(clasp, proto_)); SkipRoot skipHash(this, &p); /* Prevent the hash from being poisoned. */ @@ -3504,7 +3504,7 @@ ExclusiveContext::getNewType(const Class *clasp, TaggedProto proto_, JSFunction RootedFunction fun(this, fun_); if (proto.isObject() && !proto.toObject()->setDelegate(this)) - return NULL; + return nullptr; bool markUnknown = proto.isObject() @@ -3513,7 +3513,7 @@ ExclusiveContext::getNewType(const Class *clasp, TaggedProto proto_, JSFunction RootedTypeObject type(this, compartment_->types.newTypeObject(this, clasp, proto, markUnknown)); if (!type) - return NULL; + return nullptr; /* * If a GC has occured, then the hash we calculated may be invalid, as it @@ -3524,7 +3524,7 @@ ExclusiveContext::getNewType(const Class *clasp, TaggedProto proto_, JSFunction gcHappened ? newTypeObjects.putNew(TypeObjectSet::Lookup(clasp, proto), type.get()) : newTypeObjects.relookupOrAdd(p, TypeObjectSet::Lookup(clasp, proto), type.get()); if (!added) - return NULL; + return nullptr; #ifdef JSGC_GENERATIONAL if (proto.isObject() && hasNursery() && nursery().isInside(proto.toObject())) { @@ -3586,7 +3586,7 @@ ExclusiveContext::getLazyType(const Class *clasp, TaggedProto proto) TypeObjectSet &table = compartment()->lazyTypeObjects; if (!table.initialized() && !table.init()) - return NULL; + return nullptr; TypeObjectSet::AddPtr p = table.lookupForAdd(TypeObjectSet::Lookup(clasp, proto)); if (p) { @@ -3599,10 +3599,10 @@ ExclusiveContext::getLazyType(const Class *clasp, TaggedProto proto) Rooted protoRoot(this, proto); TypeObject *type = compartment()->types.newTypeObject(this, clasp, protoRoot, false); if (!type) - return NULL; + return nullptr; if (!table.relookupOrAdd(p, TypeObjectSet::Lookup(clasp, protoRoot), type)) - return NULL; + return nullptr; type->singleton = (JSObject *) TypeObject::LAZY_SINGLETON; @@ -3645,20 +3645,20 @@ TypeSet::sweep(Zone *zone) } else if (objectCount == 1) { TypeObjectKey *object = (TypeObjectKey *) objectSet; if (IsAboutToBeFinalized(object)) { - objectSet = NULL; + objectSet = nullptr; setBaseObjectCount(0); } } /* All constraints are wiped out on each GC. */ - constraintList = NULL; + constraintList = nullptr; } inline void TypeObject::clearProperties() { setBasePropertyCount(0); - propertySet = NULL; + propertySet = nullptr; } /* @@ -3761,7 +3761,7 @@ TypeCompartment::sweep(FreeOp *fop) JS_ASSERT(key.type.isUnknown() || !key.type.isSingleObject()); bool remove = false; - TypeObject *typeObject = NULL; + TypeObject *typeObject = nullptr; if (!key.type.isUnknown() && key.type.isTypeObject()) { typeObject = key.type.typeObject(); if (IsTypeObjectAboutToBeFinalized(&typeObject)) @@ -3799,7 +3799,7 @@ TypeCompartment::sweep(FreeOp *fop) JS_ASSERT(AtomToId((JSAtom *)str) == key.properties[i]); } JS_ASSERT(!entry.types[i].isSingleObject()); - TypeObject *typeObject = NULL; + TypeObject *typeObject = nullptr; if (entry.types[i].isTypeObject()) { typeObject = entry.types[i].typeObject(); if (IsTypeObjectAboutToBeFinalized(&typeObject)) @@ -3836,7 +3836,7 @@ TypeCompartment::sweep(FreeOp *fop) if (pendingArray) fop->free_(pendingArray); - pendingArray = NULL; + pendingArray = nullptr; pendingCapacity = 0; } @@ -3866,13 +3866,13 @@ TypeCompartment::clearCompilerOutputs(FreeOp *fop) { if (constrainedOutputs) { fop->delete_(constrainedOutputs); - constrainedOutputs = NULL; + constrainedOutputs = nullptr; } if (pendingRecompiles) { JS_ASSERT(pendingRecompiles->length() == 0); fop->delete_(pendingRecompiles); - pendingRecompiles = NULL; + pendingRecompiles = nullptr; } } @@ -3979,7 +3979,10 @@ TypeCompartment::addSizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf, /* Pending arrays are cleared on GC along with the analysis pool. */ *pendingArrays += mallocSizeOf(pendingArray); - /* TypeCompartment::pendingRecompiles is non-NULL only while inference code is running. */ + /* + * TypeCompartment::pendingRecompiles is non-nullptr only while inference + * code is running. + */ JS_ASSERT(!pendingRecompiles); if (allocationSiteTable) @@ -4061,7 +4064,7 @@ TypeZone::sweep(FreeOp *fop, bool releaseTypes) if (releaseTypes) { script->types->destroy(); - script->types = NULL; + script->types = nullptr; } } } @@ -4104,7 +4107,7 @@ TypeScript::printTypes(JSContext *cx, HandleScript script) const if (!bytecodeMap) return; - AutoEnterAnalysis enter(NULL, script->compartment()); + AutoEnterAnalysis enter(nullptr, script->compartment()); if (script->function()) fprintf(stderr, "Function"); @@ -4116,7 +4119,7 @@ TypeScript::printTypes(JSContext *cx, HandleScript script) const if (script->function()) { if (js::PropertyName *name = script->function()->name()) { - const jschar *chars = name->getChars(NULL); + const jschar *chars = name->getChars(nullptr); JSString::dumpChars(chars, name->length()); } } diff --git a/js/src/jsinfer.h b/js/src/jsinfer.h index f59800cfc966..c99df7a1af95 100644 --- a/js/src/jsinfer.h +++ b/js/src/jsinfer.h @@ -28,7 +28,7 @@ class TypeRepresentation; class TaggedProto { public: - TaggedProto() : proto(NULL) {} + TaggedProto() : proto(nullptr) {} TaggedProto(JSObject *proto) : proto(proto) {} uintptr_t toWord() const { return uintptr_t(proto); } @@ -259,7 +259,7 @@ public: TypeConstraint *next; TypeConstraint() - : next(NULL) + : next(nullptr) {} /* Debugging name for this kind of constraint. */ @@ -451,7 +451,7 @@ class TypeSet TypeConstraint *constraintList; TypeSet() - : flags(0), objectSet(NULL), constraintList(NULL) + : flags(0), objectSet(nullptr), constraintList(nullptr) {} void print(); @@ -466,7 +466,7 @@ class TypeSet bool unknownObject() const { return !!(flags & (TYPE_FLAG_UNKNOWN | TYPE_FLAG_ANYOBJECT)); } bool empty() const { return !baseFlags() && !baseObjectCount(); } - bool noConstraints() const { return constraintList == NULL; } + bool noConstraints() const { return constraintList == nullptr; } bool hasAnyFlag(TypeFlags flags) const { JS_ASSERT((flags & TYPE_FLAG_BASE_MASK) == flags); @@ -497,7 +497,7 @@ class TypeSet /* * Iterate through the objects in this set. getObjectCount overapproximates * in the hash case (see SET_ARRAY_SIZE in jsinferinlines.h), and getObject - * may return NULL. + * may return nullptr. */ inline unsigned getObjectCount() const; inline TypeObjectKey *getObject(unsigned i) const; @@ -618,10 +618,10 @@ class TemporaryTypeSet : public TypeSet /* Whether the type set contains objects with any of a set of flags. */ bool hasObjectFlags(CompilerConstraintList *constraints, TypeObjectFlags flags); - /* Get the class shared by all objects in this set, or NULL. */ + /* Get the class shared by all objects in this set, or nullptr. */ const Class *getKnownClass(); - /* Get the prototype shared by all objects in this set, or NULL. */ + /* Get the prototype shared by all objects in this set, or nullptr. */ JSObject *getCommonPrototype(); /* Get the typed array type of all objects in this set, or TypedArrayObject::TYPE_MAX. */ @@ -636,7 +636,7 @@ class TemporaryTypeSet : public TypeSet /* Whether clasp->emulatesUndefined() is true for one or more objects in this set. */ bool maybeEmulatesUndefined(); - /* Get the single value which can appear in this type set, otherwise NULL. */ + /* Get the single value which can appear in this type set, otherwise nullptr. */ JSObject *getSingleton(); /* Whether any objects in the type set needs a barrier on id. */ @@ -1242,7 +1242,7 @@ class CompilerOutput public: CompilerOutput() - : script_(NULL), mode_(0), pendingInvalidation_(false) + : script_(nullptr), mode_(0), pendingInvalidation_(false) {} CompilerOutput(JSScript *script, jit::ExecutionMode mode) @@ -1255,10 +1255,10 @@ class CompilerOutput inline jit::IonScript *ion() const; bool isValid() const { - return script_ != NULL; + return script_ != nullptr; } void invalidate() { - script_ = NULL; + script_ = nullptr; } void setPendingInvalidation() { @@ -1440,12 +1440,12 @@ bool TypeHasProperty(JSContext *cx, TypeObject *obj, jsid id, const Value &value #else -inline const char * InferSpewColorReset() { return NULL; } -inline const char * InferSpewColor(TypeConstraint *constraint) { return NULL; } -inline const char * InferSpewColor(TypeSet *types) { return NULL; } +inline const char * InferSpewColorReset() { return nullptr; } +inline const char * InferSpewColor(TypeConstraint *constraint) { return nullptr; } +inline const char * InferSpewColor(TypeSet *types) { return nullptr; } inline void InferSpew(SpewChannel which, const char *fmt, ...) {} -inline const char * TypeString(Type type) { return NULL; } -inline const char * TypeObjectString(TypeObject *type) { return NULL; } +inline const char * TypeString(Type type) { return nullptr; } +inline const char * TypeObjectString(TypeObject *type) { return nullptr; } #endif diff --git a/js/src/jsinferinlines.h b/js/src/jsinferinlines.h index cc5f9cad7277..30d470573bf7 100644 --- a/js/src/jsinferinlines.h +++ b/js/src/jsinferinlines.h @@ -29,7 +29,7 @@ inline bool js::TaggedProto::isObject() const { - /* Skip NULL and Proxy::LazyProto. */ + /* Skip nullptr and Proxy::LazyProto. */ return uintptr_t(proto) > uintptr_t(Proxy::LazyProto); } @@ -107,7 +107,7 @@ inline CompilerOutput* RecompileInfo::compilerOutput(TypeCompartment &types) const { if (!types.constrainedOutputs || outputIndex >= types.constrainedOutputs->length()) - return NULL; + return nullptr; return &(*types.constrainedOutputs)[outputIndex]; } @@ -371,7 +371,7 @@ GetTypeNewObject(JSContext *cx, JSProtoKey key) { RootedObject proto(cx); if (!js_GetClassPrototype(cx, key, &proto)) - return NULL; + return nullptr; return cx->getNewType(GetClassForProtoKey(key), proto.get()); } @@ -623,8 +623,8 @@ TypeScript::BytecodeTypes(JSScript *script, jsbytecode *pc) TypeScript::StandardType(JSContext *cx, JSProtoKey key) { RootedObject proto(cx); - if (!js_GetClassPrototype(cx, key, &proto, NULL)) - return NULL; + if (!js_GetClassPrototype(cx, key, &proto, nullptr)) + return nullptr; return cx->getNewType(GetClassForProtoKey(key), proto.get()); } @@ -891,7 +891,7 @@ HashKey(T v) /* * Insert space for an element into the specified set and grow its capacity if needed. - * returned value is an existing or new entry (NULL if new). + * returned value is an existing or new entry (nullptr if new). */ template static U ** @@ -904,7 +904,7 @@ HashSetInsertTry(LifoAlloc &alloc, U **&values, unsigned &count, T key) bool converting = (count == SET_ARRAY_SIZE); if (!converting) { - while (values[insertpos] != NULL) { + while (values[insertpos] != nullptr) { if (KEY::getKey(values[insertpos]) == key) return &values[insertpos]; insertpos = (insertpos + 1) & (capacity - 1); @@ -921,13 +921,13 @@ HashSetInsertTry(LifoAlloc &alloc, U **&values, unsigned &count, T key) U **newValues = alloc.newArray(newCapacity); if (!newValues) - return NULL; + return nullptr; mozilla::PodZero(newValues, newCapacity); for (unsigned i = 0; i < capacity; i++) { if (values[i]) { unsigned pos = HashKey(KEY::getKey(values[i])) & (newCapacity - 1); - while (newValues[pos] != NULL) + while (newValues[pos] != nullptr) pos = (pos + 1) & (newCapacity - 1); newValues[pos] = values[i]; } @@ -936,21 +936,21 @@ HashSetInsertTry(LifoAlloc &alloc, U **&values, unsigned &count, T key) values = newValues; insertpos = HashKey(key) & (newCapacity - 1); - while (values[insertpos] != NULL) + while (values[insertpos] != nullptr) insertpos = (insertpos + 1) & (newCapacity - 1); return &values[insertpos]; } /* * Insert an element into the specified set if it is not already there, returning - * an entry which is NULL if the element was not there. + * an entry which is nullptr if the element was not there. */ template static inline U ** HashSetInsert(LifoAlloc &alloc, U **&values, unsigned &count, T key) { if (count == 0) { - JS_ASSERT(values == NULL); + JS_ASSERT(values == nullptr); count++; return (U **) &values; } @@ -963,7 +963,7 @@ HashSetInsert(LifoAlloc &alloc, U **&values, unsigned &count, T key) values = alloc.newArray(SET_ARRAY_SIZE); if (!values) { values = (U **) oldData; - return NULL; + return nullptr; } mozilla::PodZero(values, SET_ARRAY_SIZE); count++; @@ -987,35 +987,35 @@ HashSetInsert(LifoAlloc &alloc, U **&values, unsigned &count, T key) return HashSetInsertTry(alloc, values, count, key); } -/* Lookup an entry in a hash set, return NULL if it does not exist. */ +/* Lookup an entry in a hash set, return nullptr if it does not exist. */ template static inline U * HashSetLookup(U **values, unsigned count, T key) { if (count == 0) - return NULL; + return nullptr; if (count == 1) - return (KEY::getKey((U *) values) == key) ? (U *) values : NULL; + return (KEY::getKey((U *) values) == key) ? (U *) values : nullptr; if (count <= SET_ARRAY_SIZE) { for (unsigned i = 0; i < count; i++) { if (KEY::getKey(values[i]) == key) return values[i]; } - return NULL; + return nullptr; } unsigned capacity = HashSetCapacity(count); unsigned pos = HashKey(key) & (capacity - 1); - while (values[pos] != NULL) { + while (values[pos] != nullptr) { if (KEY::getKey(values[pos]) == key) return values[pos]; pos = (pos + 1) & (capacity - 1); } - return NULL; + return nullptr; } inline TypeObjectKey * @@ -1060,7 +1060,7 @@ TypeSet::hasType(Type type) const } else { return !!(flags & TYPE_FLAG_ANYOBJECT) || HashSetLookup - (objectSet, baseObjectCount(), type.objectKey()) != NULL; + (objectSet, baseObjectCount(), type.objectKey()) != nullptr; } } @@ -1076,7 +1076,7 @@ inline void TypeSet::clearObjects() { setBaseObjectCount(0); - objectSet = NULL; + objectSet = nullptr; } inline void @@ -1205,14 +1205,14 @@ inline JSObject * TypeSet::getSingleObject(unsigned i) const { TypeObjectKey *key = getObject(i); - return (key && key->isSingleObject()) ? key->asSingleObject() : NULL; + return (key && key->isSingleObject()) ? key->asSingleObject() : nullptr; } inline TypeObject * TypeSet::getTypeObject(unsigned i) const { TypeObjectKey *key = getObject(i); - return (key && key->isTypeObject()) ? key->asTypeObject() : NULL; + return (key && key->isTypeObject()) ? key->asTypeObject() : nullptr; } inline bool @@ -1221,7 +1221,7 @@ TypeSet::getTypeOrSingleObject(JSContext *cx, unsigned i, TypeObject **result) c JS_ASSERT(result); JS_ASSERT(cx->compartment()->activeAnalysis); - *result = NULL; + *result = nullptr; TypeObject *type = getTypeObject(i); if (!type) { @@ -1246,7 +1246,7 @@ TypeSet::getObjectClass(unsigned i) const return object->getClass(); if (TypeObject *object = getTypeObject(i)) return object->clasp; - return NULL; + return nullptr; } ///////////////////////////////////////////////////////////////////// @@ -1297,15 +1297,15 @@ TypeObject::getProperty(ExclusiveContext *cx, jsid id) (cx->typeLifoAlloc(), propertySet, propertyCount, id); if (!pprop) { cx->compartment()->types.setPendingNukeTypes(cx); - return NULL; + return nullptr; } if (!*pprop) { setBasePropertyCount(propertyCount); if (!addProperty(cx, id, pprop)) { setBasePropertyCount(0); - propertySet = NULL; - return NULL; + propertySet = nullptr; + return nullptr; } if (propertyCount == OBJECT_FLAG_PROPERTY_COUNT_LIMIT) { markUnknown(cx); @@ -1337,7 +1337,7 @@ TypeObject::maybeGetProperty(ExclusiveContext *cx, jsid id) Property *prop = HashSetLookup (propertySet, basePropertyCount(), id); - return prop ? &prop->types : NULL; + return prop ? &prop->types : nullptr; } inline unsigned @@ -1484,8 +1484,8 @@ inline void JSScript::clearAnalysis() { if (types) { - types->analysis = NULL; - types->bytecodeMap = NULL; + types->analysis = nullptr; + types->bytecodeMap = nullptr; } } diff --git a/js/src/jsiter.cpp b/js/src/jsiter.cpp index f57ef22b9eb4..98a14ba6d79d 100644 --- a/js/src/jsiter.cpp +++ b/js/src/jsiter.cpp @@ -250,7 +250,7 @@ Snapshot(JSContext *cx, JSObject *pobj_, unsigned flags, AutoIdVector *props) if (flags & JSITER_OWNONLY) break; - } while ((pobj = pobj->getProto()) != NULL); + } while ((pobj = pobj->getProto()) != nullptr); #ifdef JS_MORE_DETERMINISTIC @@ -374,24 +374,24 @@ static inline PropertyIteratorObject * NewPropertyIteratorObject(JSContext *cx, unsigned flags) { if (flags & JSITER_ENUMERATE) { - RootedTypeObject type(cx, cx->getNewType(&PropertyIteratorObject::class_, NULL)); + RootedTypeObject type(cx, cx->getNewType(&PropertyIteratorObject::class_, nullptr)); if (!type) - return NULL; + return nullptr; - JSObject *metadata = NULL; + JSObject *metadata = nullptr; if (!NewObjectMetadata(cx, &metadata)) - return NULL; + return nullptr; const Class *clasp = &PropertyIteratorObject::class_; - RootedShape shape(cx, EmptyShape::getInitialShape(cx, clasp, NULL, NULL, metadata, + RootedShape shape(cx, EmptyShape::getInitialShape(cx, clasp, nullptr, nullptr, metadata, ITERATOR_FINALIZE_KIND)); if (!shape) - return NULL; + return nullptr; JSObject *obj = JSObject::create(cx, ITERATOR_FINALIZE_KIND, GetInitialHeap(GenericObject, clasp), shape, type); if (!obj) - return NULL; + return nullptr; JS_ASSERT(obj->numFixedSlots() == JSObject::ITER_CLASS_NFIXED_SLOTS); return &obj->as(); @@ -409,7 +409,7 @@ NativeIterator::allocateIterator(JSContext *cx, uint32_t slength, const AutoIdVe + plength * sizeof(JSString *) + slength * sizeof(Shape *)); if (!ni) - return NULL; + return nullptr; AutoValueVector strings(cx); ni->props_array = ni->props_cursor = (HeapPtr *) (ni + 1); ni->props_end = ni->props_array + plength; @@ -417,12 +417,12 @@ NativeIterator::allocateIterator(JSContext *cx, uint32_t slength, const AutoIdVe for (size_t i = 0; i < plength; i++) { JSFlatString *str = IdToString(cx, props[i]); if (!str || !strings.append(StringValue(str))) - return NULL; + return nullptr; ni->props_array[i].init(str); } } - ni->next_ = NULL; - ni->prev_ = NULL; + ni->next_ = nullptr; + ni->prev_ = nullptr; return ni; } @@ -431,7 +431,7 @@ NativeIterator::allocateSentinel(JSContext *cx) { NativeIterator *ni = (NativeIterator *)js_malloc(sizeof(NativeIterator)); if (!ni) - return NULL; + return nullptr; PodZero(ni); @@ -578,12 +578,12 @@ js::GetIterator(JSContext *cx, HandleObject obj, unsigned flags, MutableHandleVa char *bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, val, NullPtr()); if (!bytes) return false; - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_ITERABLE, bytes); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_ITERABLE, bytes); js_free(bytes); return false; } - if (!Invoke(cx, ObjectOrNullValue(obj), method, 0, NULL, vp)) + if (!Invoke(cx, ObjectOrNullValue(obj), method, 0, nullptr, vp)) return false; JSObject *resultObj = ToObject(cx, vp); @@ -695,13 +695,13 @@ js::GetIterator(JSContext *cx, HandleObject obj, unsigned flags, MutableHandleVa AutoIdVector keys(cx); if (flags & JSITER_FOREACH) { - if (JS_LIKELY(obj != NULL) && !Snapshot(cx, obj, flags, &keys)) + if (JS_LIKELY(obj != nullptr) && !Snapshot(cx, obj, flags, &keys)) return false; JS_ASSERT(shapes.empty()); if (!VectorToValueIterator(cx, obj, flags, keys, vp)) return false; } else { - if (JS_LIKELY(obj != NULL) && !Snapshot(cx, obj, flags, &keys)) + if (JS_LIKELY(obj != nullptr) && !Snapshot(cx, obj, flags, &keys)) return false; if (!VectorToKeyIterator(cx, obj, flags, keys, shapes.length(), key, vp)) return false; @@ -723,7 +723,7 @@ js::GetIteratorObject(JSContext *cx, HandleObject obj, uint32_t flags) { RootedValue value(cx); if (!GetIterator(cx, obj, flags, &value)) - return NULL; + return nullptr; return &value.toObject(); } @@ -860,14 +860,14 @@ const Class PropertyIteratorObject::class_ = { JS_ResolveStub, JS_ConvertStub, finalize, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ trace, { - NULL, /* outerObject */ - NULL, /* innerObject */ + nullptr, /* outerObject */ + nullptr, /* innerObject */ iterator_iteratorObject, } }; @@ -879,7 +879,7 @@ ElementIteratorObject::create(JSContext *cx, Handle target) { RootedObject proto(cx, cx->global()->getOrCreateElementIteratorPrototype(cx)); if (!proto) - return NULL; + return nullptr; RootedObject iterobj(cx, NewObjectWithGivenProto(cx, &class_, proto, cx->global())); if (iterobj) { iterobj->setReservedSlot(TargetSlot, target); @@ -962,7 +962,7 @@ const Class ElementIteratorObject::class_ = { JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, - NULL /* finalize */ + nullptr /* finalize */ }; const JSFunctionSpec ElementIteratorObject::methods[] = { @@ -1140,7 +1140,7 @@ SuppressDeletedPropertyHelper(JSContext *cx, HandleObject obj, StringPredicate p * it's no longer going to be marked, and ensures that * any existing remembered set entry will be dropped. */ - *ni->props_end = NULL; + *ni->props_end = nullptr; } /* Don't reuse modified native iterators. */ @@ -1215,7 +1215,7 @@ bool js_IteratorMore(JSContext *cx, HandleObject iterobj, MutableHandleValue rval) { /* Fast path for native iterators */ - NativeIterator *ni = NULL; + NativeIterator *ni = nullptr; if (iterobj->is()) { /* Key iterators are handled by fast-paths. */ ni = iterobj->as().getNativeIterator(); @@ -1252,7 +1252,7 @@ js_IteratorMore(JSContext *cx, HandleObject iterobj, MutableHandleValue rval) /* Call the iterator object's .next method. */ if (!JSObject::getProperty(cx, iterobj, iterobj, cx->names().next, rval)) return false; - if (!Invoke(cx, ObjectValue(*iterobj), rval, 0, NULL, rval)) { + if (!Invoke(cx, ObjectValue(*iterobj), rval, 0, nullptr, rval)) { /* Check for StopIteration. */ if (!cx->isExceptionPending() || !JS_IsStopIteration(cx->getPendingException())) return false; @@ -1314,11 +1314,11 @@ const Class StopIterationObject::class_ = { JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, - NULL, /* finalize */ - NULL, /* checkAccess */ - NULL, /* call */ + nullptr, /* finalize */ + nullptr, /* checkAccess */ + nullptr, /* call */ stopiter_hasInstance, - NULL /* construct */ + nullptr /* construct */ }; bool @@ -1367,7 +1367,7 @@ FinalizeGenerator(FreeOp *fop, JSObject *obj) JS_ASSERT(gen->state == JSGEN_NEWBORN || gen->state == JSGEN_CLOSED || gen->state == JSGEN_OPEN); - // If gen->state is JSGEN_CLOSED, gen->fp may be NULL. + // If gen->state is JSGEN_CLOSED, gen->fp may be nullptr. if (gen->fp) JS_POISON(gen->fp, JS_FREE_PATTERN, sizeof(StackFrame)); JS_POISON(gen, JS_FREE_PATTERN, sizeof(JSGenerator)); @@ -1433,7 +1433,7 @@ SetGeneratorClosed(JSContext *cx, JSGenerator *gen) MakeRangeGCSafe(gen->fp->generatorSlotsSnapshotBegin(), gen->regs.sp); PodZero(&gen->regs, 1); - gen->fp = NULL; + gen->fp = nullptr; #endif } @@ -1499,14 +1499,14 @@ const Class LegacyGeneratorObject::class_ = { JS_ResolveStub, JS_ConvertStub, FinalizeGenerator, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ TraceGenerator, { - NULL, /* outerObject */ - NULL, /* innerObject */ + nullptr, /* outerObject */ + nullptr, /* innerObject */ iterator_iteratorObject, } }; @@ -1522,14 +1522,14 @@ const Class StarGeneratorObject::class_ = { JS_ResolveStub, JS_ConvertStub, FinalizeGenerator, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ TraceGenerator, { - NULL, /* outerObject */ - NULL, /* innerObject */ + nullptr, /* outerObject */ + nullptr, /* innerObject */ iterator_iteratorObject, } }; @@ -1558,23 +1558,23 @@ js_NewGenerator(JSContext *cx, const FrameRegs &stackRegs) // FIXME: This would be faster if we could avoid doing a lookup to get // the prototype for the instance. Bug 906600. if (!JSObject::getProperty(cx, fun, fun, cx->names().classPrototype, &pval)) - return NULL; - JSObject *proto = pval.isObject() ? &pval.toObject() : NULL; + return nullptr; + JSObject *proto = pval.isObject() ? &pval.toObject() : nullptr; if (!proto) { proto = global->getOrCreateStarGeneratorObjectPrototype(cx); if (!proto) - return NULL; + return nullptr; } obj = NewObjectWithGivenProto(cx, &StarGeneratorObject::class_, proto, global); } else { JS_ASSERT(stackfp->script()->isLegacyGenerator()); JSObject *proto = global->getOrCreateLegacyGeneratorObjectPrototype(cx); if (!proto) - return NULL; + return nullptr; obj = NewObjectWithGivenProto(cx, &LegacyGeneratorObject::class_, proto, global); } if (!obj) - return NULL; + return nullptr; /* Load and compute stack slot counts. */ Value *stackvp = stackfp->generatorArgsSnapshotBegin(); @@ -1592,7 +1592,7 @@ js_NewGenerator(JSContext *cx, const FrameRegs &stackRegs) JSGenerator *gen = (JSGenerator *) cx->calloc_(nbytes); if (!gen) - return NULL; + return nullptr; /* Cut up floatingStack space. */ HeapValue *genvp = gen->stackSnapshot; @@ -1604,7 +1604,7 @@ js_NewGenerator(JSContext *cx, const FrameRegs &stackRegs) gen->obj.init(obj); gen->state = JSGEN_NEWBORN; gen->fp = genfp; - gen->prevGenerator = NULL; + gen->prevGenerator = nullptr; /* Copy from the stack to the generator's floating frame. */ gen->regs.rebaseFromTo(stackRegs, *genfp); @@ -1637,7 +1637,7 @@ SendToGenerator(JSContext *cx, JSGeneratorOp op, HandleObject obj, JS_ASSERT(generatorKind == LegacyGenerator || generatorKind == StarGenerator); if (gen->state == JSGEN_RUNNING || gen->state == JSGEN_CLOSING) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NESTING_GENERATOR); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NESTING_GENERATOR); return false; } @@ -1720,7 +1720,7 @@ star_generator_next(JSContext *cx, CallArgs args) JSGenerator *gen = thisObj->as().getGenerator(); if (gen->state == JSGEN_CLOSED) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_GENERATOR_FINISHED); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_GENERATOR_FINISHED); return false; } @@ -1742,7 +1742,7 @@ star_generator_throw(JSContext *cx, CallArgs args) JSGenerator *gen = thisObj->as().getGenerator(); if (gen->state == JSGEN_CLOSED) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_GENERATOR_FINISHED); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_GENERATOR_FINISHED); return false; } @@ -1862,7 +1862,7 @@ NewObjectWithObjectPrototype(JSContext *cx, Handle global) { JSObject *proto = global->getOrCreateObjectPrototype(cx); if (!proto) - return NULL; + return nullptr; return NewObjectWithGivenProto(cx, &JSObject::class_, proto, global); } @@ -1871,7 +1871,7 @@ NewObjectWithFunctionPrototype(JSContext *cx, Handle global) { JSObject *proto = global->getOrCreateFunctionPrototype(cx); if (!proto) - return NULL; + return nullptr; return NewObjectWithGivenProto(cx, &JSObject::class_, proto, global); } @@ -1891,7 +1891,7 @@ GlobalObject::initIteratorClasses(JSContext *cx, Handle global) NativeIterator *ni = NativeIterator::allocateIterator(cx, 0, blank); if (!ni) return false; - ni->init(NULL, NULL, 0 /* flags */, 0, 0); + ni->init(nullptr, nullptr, 0 /* flags */, 0, 0); iteratorProto->as().setNativeIterator(ni); @@ -1901,7 +1901,7 @@ GlobalObject::initIteratorClasses(JSContext *cx, Handle global) return false; if (!LinkConstructorAndPrototype(cx, ctor, iteratorProto)) return false; - if (!DefinePropertiesAndBrand(cx, iteratorProto, NULL, iterator_methods)) + if (!DefinePropertiesAndBrand(cx, iteratorProto, nullptr, iterator_methods)) return false; if (!DefineConstructorAndPrototype(cx, global, JSProto_Iterator, ctor, iteratorProto)) return false; @@ -1911,14 +1911,14 @@ GlobalObject::initIteratorClasses(JSContext *cx, Handle global) if (global->getSlot(ELEMENT_ITERATOR_PROTO).isUndefined()) { const Class *cls = &ElementIteratorObject::class_; proto = global->createBlankPrototypeInheriting(cx, cls, *iteratorProto); - if (!proto || !DefinePropertiesAndBrand(cx, proto, NULL, ElementIteratorObject::methods)) + if (!proto || !DefinePropertiesAndBrand(cx, proto, nullptr, ElementIteratorObject::methods)) return false; global->setReservedSlot(ELEMENT_ITERATOR_PROTO, ObjectValue(*proto)); } if (global->getSlot(LEGACY_GENERATOR_OBJECT_PROTO).isUndefined()) { proto = NewObjectWithObjectPrototype(cx, global); - if (!proto || !DefinePropertiesAndBrand(cx, proto, NULL, legacy_generator_methods)) + if (!proto || !DefinePropertiesAndBrand(cx, proto, nullptr, legacy_generator_methods)) return false; global->setReservedSlot(LEGACY_GENERATOR_OBJECT_PROTO, ObjectValue(*proto)); } @@ -1927,7 +1927,7 @@ GlobalObject::initIteratorClasses(JSContext *cx, Handle global) RootedObject genObjectProto(cx, NewObjectWithObjectPrototype(cx, global)); if (!genObjectProto) return false; - if (!DefinePropertiesAndBrand(cx, genObjectProto, NULL, star_generator_methods)) + if (!DefinePropertiesAndBrand(cx, genObjectProto, nullptr, star_generator_methods)) return false; RootedObject genFunctionProto(cx, NewObjectWithFunctionPrototype(cx, global)); @@ -1973,6 +1973,6 @@ js_InitIteratorClasses(JSContext *cx, HandleObject obj) { Rooted global(cx, &obj->as()); if (!GlobalObject::initIteratorClasses(cx, global)) - return NULL; + return nullptr; return global->getIteratorPrototype(); } diff --git a/js/src/jsiter.h b/js/src/jsiter.h index ab3f64fbe27e..0033eca43c48 100644 --- a/js/src/jsiter.h +++ b/js/src/jsiter.h @@ -98,8 +98,8 @@ struct NativeIterator next_->prev_ = prev_; prev_->next_ = next_; - next_ = NULL; - prev_ = NULL; + next_ = nullptr; + prev_ = nullptr; } static NativeIterator *allocateSentinel(JSContext *cx); diff --git a/js/src/jsmath.cpp b/js/src/jsmath.cpp index 8dd421a9e99d..232ee221d1a3 100644 --- a/js/src/jsmath.cpp +++ b/js/src/jsmath.cpp @@ -1481,19 +1481,19 @@ static const JSFunctionSpec math_static_methods[] = { JSObject * js_InitMathClass(JSContext *cx, HandleObject obj) { - RootedObject Math(cx, NewObjectWithClassProto(cx, &MathClass, NULL, obj, SingletonObject)); + RootedObject Math(cx, NewObjectWithClassProto(cx, &MathClass, nullptr, obj, SingletonObject)); if (!Math) - return NULL; + return nullptr; if (!JS_DefineProperty(cx, obj, js_Math_str, OBJECT_TO_JSVAL(Math), JS_PropertyStub, JS_StrictPropertyStub, 0)) { - return NULL; + return nullptr; } if (!JS_DefineFunctions(cx, Math, math_static_methods)) - return NULL; + return nullptr; if (!JS_DefineConstDoubles(cx, Math, math_constants)) - return NULL; + return nullptr; MarkStandardClassInitializedNoProto(obj, &MathClass); diff --git a/js/src/jsnativestack.cpp b/js/src/jsnativestack.cpp index 057fe6536eb3..13802600839a 100644 --- a/js/src/jsnativestack.cpp +++ b/js/src/jsnativestack.cpp @@ -142,7 +142,7 @@ js::GetNativeStackBaseImpl() if (fs) { char line[100]; unsigned long stackAddr = (unsigned long)&sattr; - while (fgets(line, sizeof(line), fs) != NULL) { + while (fgets(line, sizeof(line), fs) != nullptr) { unsigned long stackStart; unsigned long stackEnd; if (sscanf(line, "%lx-%lx ", &stackStart, &stackEnd) == 2 && diff --git a/js/src/jsnum.cpp b/js/src/jsnum.cpp index 6557ce7c6729..cfe1c80d4557 100644 --- a/js/src/jsnum.cpp +++ b/js/src/jsnum.cpp @@ -531,7 +531,7 @@ num_toSource(JSContext *cx, unsigned argc, Value *vp) } #endif -ToCStringBuf::ToCStringBuf() :dbuf(NULL) +ToCStringBuf::ToCStringBuf() :dbuf(nullptr) { JS_STATIC_ASSERT(sbufSize >= DTOSTR_STANDARD_BUFFER_SIZE); } @@ -546,14 +546,14 @@ static JSFlatString * LookupDtoaCache(ThreadSafeContext *cx, double d) { if (!cx->isExclusiveContext()) - return NULL; + return nullptr; if (JSCompartment *comp = cx->asExclusiveContext()->compartment()) { if (JSFlatString *str = comp->dtoaCache.lookup(10, d)) return str; } - return NULL; + return nullptr; } JS_ALWAYS_INLINE @@ -604,7 +604,7 @@ js::Int32ToString(ThreadSafeContext *cx, int32_t si) JSShortString *str = js_NewGCShortString(cx); if (!str) - return NULL; + return nullptr; jschar buffer[JSShortString::MAX_SHORT_LENGTH + 1]; size_t length; @@ -636,7 +636,7 @@ js::Int32ToAtom(ExclusiveContext *cx, int32_t si) JSAtom *atom = AtomizeMaybeGC(cx, start, length); if (!atom) - return NULL; + return nullptr; CacheNumber(cx, si, atom); return atom; @@ -648,7 +648,7 @@ js::Int32ToAtom(ExclusiveContext *cx, int32_t si); template JSAtom * js::Int32ToAtom(ExclusiveContext *cx, int32_t si); -/* Returns a non-NULL pointer to inside cbuf. */ +/* Returns a non-nullptr pointer to inside cbuf. */ static char * IntToCString(ToCStringBuf *cbuf, int i, size_t *len, int base = 10) { @@ -704,7 +704,7 @@ num_toString_impl(JSContext *cx, CallArgs args) return false; if (d2 < 2 || d2 > 36) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_RADIX); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_RADIX); return false; } @@ -892,7 +892,7 @@ ComputePrecisionInRange(JSContext *cx, int minPrecision, int maxPrecision, Handl ToCStringBuf cbuf; if (char *numStr = NumberToCString(cx, &cbuf, prec, 10)) - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_PRECISION_RANGE, numStr); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_PRECISION_RANGE, numStr); return false; } @@ -1233,29 +1233,29 @@ js_InitNumberClass(JSContext *cx, HandleObject obj) RootedObject numberProto(cx, global->createBlankPrototype(cx, &NumberObject::class_)); if (!numberProto) - return NULL; + return nullptr; numberProto->as().setPrimitiveValue(0); RootedFunction ctor(cx); ctor = global->createConstructor(cx, Number, cx->names().Number, 1); if (!ctor) - return NULL; + return nullptr; if (!LinkConstructorAndPrototype(cx, ctor, numberProto)) - return NULL; + return nullptr; /* Add numeric constants (MAX_VALUE, NaN, &c.) to the Number constructor. */ if (!JS_DefineConstDoubles(cx, ctor, number_constants)) - return NULL; + return nullptr; - if (!DefinePropertiesAndBrand(cx, ctor, NULL, number_static_methods)) - return NULL; + if (!DefinePropertiesAndBrand(cx, ctor, nullptr, number_static_methods)) + return nullptr; - if (!DefinePropertiesAndBrand(cx, numberProto, NULL, number_methods)) - return NULL; + if (!DefinePropertiesAndBrand(cx, numberProto, nullptr, number_methods)) + return nullptr; if (!JS_DefineFunctions(cx, global, number_functions)) - return NULL; + return nullptr; RootedValue valueNaN(cx, cx->runtime()->NaNValue); RootedValue valueInfinity(cx, cx->runtime()->positiveInfinityValue); @@ -1268,11 +1268,11 @@ js_InitNumberClass(JSContext *cx, HandleObject obj) JS_PropertyStub, JS_StrictPropertyStub, JSPROP_PERMANENT | JSPROP_READONLY, 0, 0)) { - return NULL; + return nullptr; } if (!DefineConstructorAndPrototype(cx, global, JSProto_Number, ctor, numberProto)) - return NULL; + return nullptr; return numberProto; } @@ -1326,15 +1326,15 @@ js_NumberToStringWithBase(ThreadSafeContext *cx, double d, int base) /* * Caller is responsible for error reporting. When called from trace, - * returning NULL here will cause us to fall of trace and then retry + * returning nullptr here will cause us to fall of trace and then retry * from the interpreter (which will report the error). */ if (base < 2 || base > 36) - return NULL; + return nullptr; JSCompartment *comp = cx->isExclusiveContext() ? cx->asExclusiveContext()->compartment() - : NULL; + : nullptr; int32_t i; if (mozilla::DoubleIsInt32(d, &i)) { @@ -1365,7 +1365,7 @@ js_NumberToStringWithBase(ThreadSafeContext *cx, double d, int base) numStr = FracNumberToCString(cx, &cbuf, d, base); if (!numStr) { js_ReportOutOfMemory(cx); - return NULL; + return nullptr; } JS_ASSERT_IF(base == 10, !cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize); @@ -1409,14 +1409,14 @@ js::NumberToAtom(ExclusiveContext *cx, double d) char *numStr = FracNumberToCString(cx, &cbuf, d); if (!numStr) { js_ReportOutOfMemory(cx); - return NULL; + return nullptr; } JS_ASSERT(!cbuf.dbuf && numStr >= cbuf.sbuf && numStr < cbuf.sbuf + cbuf.sbufSize); size_t length = strlen(numStr); JSAtom *atom = AtomizeMaybeGC(cx, numStr, length); if (!atom) - return NULL; + return nullptr; CacheNumber(cx, d, atom); @@ -1434,7 +1434,7 @@ js::NumberToString(JSContext *cx, double d) { if (JSString *str = js_NumberToStringWithBase(cx, d, 10)) return &str->asFlat(); - return NULL; + return nullptr; } JSFlatString * @@ -1449,7 +1449,7 @@ js::IndexToString(JSContext *cx, uint32_t index) JSShortString *str = js_NewGCShortString(cx); if (!str) - return NULL; + return nullptr; jschar buffer[JSShortString::MAX_SHORT_LENGTH + 1]; RangedPtr end(buffer + JSShortString::MAX_SHORT_LENGTH, diff --git a/js/src/jsnum.h b/js/src/jsnum.h index 1ccec4aeac0f..3c73918825e4 100644 --- a/js/src/jsnum.h +++ b/js/src/jsnum.h @@ -101,7 +101,7 @@ struct ToCStringBuf /* * Convert a number to a C string. When base==10, this function implements * ToString() as specified by ECMA-262-5 section 9.8.1. It handles integral - * values cheaply. Return NULL if we ran out of memory. See also + * values cheaply. Return nullptr if we ran out of memory. See also * js_NumberToCString(). */ extern char * diff --git a/js/src/jsobj.cpp b/js/src/jsobj.cpp index 23d91b17c24e..93d5305c848e 100644 --- a/js/src/jsobj.cpp +++ b/js/src/jsobj.cpp @@ -89,8 +89,8 @@ JS_ObjectToInnerObject(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); if (!obj) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INACTIVE); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INACTIVE); + return nullptr; } return GetInnerObject(cx, obj); } @@ -107,8 +107,8 @@ JSObject * js::NonNullObject(JSContext *cx, const Value &v) { if (v.isPrimitive()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_NONNULL_OBJECT); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT); + return nullptr; } return &v.toObject(); } @@ -228,7 +228,7 @@ js::GetOwnPropertyDescriptor(JSContext *cx, HandleObject obj, HandleId id, if (!HasOwnProperty(cx, obj->getOps()->lookupGeneric, obj, id, &pobj, &shape)) return false; if (!shape) { - desc.object().set(NULL); + desc.object().set(nullptr); return true; } @@ -269,7 +269,7 @@ js::GetFirstArgumentAsObject(JSContext *cx, const CallArgs &args, const char *me MutableHandleObject objp) { if (args.length() == 0) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, method, "0", "s"); return false; } @@ -279,7 +279,7 @@ js::GetFirstArgumentAsObject(JSContext *cx, const CallArgs &args, const char *me char *bytes = DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, v, NullPtr()); if (!bytes) return false; - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNEXPECTED_TYPE, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, bytes, "not an object"); js_free(bytes); return false; @@ -315,7 +315,7 @@ PropDesc::initialize(JSContext *cx, const Value &origval, bool checkAccessors) /* 8.10.5 step 1 */ if (v.isPrimitive()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_NONNULL_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT); return false; } RootedObject desc(cx, &v.toObject()); @@ -401,7 +401,7 @@ PropDesc::initialize(JSContext *cx, const Value &origval, bool checkAccessors) /* 8.10.7 step 9 */ if ((hasGet() || hasSet()) && (hasValue() || hasWritable())) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INVALID_DESCRIPTOR); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INVALID_DESCRIPTOR); return false; } @@ -453,7 +453,7 @@ js::Throw(JSContext *cx, jsid id, unsigned errorNumber) JSAutoByteString bytes(cx, idstr); if (!bytes) return false; - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, errorNumber, bytes.ptr()); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, errorNumber, bytes.ptr()); return false; } @@ -464,10 +464,10 @@ js::Throw(JSContext *cx, JSObject *obj, unsigned errorNumber) RootedValue val(cx, ObjectValue(*obj)); js_ReportValueErrorFlags(cx, JSREPORT_ERROR, errorNumber, JSDVG_IGNORE_STACK, val, NullPtr(), - NULL, NULL); + nullptr, nullptr); } else { JS_ASSERT(js_ErrorFormatString[errorNumber].argCount == 0); - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, errorNumber); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, errorNumber); } return false; } @@ -554,7 +554,7 @@ DefinePropertyOnObject(JSContext *cx, HandleObject obj, HandleId id, const PropD RootedShape shape(cx); RootedObject obj2(cx); JS_ASSERT(!obj->getOps()->lookupGeneric); - if (!HasOwnProperty(cx, NULL, obj, id, &obj2, &shape)) + if (!HasOwnProperty(cx, nullptr, obj, id, &obj2, &shape)) return false; JS_ASSERT(!obj->getOps()->defineProperty); @@ -1266,24 +1266,24 @@ NewObject(ExclusiveContext *cx, const Class *clasp, types::TypeObject *type_, JS RootedTypeObject type(cx, type_); - JSObject *metadata = NULL; + JSObject *metadata = nullptr; if (!NewObjectMetadata(cx, &metadata)) - return NULL; + return nullptr; RootedShape shape(cx, EmptyShape::getInitialShape(cx, clasp, TaggedProto(type->proto), parent, metadata, kind)); if (!shape) - return NULL; + return nullptr; gc::InitialHeap heap = GetInitialHeap(newKind, clasp); JSObject *obj = JSObject::create(cx, kind, heap, shape, type); if (!obj) - return NULL; + return nullptr; if (newKind == SingletonObject) { RootedObject nobj(cx, obj); if (!JSObject::setSingletonType(cx, nobj)) - return NULL; + return nullptr; obj = nobj; } @@ -1293,7 +1293,7 @@ NewObject(ExclusiveContext *cx, const Class *clasp, types::TypeObject *type_, JS */ if (clasp->trace && !(clasp->flags & JSCLASS_IMPLEMENTS_BARRIERS)) { if (!cx->shouldBeJSContext()) - return NULL; + return nullptr; JSRuntime *rt = cx->asJSContext()->runtime(); rt->gcIncrementalEnabled = false; @@ -1350,9 +1350,9 @@ js::NewObjectWithGivenProto(ExclusiveContext *cxArg, const js::Class *clasp, } } - types::TypeObject *type = cxArg->getNewType(clasp, proto, NULL); + types::TypeObject *type = cxArg->getNewType(clasp, proto, nullptr); if (!type) - return NULL; + return nullptr; /* * Default parent to the parent of the prototype, which was set from @@ -1363,7 +1363,7 @@ js::NewObjectWithGivenProto(ExclusiveContext *cxArg, const js::Class *clasp, RootedObject obj(cxArg, NewObject(cxArg, clasp, type, parent, allocKind, newKind)); if (!obj) - return NULL; + return nullptr; if (entry != -1 && !obj->hasDynamicSlots()) { cxArg->asJSContext()->runtime()->newObjectCache.fillProto(entry, clasp, @@ -1418,15 +1418,15 @@ js::NewObjectWithClassProtoCommon(ExclusiveContext *cxArg, RootedObject proto(cxArg, protoArg); if (!FindProto(cxArg, clasp, &proto)) - return NULL; + return nullptr; types::TypeObject *type = cxArg->getNewType(clasp, proto.get()); if (!type) - return NULL; + return nullptr; JSObject *obj = NewObject(cxArg, clasp, type, parent, allocKind, newKind); if (!obj) - return NULL; + return nullptr; if (entry != -1 && !obj->hasDynamicSlots()) { cxArg->asJSContext()->runtime()->newObjectCache.fillGlobal(entry, clasp, @@ -1468,7 +1468,7 @@ NewObjectWithType(JSContext *cx, HandleTypeObject type, JSObject *parent, gc::Al JSObject *obj = NewObject(cx, &JSObject::class_, type, parent, allocKind, newKind); if (!obj) - return NULL; + return nullptr; if (entry != -1 && !obj->hasDynamicSlots()) cache.fillType(entry, &JSObject::class_, type, allocKind, obj); @@ -1505,7 +1505,7 @@ js::NewReshapedObject(JSContext *cx, HandleTypeObject type, JSObject *parent, { RootedObject res(cx, NewObjectWithType(cx, type, parent, kind)); if (!res) - return NULL; + return nullptr; if (shape->isEmptyShape()) return res; @@ -1515,7 +1515,7 @@ js::NewReshapedObject(JSContext *cx, HandleTypeObject type, JSObject *parent, { for (unsigned i = 0; i <= shape->slot(); i++) { if (!ids.append(JSID_VOID)) - return NULL; + return nullptr; } Shape *nshape = shape; while (!nshape->isEmptyShape()) { @@ -1529,9 +1529,9 @@ js::NewReshapedObject(JSContext *cx, HandleTypeObject type, JSObject *parent, RootedValue undefinedValue(cx, UndefinedValue()); for (unsigned i = 0; i < ids.length(); i++) { id = ids[i]; - if (!DefineNativeProperty(cx, res, id, undefinedValue, NULL, NULL, + if (!DefineNativeProperty(cx, res, id, undefinedValue, nullptr, nullptr, JSPROP_ENUMERATE, 0, 0, DNP_SKIP_TYPE)) { - return NULL; + return nullptr; } } JS_ASSERT(!res->inDictionaryMode()); @@ -1544,9 +1544,9 @@ js::CreateThis(JSContext *cx, const Class *newclasp, HandleObject callee) { RootedValue protov(cx); if (!JSObject::getProperty(cx, callee, callee, cx->names().classPrototype, &protov)) - return NULL; + return nullptr; - JSObject *proto = protov.isObjectOrNull() ? protov.toObjectOrNull() : NULL; + JSObject *proto = protov.isObjectOrNull() ? protov.toObjectOrNull() : nullptr; JSObject *parent = callee->getParent(); gc::AllocKind kind = NewObjectGCKind(newclasp); return NewObjectWithClassProto(cx, newclasp, proto, parent, kind); @@ -1565,12 +1565,12 @@ CreateThisForFunctionWithType(JSContext *cx, HandleTypeObject type, JSObject *pa gc::AllocKind kind = type->newScript()->allocKind; RootedObject res(cx, NewObjectWithType(cx, type, parent, kind, newKind)); if (!res) - return NULL; + return nullptr; RootedObject metadata(cx, res->getMetadata()); RootedShape shape(cx, type->newScript()->shape); JS_ALWAYS_TRUE(JSObject::setLastProperty(cx, res, shape)); if (metadata && !JSObject::setMetadata(cx, res, metadata)) - return NULL; + return nullptr; return res; } @@ -1587,7 +1587,7 @@ js::CreateThisForFunctionWithProto(JSContext *cx, HandleObject callee, JSObject if (proto) { RootedTypeObject type(cx, cx->getNewType(&JSObject::class_, proto, &callee->as())); if (!type) - return NULL; + return nullptr; res = CreateThisForFunctionWithType(cx, type, callee->getParent(), newKind); } else { gc::AllocKind allocKind = NewObjectGCKind(&JSObject::class_); @@ -1597,7 +1597,7 @@ js::CreateThisForFunctionWithProto(JSContext *cx, HandleObject callee, JSObject if (res && cx->typeInferenceEnabled()) { JSScript *script = callee->as().getOrCreateScript(cx); if (!script) - return NULL; + return nullptr; TypeScript::SetThis(cx, script, types::Type::ObjectType(res)); } @@ -1609,12 +1609,12 @@ js::CreateThisForFunction(JSContext *cx, HandleObject callee, bool newType) { RootedValue protov(cx); if (!JSObject::getProperty(cx, callee, callee, cx->names().classPrototype, &protov)) - return NULL; + return nullptr; JSObject *proto; if (protov.isObject()) proto = &protov.toObject(); else - proto = NULL; + proto = nullptr; NewObjectKind newKind = newType ? SingletonObject : GenericObject; JSObject *obj = CreateThisForFunctionWithProto(cx, callee, proto, newKind); @@ -1823,18 +1823,18 @@ JSObject * js::CloneObject(JSContext *cx, HandleObject obj, Handle proto, HandleObject parent) { if (!obj->isNative() && !obj->is()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); - return NULL; + return nullptr; } RootedObject clone(cx, NewObjectWithGivenProto(cx, obj->getClass(), proto, parent)); if (!clone) - return NULL; + return nullptr; if (obj->isNative()) { if (clone->is() && (obj->compartment() != clone->compartment())) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); - return NULL; + return nullptr; } if (obj->hasPrivate()) @@ -1842,7 +1842,7 @@ js::CloneObject(JSContext *cx, HandleObject obj, Handle proto, } else { JS_ASSERT(obj->is()); if (!CopySlots(cx, obj, clone)) - return NULL; + return nullptr; } return clone; @@ -1876,7 +1876,7 @@ struct JSObject::TradeGutsReserved { : avals(cx), bvals(cx), newafixed(0), newbfixed(0), newashape(cx), newbshape(cx), - newaslots(NULL), newbslots(NULL) + newaslots(nullptr), newbslots(nullptr) {} ~TradeGutsReserved() @@ -2081,8 +2081,8 @@ JSObject::TradeGuts(JSContext *cx, JSObject *a, JSObject *b, TradeGutsReserved & if (b->hasDynamicSlots()) js_free(b->slots); - void *apriv = a->hasPrivate() ? a->getPrivate() : NULL; - void *bpriv = b->hasPrivate() ? b->getPrivate() : NULL; + void *apriv = a->hasPrivate() ? a->getPrivate() : nullptr; + void *bpriv = b->hasPrivate() ? b->getPrivate() : nullptr; char tmp[sizeof(JSObject)]; js_memcpy(&tmp, a, sizeof tmp); @@ -2110,8 +2110,8 @@ JSObject::TradeGuts(JSContext *cx, JSObject *a, JSObject *b, TradeGutsReserved & b->initPrivate(apriv); /* Make sure the destructor for reserved doesn't free the slots. */ - reserved.newaslots = NULL; - reserved.newbslots = NULL; + reserved.newaslots = nullptr; + reserved.newbslots = nullptr; } #ifdef JSGC_GENERATIONAL @@ -2263,7 +2263,7 @@ js::DefineConstructorAndPrototype(JSContext *cx, HandleObject obj, JSProtoKey ke */ RootedObject proto(cx, NewObjectWithClassProto(cx, clasp, protoProto, obj, SingletonObject)); if (!proto) - return NULL; + return nullptr; /* After this point, control must exit via label bad or out. */ RootedObject ctor(cx); @@ -2358,7 +2358,7 @@ bad: } if (cached) ClearClassObject(obj, key); - return NULL; + return nullptr; } /* @@ -2412,7 +2412,7 @@ js_InitClass(JSContext *cx, HandleObject obj, JSObject *protoProto_, RootedAtom atom(cx, Atomize(cx, clasp->name, strlen(clasp->name))); if (!atom) - return NULL; + return nullptr; /* * All instances of the class will inherit properties from the prototype @@ -2423,14 +2423,14 @@ js_InitClass(JSContext *cx, HandleObject obj, JSObject *protoProto_, * null, default to the Object prototype object. The engine's internal uses * of js_InitClass depend on this nicety. Note that in * js_InitFunctionAndObjectClasses, we specially hack the resolving table - * and then depend on js_GetClassPrototype here leaving protoProto NULL and - * returning true. + * and then depend on js_GetClassPrototype here leaving protoProto nullptr + * and returning true. */ JSProtoKey key = JSCLASS_CACHED_PROTO_KEY(clasp); if (key != JSProto_Null && !protoProto && !js_GetClassPrototype(cx, JSProto_Object, &protoProto)) { - return NULL; + return nullptr; } return DefineConstructorAndPrototype(cx, obj, key, atom, protoProto, clasp, constructor, nargs, @@ -2613,7 +2613,7 @@ JSObject::shrinkSlots(ExclusiveContext *cx, HandleObject obj, uint32_t oldCount, if (newCount == 0) { FreeSlots(cx, obj->slots); - obj->slots = NULL; + obj->slots = nullptr; return; } @@ -2942,7 +2942,7 @@ static JSObject * js_InitNullClass(JSContext *cx, HandleObject obj) { JS_ASSERT(0); - return NULL; + return nullptr; } #define DECLARE_PROTOTYPE_CLASS_INIT(name,code,init) \ @@ -2998,7 +2998,7 @@ js::SetClassAndProto(JSContext *cx, HandleObject obj, RootedObject obj2(cx); for (obj2 = proto.toObjectOrNull(); obj2; ) { if (obj2 == obj) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CYCLIC_VALUE, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CYCLIC_VALUE, js_proto_str); return false; } @@ -3049,7 +3049,7 @@ js_GetClassObject(ExclusiveContext *cxArg, JSObject *obj, JSProtoKey key, Mutabl { RootedObject global(cxArg, &obj->global()); if (!global->is()) { - objp.set(NULL); + objp.set(nullptr); return true; } @@ -3069,11 +3069,11 @@ js_GetClassObject(ExclusiveContext *cxArg, JSObject *obj, JSProtoKey key, Mutabl AutoResolving resolving(cx, global, name); if (resolving.alreadyStarted()) { /* Already caching id in global -- suppress recursion. */ - objp.set(NULL); + objp.set(nullptr); return true; } - RootedObject cobj(cx, NULL); + RootedObject cobj(cx, nullptr); if (ClassInitializerOp init = lazy_prototype_init[key]) { if (!init(cx, global)) return false; @@ -3263,7 +3263,7 @@ PurgeScopeChainHelper(ExclusiveContext *cx, HandleObject objArg, HandleId id) * may gain such properties via eval introducing new vars; see bug 490364. */ if (obj->is()) { - while ((obj = obj->enclosingScope()) != NULL) { + while ((obj = obj->enclosingScope()) != nullptr) { if (!PurgeProtoChain(cx, obj, id)) return false; } @@ -3297,7 +3297,7 @@ js_AddNativeProperty(JSContext *cx, HandleObject obj, HandleId id, * we can lock the shadowed scope. */ if (!PurgeScopeChain(cx, obj, id)) - return NULL; + return nullptr; Shape *shape = JSObject::putProperty(cx, obj, id, getter, setter, slot, attrs, flags, shortid); @@ -3388,7 +3388,7 @@ JSObject::addDataProperty(ExclusiveContext *cx, jsid idArg, uint32_t slot, unsig JS_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER))); RootedObject self(cx, this); RootedId id(cx, idArg); - return addProperty(cx, self, id, NULL, NULL, slot, attrs, 0, 0); + return addProperty(cx, self, id, nullptr, nullptr, slot, attrs, 0, 0); } Shape * @@ -3398,7 +3398,7 @@ JSObject::addDataProperty(ExclusiveContext *cx, HandlePropertyName name, JS_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER))); RootedObject self(cx, this); RootedId id(cx, NameToId(name)); - return addProperty(cx, self, id, NULL, NULL, slot, attrs, 0, 0); + return addProperty(cx, self, id, nullptr, nullptr, slot, attrs, 0, 0); } /* @@ -3595,10 +3595,10 @@ js::DefineNativeProperty(ExclusiveContext *cx, HandleObject obj, HandleId id, Ha if (!shape) return false; } else { - shape = NULL; + shape = nullptr; } } else { - shape = NULL; + shape = nullptr; } } @@ -3657,8 +3657,8 @@ js::DefineNativeProperty(ExclusiveContext *cx, HandleObject obj, HandleId id, Ha * - If the resolve hook finds or defines the sought property, set *objp and * *propp appropriately, set *recursedp = false, and return true. * - * - Otherwise no property was resolved. Set *propp = NULL and *recursedp = false - * and return true. + * - Otherwise no property was resolved. Set *propp = nullptr and + * *recursedp = false and return true. */ static JS_ALWAYS_INLINE bool CallResolveOp(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, @@ -3683,19 +3683,19 @@ CallResolveOp(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, } *recursedp = false; - propp.set(NULL); + propp.set(nullptr); if (clasp->flags & JSCLASS_NEW_RESOLVE) { JSNewResolveOp newresolve = reinterpret_cast(resolve); if (flags == RESOLVE_INFER) flags = js_InferFlags(cx, 0); - RootedObject obj2(cx, NULL); + RootedObject obj2(cx, nullptr); if (!newresolve(cx, obj, id, flags, &obj2)) return false; /* - * We trust the new style resolve hook to set obj2 to NULL when + * We trust the new style resolve hook to set obj2 to nullptr when * the id cannot be resolved. But, when obj2 is not null, we do * not assume that id must exist and do full nativeLookup for * compatibility. @@ -3726,7 +3726,7 @@ CallResolveOp(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, if (!objp->nativeEmpty() && (shape = objp->nativeLookup(cx, id))) propp.set(shape); else - objp.set(NULL); + objp.set(nullptr); return true; } @@ -3775,8 +3775,8 @@ LookupOwnPropertyWithFlagsInline(ExclusiveContext *cx, } if (recursed) { - objp.set(NULL); - propp.set(NULL); + objp.set(nullptr); + propp.set(nullptr); *donep = true; return true; } @@ -3832,8 +3832,8 @@ LookupPropertyWithFlagsInline(ExclusiveContext *cx, current = proto; } - objp.set(NULL); - propp.set(NULL); + objp.set(nullptr); + propp.set(nullptr); return true; } @@ -3911,9 +3911,9 @@ js::LookupName(JSContext *cx, HandlePropertyName name, HandleObject scopeChain, } } - objp.set(NULL); - pobjp.set(NULL); - propp.set(NULL); + objp.set(nullptr); + pobjp.set(nullptr); + propp.set(nullptr); return true; } @@ -3989,8 +3989,8 @@ js::HasOwnProperty(JSContext *cx, LookupGenericOp lookup, if (!LookupOwnPropertyWithFlagsInline(cx, obj, id, 0, objp, propp, &done)) return false; if (!done) { - objp.set(NULL); - propp.set(NULL); + objp.set(nullptr); + propp.set(nullptr); return true; } } @@ -4001,7 +4001,7 @@ js::HasOwnProperty(JSContext *cx, LookupGenericOp lookup, if (objp == obj) return true; - JSObject *outer = NULL; + JSObject *outer = nullptr; if (JSObjectOp op = objp->getClass()->ext.outerObject) { if (!allowGC) return false; @@ -4012,7 +4012,7 @@ js::HasOwnProperty(JSContext *cx, LookupGenericOp lookup, } if (outer != objp) - propp.set(NULL); + propp.set(nullptr); return true; } @@ -4179,7 +4179,7 @@ GetPropertyHelperInline(JSContext *cx, * object foo with no property named 'bar'. */ if (vp.isUndefined()) { - jsbytecode *pc = NULL; + jsbytecode *pc = nullptr; RootedScript script(cx, cx->currentScript(&pc)); if (!pc) return true; @@ -4219,7 +4219,7 @@ GetPropertyHelperInline(JSContext *cx, RootedValue val(cx, IdToValue(id)); if (!js_ReportValueErrorFlags(cx, flags, JSMSG_UNDEFINED_PROP, JSDVG_IGNORE_STACK, val, NullPtr(), - NULL, NULL)) + nullptr, nullptr)) { return false; } @@ -4302,8 +4302,8 @@ LookupPropertyPureInline(JSObject *obj, jsid id, JSObject **objp, Shape **propp) current = proto; } - *objp = NULL; - *propp = NULL; + *objp = nullptr; + *propp = nullptr; return true; } @@ -4454,7 +4454,7 @@ static bool MaybeReportUndeclaredVarAssignment(JSContext *cx, JSString *propname) { { - JSScript *script = cx->currentScript(NULL, JSContext::ALLOW_CROSS_COMPARTMENT); + JSScript *script = cx->currentScript(nullptr, JSContext::ALLOW_CROSS_COMPARTMENT); if (!script) return true; @@ -4469,7 +4469,7 @@ MaybeReportUndeclaredVarAssignment(JSContext *cx, JSString *propname) JS_ReportErrorFlagsAndNumber(cx, (JSREPORT_WARNING | JSREPORT_STRICT | JSREPORT_STRICT_MODE_ERROR), - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_UNDECLARED_VAR, bytes.ptr()); } @@ -4512,7 +4512,7 @@ js::ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname) JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING | JSREPORT_STRICT | JSREPORT_STRICT_MODE_ERROR, - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_UNDECLARED_VAR, bytes.ptr()); } @@ -4522,7 +4522,7 @@ JSObject::reportReadOnly(JSContext *cx, jsid id, unsigned report) RootedValue val(cx, IdToValue(id)); return js_ReportValueErrorFlags(cx, report, JSMSG_READ_ONLY, JSDVG_IGNORE_STACK, val, NullPtr(), - NULL, NULL); + nullptr, nullptr); } bool @@ -4531,7 +4531,7 @@ JSObject::reportNotConfigurable(JSContext *cx, jsid id, unsigned report) RootedValue val(cx, IdToValue(id)); return js_ReportValueErrorFlags(cx, report, JSMSG_CANT_DELETE, JSDVG_IGNORE_STACK, val, NullPtr(), - NULL, NULL); + nullptr, nullptr); } bool @@ -4540,7 +4540,7 @@ JSObject::reportNotExtensible(JSContext *cx, unsigned report) RootedValue val(cx, ObjectValue(*this)); return js_ReportValueErrorFlags(cx, report, JSMSG_OBJECT_NOT_EXTENSIBLE, JSDVG_IGNORE_STACK, val, NullPtr(), - NULL, NULL); + nullptr, nullptr); } bool @@ -4592,7 +4592,7 @@ baseops::SetPropertyHelper(JSContext *cx, HandleObject obj, HandleObject receive } } - shape = NULL; + shape = nullptr; } } else { /* We should never add properties to lexical blocks. */ @@ -4620,7 +4620,7 @@ baseops::SetPropertyHelper(JSContext *cx, HandleObject obj, HandleObject receive if (IsImplicitDenseElement(shape)) { /* ES5 8.12.4 [[Put]] step 2, for a dense data property on pobj. */ if (pobj != obj) - shape = NULL; + shape = nullptr; } else if (shape) { /* ES5 8.12.4 [[Put]] step 2. */ if (shape->isAccessorDescriptor()) { @@ -4683,7 +4683,7 @@ baseops::SetPropertyHelper(JSContext *cx, HandleObject obj, HandleObject receive * Forget we found the proto-property now that we've copied any * needed member values. */ - shape = NULL; + shape = nullptr; } } @@ -4881,7 +4881,7 @@ MaybeCallMethod(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp.setObject(*obj); return true; } - return Invoke(cx, ObjectValue(*obj), vp, 0, NULL, vp); + return Invoke(cx, ObjectValue(*obj), vp, 0, nullptr, vp); } JS_FRIEND_API(bool) @@ -4953,7 +4953,7 @@ js::DefaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValu if (!str) return false; } else { - str = NULL; + str = nullptr; } RootedValue val(cx, ObjectValue(*obj)); @@ -5094,7 +5094,7 @@ js::GetClassPrototypePure(GlobalObject *global, JSProtoKey protoKey) return &v.toObject(); } - return NULL; + return nullptr; } /* @@ -5129,7 +5129,7 @@ js_GetClassPrototype(ExclusiveContext *cx, JSProtoKey protoKey, } } - protop.set(v.get().isObject() ? &v.get().toObject() : NULL); + protop.set(v.get().isObject() ? &v.get().toObject() : nullptr); return true; } @@ -5158,10 +5158,10 @@ js::ToObjectSlow(JSContext *cx, HandleValue val, bool reportScanStack) if (reportScanStack) { js_ReportIsNullOrUndefined(cx, JSDVG_SEARCH_STACK, val, NullPtr()); } else { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CONVERT_TO, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO, val.isNull() ? "null" : "undefined", "object"); } - return NULL; + return nullptr; } return PrimitiveToObject(cx, val); @@ -5181,11 +5181,11 @@ js_GetObjectSlotName(JSTracer *trc, char *buf, size_t bufsize) while (shape && (!shape->hasSlot() || shape->slot() != slot)) shape = shape->previous(); } else { - shape = NULL; + shape = nullptr; } if (!shape) { - const char *slotname = NULL; + const char *slotname = nullptr; if (obj->is()) { #define TEST_SLOT_MATCHES_PROTOTYPE(name,code,init) \ if ((code) == slot) { slotname = js_##name##_str; goto found; } @@ -5216,7 +5216,7 @@ js_ReportGetterOnlyAssignment(JSContext *cx, bool strict) strict ? JSREPORT_ERROR : JSREPORT_WARNING | JSREPORT_STRICT, - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_GETTER_ONLY); } @@ -5224,7 +5224,7 @@ JS_FRIEND_API(bool) js_GetterOnlyPropertyStub(JSContext *cx, HandleObject obj, HandleId id, bool strict, MutableHandleValue vp) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_GETTER_ONLY); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_GETTER_ONLY); return false; } diff --git a/js/src/jsobj.h b/js/src/jsobj.h index 5210d3b2b58b..ffcfadcef108 100644 --- a/js/src/jsobj.h +++ b/js/src/jsobj.h @@ -245,7 +245,7 @@ class JSObject : public js::ObjectImpl js::gc::InitialHeap heap, js::HandleShape shape, js::HandleTypeObject type, - js::HeapSlot *extantSlots = NULL); + js::HeapSlot *extantSlots = nullptr); /* Make an array object with the specified initial state. */ static inline js::ArrayObject *createArray(js::ExclusiveContext *cx, @@ -374,7 +374,7 @@ class JSObject : public js::ObjectImpl static void shrinkSlots(js::ExclusiveContext *cx, js::HandleObject obj, uint32_t oldCount, uint32_t newCount); - bool hasDynamicSlots() const { return slots != NULL; } + bool hasDynamicSlots() const { return slots != nullptr; } protected: static inline bool updateSlotsForSpan(js::ExclusiveContext *cx, @@ -450,7 +450,7 @@ class JSObject : public js::ObjectImpl * * 1. obj->getProto() returns the prototype, but asserts if obj is a proxy. * 2. obj->getTaggedProto() returns a TaggedProto, which can be tested to - * check if the proto is an object, NULL, or lazily computed. + * check if the proto is an object, nullptr, or lazily computed. * 3. JSObject::getProto(cx, obj, &proto) computes the proto of an object. * If obj is a proxy and the proto is lazy, this code may allocate or * GC in order to compute the proto. Currently, it will not run JS code. @@ -498,10 +498,10 @@ class JSObject : public js::ObjectImpl /* * Parents and scope chains. * - * All script-accessible objects with a NULL parent are global objects, - * and all global objects have a NULL parent. Some builtin objects which - * are not script-accessible also have a NULL parent, such as parser - * created functions for non-compileAndGo scripts. + * All script-accessible objects with a nullptr parent are global objects, + * and all global objects have a nullptr parent. Some builtin objects + * which are not script-accessible also have a nullptr parent, such as + * parser created functions for non-compileAndGo scripts. * * Except for the non-script-accessible builtins, the global with which an * object is associated can be reached by following parent links to that @@ -1249,7 +1249,7 @@ js_IdentifyClassPrototype(JSObject *obj); */ bool js_FindClassObject(js::ExclusiveContext *cx, JSProtoKey protoKey, js::MutableHandleValue vp, - const js::Class *clasp = NULL); + const js::Class *clasp = nullptr); /* * Find or create a property named by id in obj's scope, with the given getter @@ -1335,7 +1335,7 @@ const unsigned DNP_UNQUALIFIED = 2; /* Unqualified property set. Only used i const unsigned DNP_SKIP_TYPE = 4; /* Don't update type information */ /* - * Return successfully added or changed shape or NULL on error. + * Return successfully added or changed shape or nullptr on error. */ extern bool DefineNativeProperty(ExclusiveContext *cx, HandleObject obj, HandleId id, HandleValue value, @@ -1517,7 +1517,7 @@ js_InferFlags(JSContext *cx, unsigned defaultFlags); */ extern bool js_GetClassPrototype(js::ExclusiveContext *cx, JSProtoKey protoKey, js::MutableHandleObject protop, - const js::Class *clasp = NULL); + const js::Class *clasp = nullptr); namespace js { diff --git a/js/src/jsobjinlines.h b/js/src/jsobjinlines.h index 682e8d15e3d4..13643cea805c 100644 --- a/js/src/jsobjinlines.h +++ b/js/src/jsobjinlines.h @@ -351,7 +351,7 @@ JSObject::clearType(JSContext *cx, js::HandleObject obj) JS_ASSERT(!obj->hasSingletonType()); JS_ASSERT(cx->compartment() == obj->compartment()); - js::types::TypeObject *type = cx->getNewType(obj->getClass(), NULL); + js::types::TypeObject *type = cx->getNewType(obj->getClass(), nullptr); if (!type) return false; @@ -389,7 +389,7 @@ inline bool JSObject::isVarObj() /* static */ inline JSObject * JSObject::create(js::ExclusiveContext *cx, js::gc::AllocKind kind, js::gc::InitialHeap heap, js::HandleShape shape, js::HandleTypeObject type, - js::HeapSlot *extantSlots /* = NULL */) + js::HeapSlot *extantSlots /* = nullptr */) { /* * Callers must use dynamicSlotsCount to size the initial slot array of the @@ -410,7 +410,7 @@ JSObject::create(js::ExclusiveContext *cx, js::gc::AllocKind kind, js::gc::Initi if (nDynamicSlots) { slots = cx->pod_malloc(nDynamicSlots); if (!slots) - return NULL; + return nullptr; js::Debug_SetSlotRangeToCrashOnTouch(slots, nDynamicSlots); } } @@ -418,7 +418,7 @@ JSObject::create(js::ExclusiveContext *cx, js::gc::AllocKind kind, js::gc::Initi JSObject *obj = js_NewGCObject(cx, kind, heap); if (!obj) { js_free(slots); - return NULL; + return nullptr; } #ifdef JSGC_GENERATIONAL @@ -433,7 +433,7 @@ JSObject::create(js::ExclusiveContext *cx, js::gc::AllocKind kind, js::gc::Initi const js::Class *clasp = type->clasp; if (clasp->hasPrivate()) - obj->privateRef(shape->numFixedSlots()) = NULL; + obj->privateRef(shape->numFixedSlots()) = nullptr; size_t span = shape->slotSpan(); if (span && clasp != &js::ArrayBufferObject::class_) @@ -469,11 +469,11 @@ JSObject::createArray(js::ExclusiveContext *cx, js::gc::AllocKind kind, js::gc:: JSObject *obj = js_NewGCObject(cx, kind, heap); if (!obj) - return NULL; + return nullptr; obj->shape_.init(shape); obj->type_.init(type); - obj->slots = NULL; + obj->slots = nullptr; obj->setFixedElements(); new (obj->getElementsHeader()) js::ObjectElements(capacity, length); @@ -729,7 +729,7 @@ class AutoPropDescArrayRooter : private AutoGCRooter PropDesc *append() { if (!descriptors.append(PropDesc())) - return NULL; + return nullptr; return &descriptors.back(); } @@ -838,7 +838,7 @@ inline JSObject * NewBuiltinClassInstance(ExclusiveContext *cx, const Class *clasp, gc::AllocKind allocKind, NewObjectKind newKind = GenericObject) { - return NewObjectWithClassProto(cx, clasp, NULL, NULL, allocKind, newKind); + return NewObjectWithClassProto(cx, clasp, nullptr, nullptr, allocKind, newKind); } inline JSObject * @@ -865,14 +865,14 @@ CopyInitializerObject(JSContext *cx, HandleObject baseobj, NewObjectKind newKind RootedObject obj(cx); obj = NewBuiltinClassInstance(cx, &JSObject::class_, allocKind, newKind); if (!obj) - return NULL; + return nullptr; RootedObject metadata(cx, obj->getMetadata()); RootedShape lastProp(cx, baseobj->lastProperty()); if (!JSObject::setLastProperty(cx, obj, lastProp)) - return NULL; + return nullptr; if (metadata && !JSObject::setMetadata(cx, obj, metadata)) - return NULL; + return nullptr; return obj; } @@ -975,7 +975,7 @@ DefineConstructorAndPrototype(JSContext *cx, HandleObject obj, JSProtoKey key, H Native constructor, unsigned nargs, const JSPropertySpec *ps, const JSFunctionSpec *fs, const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs, - JSObject **ctorp = NULL, + JSObject **ctorp = nullptr, gc::AllocKind ctorKind = JSFunction::FinalizeKind); static JS_ALWAYS_INLINE bool @@ -1041,7 +1041,7 @@ js_InitClass(JSContext *cx, js::HandleObject obj, JSObject *parent_proto, const js::Class *clasp, JSNative constructor, unsigned nargs, const JSPropertySpec *ps, const JSFunctionSpec *fs, const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs, - JSObject **ctorp = NULL, + JSObject **ctorp = nullptr, js::gc::AllocKind ctorKind = JSFunction::FinalizeKind); #endif /* jsobjinlines_h */ diff --git a/js/src/json.cpp b/js/src/json.cpp index c27f4270e0fb..1a4692bfc8ff 100644 --- a/js/src/json.cpp +++ b/js/src/json.cpp @@ -290,7 +290,7 @@ JO(JSContext *cx, HandleObject obj, StringifyContext *scx) if (!detect.init()) return false; if (detect.foundCycle()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CYCLIC_VALUE, js_object_str); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CYCLIC_VALUE, js_object_str); return false; } @@ -380,7 +380,7 @@ JA(JSContext *cx, HandleObject obj, StringifyContext *scx) if (!detect.init()) return false; if (detect.foundCycle()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CYCLIC_VALUE, js_object_str); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CYCLIC_VALUE, js_object_str); return false; } @@ -598,7 +598,7 @@ js_Stringify(JSContext *cx, MutableHandleValue vp, JSObject *replacer_, Value sp } } } else { - replacer = NULL; + replacer = nullptr; } } @@ -829,7 +829,7 @@ json_stringify(JSContext *cx, unsigned argc, Value *vp) { RootedObject replacer(cx, (argc >= 2 && vp[3].isObject()) ? &vp[3].toObject() - : NULL); + : nullptr); RootedValue value(cx, (argc >= 1) ? vp[2] : UndefinedValue()); RootedValue space(cx, (argc >= 3) ? vp[4] : UndefinedValue()); @@ -872,18 +872,19 @@ js_InitJSONClass(JSContext *cx, HandleObject obj) * called from PreprocessValue above. */ if (!global->getOrCreateBooleanPrototype(cx)) - return NULL; + return nullptr; - RootedObject JSON(cx, NewObjectWithClassProto(cx, &JSONClass, NULL, global, SingletonObject)); + RootedObject JSON(cx, NewObjectWithClassProto(cx, &JSONClass, nullptr, + global, SingletonObject)); if (!JSON) - return NULL; + return nullptr; if (!JS_DefineProperty(cx, global, js_JSON_str, OBJECT_TO_JSVAL(JSON), JS_PropertyStub, JS_StrictPropertyStub, 0)) - return NULL; + return nullptr; if (!JS_DefineFunctions(cx, JSON, json_static_methods)) - return NULL; + return nullptr; MarkStandardClassInitializedNoProto(global, &JSONClass); diff --git a/js/src/jsonparser.cpp b/js/src/jsonparser.cpp index 5560d1a39ca1..20c80d00c6b0 100644 --- a/js/src/jsonparser.cpp +++ b/js/src/jsonparser.cpp @@ -60,7 +60,7 @@ void JSONParser::error(const char *msg) { if (errorHandling == RaiseError) - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_JSON_BAD_PARSE, msg); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_JSON_BAD_PARSE, msg); } bool @@ -540,7 +540,7 @@ JSONParser::createFinishedObject(PropertyVector &properties) gc::AllocKind allocKind = gc::GetGCObjectKind(properties.length()); RootedObject obj(cx, NewBuiltinClassInstance(cx, &JSObject::class_, allocKind)); if (!obj) - return NULL; + return nullptr; RootedId propid(cx); RootedValue value(cx); @@ -552,7 +552,7 @@ JSONParser::createFinishedObject(PropertyVector &properties) JS_PropertyStub, JS_StrictPropertyStub, JSPROP_ENUMERATE, 0, 0)) { - return NULL; + return nullptr; } } diff --git a/js/src/jsopcode.cpp b/js/src/jsopcode.cpp index 6c4353b1278c..5eab43d9227a 100644 --- a/js/src/jsopcode.cpp +++ b/js/src/jsopcode.cpp @@ -325,8 +325,9 @@ js_DumpPCCounts(JSContext *cx, HandleScript script, js::Sprinter *sp) #ifdef DEBUG /* - * If pc != NULL, include a prefix indicating whether the PC is at the current line. - * If showAll is true, include the source note type and the entry stack depth. + * If pc != nullptr, include a prefix indicating whether the PC is at the + * current line. If showAll is true, include the source note type and the + * entry stack depth. */ JS_FRIEND_API(bool) js_DisassembleAtPC(JSContext *cx, JSScript *scriptArg, bool lines, @@ -340,7 +341,7 @@ js_DisassembleAtPC(JSContext *cx, JSScript *scriptArg, bool lines, if (showAll) Sprint(sp, "%s:%u\n", script->filename(), script->lineno); - if (pc != NULL) + if (pc != nullptr) sp->put(" "); if (showAll) sp->put("sn stack "); @@ -349,7 +350,7 @@ js_DisassembleAtPC(JSContext *cx, JSScript *scriptArg, bool lines, sp->put("line"); sp->put(" op\n"); - if (pc != NULL) + if (pc != nullptr) sp->put(" "); if (showAll) sp->put("-- ----- "); @@ -363,7 +364,7 @@ js_DisassembleAtPC(JSContext *cx, JSScript *scriptArg, bool lines, while (next < end) { if (next == script->main()) sp->put("main:\n"); - if (pc != NULL) { + if (pc != nullptr) { if (pc == next) sp->put("--> "); else @@ -399,7 +400,7 @@ js_DisassembleAtPC(JSContext *cx, JSScript *scriptArg, bool lines, bool js_Disassemble(JSContext *cx, HandleScript script, bool lines, Sprinter *sp) { - return js_DisassembleAtPC(cx, script, lines, NULL, false, sp); + return js_DisassembleAtPC(cx, script, lines, nullptr, false, sp); } JS_FRIEND_API(bool) @@ -458,7 +459,7 @@ ToDisassemblySource(JSContext *cx, jsval v, JSAutoByteString *bytes) char *nbytes = QuoteString(&sprinter, JSVAL_TO_STRING(v), '"'); if (!nbytes) return false; - nbytes = JS_sprintf_append(NULL, "%s", nbytes); + nbytes = JS_sprintf_append(nullptr, "%s", nbytes); if (!nbytes) return false; bytes->initBytes(nbytes); @@ -466,7 +467,7 @@ ToDisassemblySource(JSContext *cx, jsval v, JSAutoByteString *bytes) } if (cx->runtime()->isHeapBusy() || cx->runtime()->noGCOrAllocationCheck) { - char *source = JS_sprintf_append(NULL, ""); + char *source = JS_sprintf_append(nullptr, ""); if (!source) return false; bytes->initBytes(source); @@ -476,7 +477,7 @@ ToDisassemblySource(JSContext *cx, jsval v, JSAutoByteString *bytes) if (!JSVAL_IS_PRIMITIVE(v)) { JSObject *obj = JSVAL_TO_OBJECT(v); if (obj->is()) { - char *source = JS_sprintf_append(NULL, "depth %d {", + char *source = JS_sprintf_append(nullptr, "depth %d {", obj->as().stackDepth()); if (!source) return false; @@ -536,7 +537,7 @@ js_Disassemble1(JSContext *cx, HandleScript script, jsbytecode *pc, char numBuf1[12], numBuf2[12]; JS_snprintf(numBuf1, sizeof numBuf1, "%d", op); JS_snprintf(numBuf2, sizeof numBuf2, "%d", JSOP_LIMIT); - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BYTECODE_TOO_BIG, numBuf1, numBuf2); return 0; } @@ -703,7 +704,7 @@ js_Disassemble1(JSContext *cx, HandleScript script, jsbytecode *pc, default: { char numBuf[12]; JS_snprintf(numBuf, sizeof numBuf, "%lx", (unsigned long) cs->format); - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNKNOWN_FORMAT, numBuf); return 0; } @@ -738,7 +739,7 @@ Sprinter::Sprinter(ExclusiveContext *cx) #ifdef DEBUG initialized(false), #endif - base(NULL), size(0), offset(0), reportedOOM(false) + base(nullptr), size(0), offset(0), reportedOOM(false) { } Sprinter::~Sprinter() @@ -809,7 +810,7 @@ Sprinter::reserve(size_t len) while (len + 1 > size - offset) { /* Include trailing \0 */ if (!realloc_(size * 2)) - return NULL; + return nullptr; } char *sb = base + offset; @@ -868,7 +869,7 @@ Sprinter::putString(JSString *s) char *buffer = reserve(size); if (!buffer) return -1; - DeflateStringToBuffer(NULL, chars, length, buffer, &size); + DeflateStringToBuffer(nullptr, chars, length, buffer, &size); buffer[size] = 0; return oldOffset; @@ -958,11 +959,11 @@ QuoteString(Sprinter *sp, JSString *str, uint32_t quote) jschar qc = (jschar) quote; ptrdiff_t offset = sp->getOffset(); if (qc && Sprint(sp, "%c", (char)qc) < 0) - return NULL; + return nullptr; const jschar *s = str->getChars(sp->context); if (!s) - return NULL; + return nullptr; const jschar *z = s + str->length(); /* Loop control variables: z points at end of string sentinel. */ @@ -980,7 +981,7 @@ QuoteString(Sprinter *sp, JSString *str, uint32_t quote) ptrdiff_t base = sp->getOffset(); char *bp = sp->reserve(len); if (!bp) - return NULL; + return nullptr; for (ptrdiff_t i = 0; i < len; ++i) (*sp)[base + i] = (char) *s++; @@ -993,7 +994,7 @@ QuoteString(Sprinter *sp, JSString *str, uint32_t quote) /* Use js_EscapeMap, \u, or \x only if necessary. */ bool ok; const char *e; - if (!(c >> 8) && c != 0 && (e = strchr(js_EscapeMap, (int)c)) != NULL) { + if (!(c >> 8) && c != 0 && (e = strchr(js_EscapeMap, (int)c)) != nullptr) { ok = dontEscape ? Sprint(sp, "%c", (char)c) >= 0 : Sprint(sp, "\\%c", e[1]) >= 0; @@ -1006,19 +1007,19 @@ QuoteString(Sprinter *sp, JSString *str, uint32_t quote) ok = Sprint(sp, (qc && !(c >> 8)) ? "\\x%02X" : "\\u%04X", c) >= 0; } if (!ok) - return NULL; + return nullptr; } /* Sprint the closing quote and return the quoted string. */ if (qc && Sprint(sp, "%c", (char)qc) < 0) - return NULL; + return nullptr; /* * If we haven't Sprint'd anything yet, Sprint an empty string so that * the return below gives a valid result. */ if (offset == sp->getOffset() && Sprint(sp, "") < 0) - return NULL; + return nullptr; return sp->stringAt(offset); } @@ -1028,10 +1029,10 @@ js_QuoteString(ExclusiveContext *cx, JSString *str, jschar quote) { Sprinter sprinter(cx); if (!sprinter.init()) - return NULL; + return nullptr; char *bytes = QuoteString(&sprinter, str, quote); if (!bytes) - return NULL; + return nullptr; return js_NewStringCopyZ(cx, bytes); } @@ -1052,7 +1053,7 @@ GetBlockChainAtPC(JSContext *cx, JSScript *script, jsbytecode *pc) JS_ASSERT(pc >= start && pc < script->code + script->length); - JSObject *blockChain = NULL; + JSObject *blockChain = nullptr; for (jsbytecode *p = start; p < pc; p += GetBytecodeLength(p)) { JSOp op = JSOp(*p); @@ -1098,7 +1099,7 @@ class PCStack int depth_; public: - PCStack() : stack(NULL), depth_(0) {} + PCStack() : stack(nullptr), depth_(0) {} ~PCStack(); bool init(JSContext *cx, JSScript *script, jsbytecode *pc); int depth() const { return depth_; } @@ -1179,7 +1180,7 @@ struct ExpressionDecompiler : cx(cx), script(cx, script), fun(cx, fun), - localNames(NULL), + localNames(nullptr), sprinter(cx) {} ~ExpressionDecompiler(); @@ -1385,7 +1386,7 @@ ExpressionDecompiler::findLetVar(jsbytecode *pc, unsigned depth) if (script->hasObjects()) { JSObject *chain = GetBlockChainAtPC(cx, script, pc); if (!chain) - return NULL; + return nullptr; JS_ASSERT(chain->is()); do { BlockObject &block = chain->as(); @@ -1401,7 +1402,7 @@ ExpressionDecompiler::findLetVar(jsbytecode *pc, unsigned depth) chain = chain->getParent(); } while (chain && chain->is()); } - return NULL; + return nullptr; } JSAtom * @@ -1454,7 +1455,7 @@ FindStartPC(JSContext *cx, ScriptFrameIter &iter, int spindex, int skipStackHits if (iter.isIon()) return true; - *valuepc = NULL; + *valuepc = nullptr; PCStack pcstack; if (!pcstack.init(cx, iter.script(), current)) @@ -1497,7 +1498,7 @@ DecompileExpressionFromStack(JSContext *cx, int spindex, int skipStackHits, Hand spindex == JSDVG_IGNORE_STACK || spindex == JSDVG_SEARCH_STACK); - *res = NULL; + *res = nullptr; #ifdef JS_MORE_DETERMINISTIC /* @@ -1518,7 +1519,7 @@ DecompileExpressionFromStack(JSContext *cx, int spindex, int skipStackHits, Hand jsbytecode *valuepc = frameIter.pc(); RootedFunction fun(cx, frameIter.isFunctionFrame() ? frameIter.callee() - : NULL); + : nullptr); JS_ASSERT(script->code <= valuepc && valuepc < script->code + script->length); @@ -1548,7 +1549,7 @@ js::DecompileValueGenerator(JSContext *cx, int spindex, HandleValue v, { char *result; if (!DecompileExpressionFromStack(cx, spindex, skipStackHits, v, &result)) - return NULL; + return nullptr; if (result) { if (strcmp(result, "(intermediate value)")) return result; @@ -1560,12 +1561,12 @@ js::DecompileValueGenerator(JSContext *cx, int spindex, HandleValue v, return JS_strdup(cx, js_undefined_str); // Prevent users from seeing "(void 0)" fallback = ValueToSource(cx, v); if (!fallback) - return NULL; + return nullptr; } Rooted linear(cx, fallback->ensureLinear(cx)); if (!linear) - return NULL; + return nullptr; TwoByteChars tbchars(linear->chars(), linear->length()); return LossyTwoByteCharsToNewLatin1CharsZ(cx, tbchars).c_str(); } @@ -1575,7 +1576,7 @@ DecompileArgumentFromStack(JSContext *cx, int formalIndex, char **res) { JS_ASSERT(formalIndex >= 0); - *res = NULL; + *res = nullptr; #ifdef JS_MORE_DETERMINISTIC /* See note in DecompileExpressionFromStack. */ @@ -1602,7 +1603,7 @@ DecompileArgumentFromStack(JSContext *cx, int formalIndex, char **res) jsbytecode *current = frameIter.pc(); RootedFunction fun(cx, frameIter.isFunctionFrame() ? frameIter.callee() - : NULL); + : nullptr); JS_ASSERT(script->code <= current && current < script->code + script->length); @@ -1637,7 +1638,7 @@ js::DecompileArgument(JSContext *cx, int formalIndex, HandleValue v) { char *result; if (!DecompileArgumentFromStack(cx, formalIndex, &result)) - return NULL; + return nullptr; if (result) { if (strcmp(result, "(intermediate value)")) return result; @@ -1648,18 +1649,18 @@ js::DecompileArgument(JSContext *cx, int formalIndex, HandleValue v) return JS_strdup(cx, js_undefined_str); // Prevent users from seeing "(void 0)" RootedString fallback(cx, ValueToSource(cx, v)); if (!fallback) - return NULL; + return nullptr; Rooted linear(cx, fallback->ensureLinear(cx)); if (!linear) - return NULL; + return nullptr; return LossyTwoByteCharsToNewLatin1CharsZ(cx, linear->range()).c_str(); } unsigned js_ReconstructStackDepth(JSContext *cx, JSScript *script, jsbytecode *pc) { - return ReconstructPCStack(cx, script, pc, NULL); + return ReconstructPCStack(cx, script, pc, nullptr); } #define LOCAL_ASSERT_CUSTOM(expr, BAD_EXIT) \ @@ -2086,8 +2087,8 @@ js::GetPCCountScriptSummary(JSContext *cx, size_t index) JSRuntime *rt = cx->runtime(); if (!rt->scriptAndCountsVector || index >= rt->scriptAndCountsVector->length()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BUFFER_TOO_SMALL); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BUFFER_TOO_SMALL); + return nullptr; } const ScriptAndCounts &sac = (*rt->scriptAndCountsVector)[index]; @@ -2105,7 +2106,7 @@ js::GetPCCountScriptSummary(JSContext *cx, size_t index) AppendJSONProperty(buf, "file", NO_COMMA); JSString *str = JS_NewStringCopyZ(cx, script->filename()); if (!str || !(str = StringToSource(cx, str))) - return NULL; + return nullptr; buf.append(str); AppendJSONProperty(buf, "line"); @@ -2116,7 +2117,7 @@ js::GetPCCountScriptSummary(JSContext *cx, size_t index) if (atom) { AppendJSONProperty(buf, "name"); if (!(str = StringToSource(cx, atom))) - return NULL; + return nullptr; buf.append(str); } } @@ -2188,7 +2189,7 @@ js::GetPCCountScriptSummary(JSContext *cx, size_t index) buf.append('}'); if (cx->isExceptionPending()) - return NULL; + return nullptr; return buf.finishString(); } @@ -2201,7 +2202,7 @@ GetPCCountJSON(JSContext *cx, const ScriptAndCounts &sac, StringBuffer &buf) buf.append('{'); AppendJSONProperty(buf, "text", NO_COMMA); - JSString *str = JS_DecompileScript(cx, script, NULL, 0); + JSString *str = JS_DecompileScript(cx, script, nullptr, 0); if (!str || !(str = StringToSource(cx, str))) return false; @@ -2349,8 +2350,8 @@ js::GetPCCountScriptContents(JSContext *cx, size_t index) JSRuntime *rt = cx->runtime(); if (!rt->scriptAndCountsVector || index >= rt->scriptAndCountsVector->length()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BUFFER_TOO_SMALL); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BUFFER_TOO_SMALL); + return nullptr; } const ScriptAndCounts &sac = (*rt->scriptAndCountsVector)[index]; @@ -2364,7 +2365,7 @@ js::GetPCCountScriptContents(JSContext *cx, size_t index) { AutoCompartment ac(cx, &script->global()); if (!GetPCCountJSON(cx, sac, buf)) - return NULL; + return nullptr; } return buf.finishString(); diff --git a/js/src/jsopcode.h b/js/src/jsopcode.h index 235313846902..1b5acfc52a95 100644 --- a/js/src/jsopcode.h +++ b/js/src/jsopcode.h @@ -453,7 +453,7 @@ class Sprinter char &operator[](size_t off); /* - * Attempt to reserve len + 1 space (for a trailing NULL byte). If the + * Attempt to reserve len + 1 space (for a trailing nullptr byte). If the * attempt succeeds, return a pointer to the start of that space and adjust the * internal content. The caller *must* completely fill this space on success. */ diff --git a/js/src/jsprf.cpp b/js/src/jsprf.cpp index 92cf56f3394b..9f7e35cad6f2 100644 --- a/js/src/jsprf.cpp +++ b/js/src/jsprf.cpp @@ -369,7 +369,7 @@ cvt_ws(SprintfState *ss, const jschar *ws, int width, int prec, int flags) { int result; /* - * Supply NULL as the JSContext; errors are not reported, + * Supply nullptr as the JSContext; errors are not reported, * and malloc() is used to allocate the buffer buffer. */ if (ws) { @@ -383,7 +383,7 @@ cvt_ws(SprintfState *ss, const jschar *ws, int width, int prec, int flags) result = cvt_s(ss, latin1, width, prec, flags); js_free(latin1); } else { - result = cvt_s(ss, NULL, width, prec, flags); + result = cvt_s(ss, nullptr, width, prec, flags); } return result; } @@ -422,13 +422,13 @@ static struct NumArgState* BuildArgArray( const char *fmt, va_list ap, int* rv, if( c == '$' ){ /* numbered argument csae */ if( i > 0 ){ *rv = -1; - return NULL; + return nullptr; } number++; } else { /* non-numbered argument case */ if( number > 0 ){ *rv = -1; - return NULL; + return nullptr; } i = 1; } @@ -440,7 +440,7 @@ static struct NumArgState* BuildArgArray( const char *fmt, va_list ap, int* rv, } if( number == 0 ){ - return NULL; + return nullptr; } @@ -448,7 +448,7 @@ static struct NumArgState* BuildArgArray( const char *fmt, va_list ap, int* rv, nas = (struct NumArgState*)malloc( number * sizeof( struct NumArgState ) ); if( !nas ){ *rv = -1; - return NULL; + return nullptr; } } else { nas = nasArray; @@ -600,7 +600,7 @@ static struct NumArgState* BuildArgArray( const char *fmt, va_list ap, int* rv, if( *rv < 0 ){ if( nas != nasArray ) js_free( nas ); - return NULL; + return nullptr; } cn = 0; @@ -638,7 +638,7 @@ static struct NumArgState* BuildArgArray( const char *fmt, va_list ap, int* rv, if( nas != nasArray ) js_free( nas ); *rv = -1; - return NULL; + return nullptr; } cn++; @@ -671,10 +671,10 @@ static int dosprintf(SprintfState *ss, const char *fmt, va_list ap) static const char HEX[] = "0123456789ABCDEF"; const char *hexp; int rv, i; - struct NumArgState *nas = NULL; + struct NumArgState *nas = nullptr; struct NumArgState nasArray[ NAS_DEFAULT_NUM ]; char pattern[20]; - const char *dolPt = NULL; /* in "%4$.2f", dolPt will poiont to . */ + const char *dolPt = nullptr; /* in "%4$.2f", dolPt will poiont to . */ /* ** build an argument array, IF the fmt is numbered argument @@ -713,7 +713,7 @@ static int dosprintf(SprintfState *ss, const char *fmt, va_list ap) continue; } - if( nas != NULL ){ + if( nas != nullptr ){ /* the fmt contains the Numbered Arguments feature */ i = 0; while( c && c != '$' ){ /* should imporve error check later */ @@ -885,7 +885,7 @@ static int dosprintf(SprintfState *ss, const char *fmt, va_list ap) case 'f': case 'g': u.d = va_arg(ap, double); - if( nas != NULL ){ + if( nas != nullptr ){ i = fmt - dolPt; if( i < (int)sizeof( pattern ) ){ pattern[0] = '%'; diff --git a/js/src/jsprf.h b/js/src/jsprf.h index fe69066a311a..b235f0b4fb4f 100644 --- a/js/src/jsprf.h +++ b/js/src/jsprf.h @@ -38,7 +38,7 @@ extern JS_PUBLIC_API(uint32_t) JS_snprintf(char *out, uint32_t outlen, const cha /* ** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, NULL on failure. Call "JS_smprintf_free" to release +** 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, ...); @@ -51,9 +51,9 @@ 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 NULL, JS_sprintf_append +** 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 NULL if there is a malloc failure. +** 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, ...); diff --git a/js/src/jspropertytree.cpp b/js/src/jspropertytree.cpp index ed1beaac66bc..126a77cfb640 100644 --- a/js/src/jspropertytree.cpp +++ b/js/src/jspropertytree.cpp @@ -45,7 +45,7 @@ HashChildren(Shape *kid1, Shape *kid2) KidsHash *hash = js_new(); if (!hash || !hash->init(2)) { js_delete(hash); - return NULL; + return nullptr; } JS_ALWAYS_TRUE(hash->putNew(kid1, kid1)); @@ -105,7 +105,7 @@ Shape::removeChild(Shape *child) if (kidp->isShape()) { JS_ASSERT(kidp->toShape() == child); kidp->setNull(); - child->parent = NULL; + child->parent = nullptr; return; } @@ -113,7 +113,7 @@ Shape::removeChild(Shape *child) JS_ASSERT(hash->count() >= 2); /* otherwise kidp->isShape() should be true */ hash->remove(child); - child->parent = NULL; + child->parent = nullptr; if (hash->count() == 1) { /* Convert from HASH form back to SHAPE form. */ @@ -129,7 +129,7 @@ Shape * PropertyTree::getChild(ExclusiveContext *cx, Shape *parent_, uint32_t nfixed, const StackShape &child) { { - Shape *shape = NULL; + Shape *shape = nullptr; JS_ASSERT(parent_); @@ -173,7 +173,7 @@ PropertyTree::getChild(ExclusiveContext *cx, Shape *parent_, uint32_t nfixed, co */ JS_ASSERT(parent_->isMarked()); parent_->removeChild(shape); - shape = NULL; + shape = nullptr; } } #endif @@ -187,12 +187,12 @@ PropertyTree::getChild(ExclusiveContext *cx, Shape *parent_, uint32_t nfixed, co Shape *shape = newShape(cx); if (!shape) - return NULL; + return nullptr; new (shape) Shape(child, nfixed); if (!insertChild(cx, parent, shape)) - return NULL; + return nullptr; return shape; } @@ -269,7 +269,7 @@ Shape::dump(JSContext *cx, FILE *fp) const RootedValue v(cx, IdToValue(propid)); JSString *s = ToStringSlow(cx, v); fputs("object ", fp); - str = s ? s->ensureLinear(cx) : NULL; + str = s ? s->ensureLinear(cx) : nullptr; } if (!str) fputs("", fp); @@ -344,7 +344,7 @@ void js::PropertyTree::dumpShapes(JSRuntime *rt) { static bool init = false; - static FILE *dumpfp = NULL; + static FILE *dumpfp = nullptr; if (!init) { init = true; const char *name = getenv("JS_DUMP_SHAPES_FILE"); diff --git a/js/src/jsproxy.cpp b/js/src/jsproxy.cpp index e66a6f8242b8..801ef5ebd1bb 100644 --- a/js/src/jsproxy.cpp +++ b/js/src/jsproxy.cpp @@ -34,12 +34,12 @@ js::AutoEnterPolicy::reportErrorIfExceptionIsNotPending(JSContext *cx, jsid id) return; if (JSID_IS_VOID(id)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_OBJECT_ACCESS_DENIED); } else { JSString *str = IdToString(cx, id); - const jschar *prop = str ? str->getCharsZ(cx) : NULL; - JS_ReportErrorNumberUC(cx, js_GetErrorMessage, NULL, + const jschar *prop = str ? str->getCharsZ(cx) : nullptr; + JS_ReportErrorNumberUC(cx, js_GetErrorMessage, nullptr, JSMSG_PROPERTY_ACCESS_DENIED, prop); } } @@ -137,7 +137,8 @@ BaseProxyHandler::get(JSContext *cx, HandleObject proxy, HandleObject receiver, return true; } if (desc.hasGetterObject()) - return InvokeGetterOrSetter(cx, receiver, ObjectValue(*desc.getterObject()), 0, NULL, vp); + return InvokeGetterOrSetter(cx, receiver, ObjectValue(*desc.getterObject()), + 0, nullptr, vp); if (!desc.isShared()) vp.set(desc.value()); else @@ -238,8 +239,8 @@ BaseProxyHandler::set(JSContext *cx, HandleObject proxy, HandleObject receiver, desc.value().set(vp.get()); desc.setAttributes(JSPROP_ENUMERATE); desc.setShortId(0); - desc.setGetter(NULL); - desc.setSetter(NULL); // Pick up the class getter/setter. + desc.setGetter(nullptr); + desc.setSetter(nullptr); // Pick up the class getter/setter. return defineProperty(cx, receiver, id, &desc); } @@ -311,7 +312,7 @@ BaseProxyHandler::fun_toString(JSContext *cx, HandleObject proxy, unsigned inden if (proxy->isCallable()) return JS_NewStringCopyZ(cx, "function () {\n [native code]\n}"); ReportIsNotFunction(cx, ObjectValue(*proxy)); - return NULL; + return nullptr; } bool @@ -359,7 +360,7 @@ BaseProxyHandler::finalize(JSFreeOp *fop, JSObject *proxy) JSObject * BaseProxyHandler::weakmapKeyDelegate(JSObject *proxy) { - return NULL; + return nullptr; } bool @@ -393,7 +394,7 @@ GetOwnPropertyDescriptor(JSContext *cx, HandleObject obj, HandleId id, unsigned if (!JS_GetPropertyDescriptorById(cx, obj, id, flags, desc)) return false; if (desc.object() != obj) - desc.object().set(NULL); + desc.object().set(nullptr); return true; } @@ -686,7 +687,7 @@ ParsePropertyDescriptorObject(JSContext *cx, HandleObject obj, const Value &v, static bool IndicatePropertyNotFound(MutableHandle desc) { - desc.object().set(NULL); + desc.object().set(nullptr); return true; } @@ -812,7 +813,7 @@ bool ScriptedIndirectProxyHandler::preventExtensions(JSContext *cx, HandleObject proxy) { // See above. - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CHANGE_EXTENSIBILITY); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CHANGE_EXTENSIBILITY); return false; } @@ -883,7 +884,7 @@ ScriptedIndirectProxyHandler::getOwnPropertyNames(JSContext *cx, HandleObject pr RootedObject handler(cx, GetIndirectProxyHandlerObject(proxy)); RootedValue fval(cx), value(cx); return GetFundamentalTrap(cx, handler, cx->names().getOwnPropertyNames, &fval) && - Trap(cx, handler, fval, 0, NULL, &value) && + Trap(cx, handler, fval, 0, nullptr, &value) && ArrayToIdVector(cx, value, props); } @@ -903,7 +904,7 @@ ScriptedIndirectProxyHandler::enumerate(JSContext *cx, HandleObject proxy, AutoI RootedObject handler(cx, GetIndirectProxyHandlerObject(proxy)); RootedValue fval(cx), value(cx); return GetFundamentalTrap(cx, handler, cx->names().enumerate, &fval) && - Trap(cx, handler, fval, 0, NULL, &value) && + Trap(cx, handler, fval, 0, nullptr, &value) && ArrayToIdVector(cx, value, props); } @@ -982,7 +983,7 @@ ScriptedIndirectProxyHandler::keys(JSContext *cx, HandleObject proxy, AutoIdVect return false; if (!js_IsCallable(value)) return BaseProxyHandler::keys(cx, proxy, props); - return Trap(cx, handler, value, 0, NULL, &value) && + return Trap(cx, handler, value, 0, nullptr, &value) && ArrayToIdVector(cx, value, props); } @@ -996,7 +997,7 @@ ScriptedIndirectProxyHandler::iterate(JSContext *cx, HandleObject proxy, unsigne return false; if (!js_IsCallable(value)) return BaseProxyHandler::iterate(cx, proxy, flags, vp); - return Trap(cx, handler, value, 0, NULL, vp) && + return Trap(cx, handler, value, 0, nullptr, vp) && ReturnedValueMustNotBePrimitive(cx, proxy, cx->names().iterate, vp); } @@ -1035,11 +1036,11 @@ ScriptedIndirectProxyHandler::fun_toString(JSContext *cx, HandleObject proxy, un { assertEnteredPolicy(cx, proxy, JSID_VOID); if (!proxy->isCallable()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO, js_Function_str, js_toString_str, "object"); - return NULL; + return nullptr; } RootedObject obj(cx, &proxy->as().extra(0).toObject().getReservedSlot(0).toObject()); return fun_toStringHelper(cx, obj, indent); @@ -1171,7 +1172,7 @@ NormalizePropertyDescriptor(JSContext *cx, MutableHandleValue vp, bool complete RootedValue v(cx); if (!JSObject::getGeneric(cx, descObj, attributes, id, &v)) return false; - if (!JSObject::defineGeneric(cx, descObj, id, v, NULL, NULL, JSPROP_ENUMERATE)) + if (!JSObject::defineGeneric(cx, descObj, id, v, nullptr, nullptr, JSPROP_ENUMERATE)) return false; } return true; @@ -1379,7 +1380,7 @@ TrapGetOwnProperty(JSContext *cx, HandleObject proxy, HandleId id, MutableHandle if (!IsSealed(cx, target, id, &sealed)) return false; if (sealed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_NC_AS_NE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_NC_AS_NE); return false; } @@ -1391,7 +1392,7 @@ TrapGetOwnProperty(JSContext *cx, HandleObject proxy, HandleId id, MutableHandle if (!HasOwn(cx, target, id, &found)) return false; if (found) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_E_AS_NE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_E_AS_NE); return false; } } @@ -1410,7 +1411,7 @@ TrapGetOwnProperty(JSContext *cx, HandleObject proxy, HandleId id, MutableHandle if (!JSObject::isExtensible(cx, target, &extensible)) return false; if (extensible && !isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_NEW); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_NEW); return false; } @@ -1426,14 +1427,14 @@ TrapGetOwnProperty(JSContext *cx, HandleObject proxy, HandleId id, MutableHandle return false; if (!valid) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_INVALID); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_INVALID); return false; } } // step 11 if (!desc->configurable() && !isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_NE_AS_NC); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_NE_AS_NC); return false; } @@ -1494,7 +1495,7 @@ TrapDefineOwnProperty(JSContext *cx, HandleObject proxy, HandleId id, MutableHan if (!JSObject::isExtensible(cx, target, &extensible)) return false; if (!extensible && !isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_DEFINE_NEW); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_DEFINE_NEW); return false; } @@ -1508,13 +1509,13 @@ TrapDefineOwnProperty(JSContext *cx, HandleObject proxy, HandleId id, MutableHan if (!ValidateProperty(cx, target, id, desc, &valid)) return false; if (!valid) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_DEFINE_INVALID); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_DEFINE_INVALID); return false; } } if (!desc->configurable() && !isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_DEFINE_NE_AS_NC); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_DEFINE_NE_AS_NC); return false; } @@ -1583,7 +1584,7 @@ ArrayToIdVector(JSContext *cx, HandleObject proxy, HandleObject target, HandleVa if (!JSObject::isExtensible(cx, target, &extensible)) return false; if (!extensible && !isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_NEW); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_NEW); return false; } @@ -1616,7 +1617,7 @@ ArrayToIdVector(JSContext *cx, HandleObject proxy, HandleObject target, HandleVa if (!IsSealed(cx, target, id, &sealed)) return false; if (sealed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_SKIP_NC); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_SKIP_NC); return false; } @@ -1630,7 +1631,7 @@ ArrayToIdVector(JSContext *cx, HandleObject proxy, HandleObject target, HandleVa if (!JSObject::isExtensible(cx, target, &extensible)) return false; if (!extensible && isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_E_AS_NE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_E_AS_NE); return false; } } @@ -1682,14 +1683,14 @@ ScriptedDirectProxyHandler::preventExtensions(JSContext *cx, HandleObject proxy) if (!JSObject::isExtensible(cx, target, &extensible)) return false; if (extensible) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE); return false; } return true; } // step h - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CHANGE_EXTENSIBILITY); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CHANGE_EXTENSIBILITY); return false; } @@ -1727,7 +1728,7 @@ ScriptedDirectProxyHandler::getOwnPropertyDescriptor(JSContext *cx, HandleObject // step 2 if (v.isUndefined()) { - desc.object().set(NULL); + desc.object().set(nullptr); return true; } @@ -1924,7 +1925,7 @@ ScriptedDirectProxyHandler::has(JSContext *cx, HandleObject proxy, HandleId id, if (!IsSealed(cx, target, id, &sealed)) return false; if (sealed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_NC_AS_NE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_NC_AS_NE); return false; } @@ -1936,7 +1937,7 @@ ScriptedDirectProxyHandler::has(JSContext *cx, HandleObject proxy, HandleId id, if (!HasOwn(cx, target, id, &isFixed)) return false; if (isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_E_AS_NE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_E_AS_NE); return false; } } @@ -1987,7 +1988,7 @@ ScriptedDirectProxyHandler::hasOwn(JSContext *cx, HandleObject proxy, HandleId i if (!IsSealed(cx, target, id, &sealed)) return false; if (sealed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_NC_AS_NE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_NC_AS_NE); return false; } @@ -1999,7 +2000,7 @@ ScriptedDirectProxyHandler::hasOwn(JSContext *cx, HandleObject proxy, HandleId i if (!HasOwn(cx, target, id, &isFixed)) return false; if (isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_E_AS_NE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_E_AS_NE); return false; } } @@ -2012,7 +2013,7 @@ ScriptedDirectProxyHandler::hasOwn(JSContext *cx, HandleObject proxy, HandleId i if (!HasOwn(cx, target, id, &isFixed)) return false; if (!isFixed) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_REPORT_NEW); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_REPORT_NEW); return false; } } @@ -2068,14 +2069,14 @@ ScriptedDirectProxyHandler::get(JSContext *cx, HandleObject proxy, HandleObject if (!SameValue(cx, vp, desc.value(), &same)) return false; if (!same) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MUST_REPORT_SAME_VALUE); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MUST_REPORT_SAME_VALUE); return false; } } if (IsAccessorDescriptor(desc) && desc.isPermanent() && !desc.hasGetterObject()) { if (!trapResult.isUndefined()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MUST_REPORT_UNDEFINED); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MUST_REPORT_UNDEFINED); return false; } } @@ -2135,13 +2136,13 @@ ScriptedDirectProxyHandler::set(JSContext *cx, HandleObject proxy, HandleObject if (!SameValue(cx, vp, desc.value(), &same)) return false; if (!same) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_SET_NW_NC); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_SET_NW_NC); return false; } } if (IsAccessorDescriptor(desc) && desc.isPermanent() && !desc.hasSetterObject()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_SET_WO_SETTER); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_SET_WO_SETTER); return false; } } @@ -2296,7 +2297,7 @@ Proxy::getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, { JS_CHECK_RECURSION(cx, return false); BaseProxyHandler *handler = proxy->as().handler(); - desc.object().set(NULL); // default result if we refuse to perform this action + desc.object().set(nullptr); // default result if we refuse to perform this action AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::GET, true); if (!policy.allowed()) return policy.returnValue(); @@ -2328,7 +2329,7 @@ Proxy::getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, JS_CHECK_RECURSION(cx, return false); BaseProxyHandler *handler = proxy->as().handler(); - desc.object().set(NULL); // default result if we refuse to perform this action + desc.object().set(nullptr); // default result if we refuse to perform this action AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::GET, true); if (!policy.allowed()) return policy.returnValue(); @@ -2693,7 +2694,7 @@ Proxy::className(JSContext *cx, HandleObject proxy) JSString * Proxy::fun_toString(JSContext *cx, HandleObject proxy, unsigned indent) { - JS_CHECK_RECURSION(cx, return NULL); + JS_CHECK_RECURSION(cx, return nullptr); BaseProxyHandler *handler = proxy->as().handler(); AutoEnterPolicy policy(cx, handler, proxy, JSID_VOIDHANDLE, BaseProxyHandler::GET, /* mayThrow = */ false); @@ -2744,8 +2745,8 @@ proxy_LookupGeneric(JSContext *cx, HandleObject obj, HandleId id, MarkNonNativePropertyFound(propp); objp.set(obj); } else { - objp.set(NULL); - propp.set(NULL); + objp.set(nullptr); + propp.set(nullptr); } return true; } @@ -3027,9 +3028,9 @@ proxy_Construct(JSContext *cx, unsigned argc, Value *vp) #define PROXY_CLASS_EXT \ { \ - NULL, /* outerObject */ \ - NULL, /* innerObject */ \ - NULL, /* iteratorObject */ \ + nullptr, /* outerObject */ \ + nullptr, /* innerObject */ \ + nullptr, /* iteratorObject */ \ false, /* isWrappedNative */ \ proxy_WeakmapKeyDelegate \ } @@ -3048,7 +3049,7 @@ proxy_Construct(JSContext *cx, unsigned argc, Value *vp) JS_ResolveStub, \ proxy_Convert, \ proxy_Finalize, /* finalize */ \ - NULL, /* checkAccess */ \ + nullptr, /* checkAccess */ \ callOp, /* call */ \ proxy_HasInstance, /* hasInstance */ \ constructOp, /* construct */ \ @@ -3077,12 +3078,12 @@ proxy_Construct(JSContext *cx, unsigned argc, Value *vp) proxy_DeleteProperty, \ proxy_DeleteElement, \ proxy_DeleteSpecial, \ - NULL, /* enumerate */ \ - NULL, /* thisObject */ \ + nullptr, /* enumerate */ \ + nullptr, /* thisObject */ \ } \ } -const Class js::ProxyObject::uncallableClass_ = PROXY_CLASS(NULL, NULL); +const Class js::ProxyObject::uncallableClass_ = PROXY_CLASS(nullptr, nullptr); const Class js::ProxyObject::callableClass_ = PROXY_CLASS(proxy_Call, proxy_Construct); const Class* const js::CallableProxyClassPtr = &ProxyObject::callableClass_; @@ -3099,15 +3100,15 @@ const Class js::OuterWindowProxyObject::class_ = { JS_ResolveStub, JS_ConvertStub, proxy_Finalize, /* finalize */ - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ ProxyObject::trace, /* trace */ { - NULL, /* outerObject */ + nullptr, /* outerObject */ proxy_innerObject, - NULL, /* iteratorObject */ + nullptr, /* iteratorObject */ false, /* isWrappedNative */ proxy_WeakmapKeyDelegate }, @@ -3134,8 +3135,8 @@ const Class js::OuterWindowProxyObject::class_ = { proxy_DeleteProperty, proxy_DeleteElement, proxy_DeleteSpecial, - NULL, /* enumerate */ - NULL, /* thisObject */ + nullptr, /* enumerate */ + nullptr, /* thisObject */ } }; @@ -3172,7 +3173,7 @@ proxy(JSContext *cx, unsigned argc, jsval *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 2) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "Proxy", "1", "s"); return false; } @@ -3203,20 +3204,20 @@ static bool proxy_create(JSContext *cx, unsigned argc, Value *vp) { if (argc < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "create", "0", "s"); return false; } JSObject *handler = NonNullObject(cx, vp[2]); if (!handler) return false; - JSObject *proto, *parent = NULL; + JSObject *proto, *parent = nullptr; if (argc > 1 && vp[3].isObject()) { proto = &vp[3].toObject(); parent = proto->getParent(); } else { JS_ASSERT(IsFunctionObject(vp[0])); - proto = NULL; + proto = nullptr; } if (!parent) parent = vp[0].toObject().getParent(); @@ -3234,7 +3235,7 @@ static bool proxy_createFunction(JSContext *cx, unsigned argc, Value *vp) { if (argc < 2) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "createFunction", "1", ""); return false; } @@ -3251,7 +3252,7 @@ proxy_createFunction(JSContext *cx, unsigned argc, Value *vp) RootedObject call(cx, ValueToCallable(cx, vp[3], argc - 2)); if (!call) return false; - JSObject *construct = NULL; + JSObject *construct = nullptr; if (argc > 2) { construct = ValueToCallable(cx, vp[4], argc - 3); if (!construct) @@ -3263,7 +3264,7 @@ proxy_createFunction(JSContext *cx, unsigned argc, Value *vp) // Stash the call and construct traps on a holder object that we can stick // in a slot on the proxy. RootedObject ccHolder(cx, JS_NewObjectWithGivenProto(cx, Jsvalify(&CallConstructHolder), - NULL, cx->global())); + nullptr, cx->global())); if (!ccHolder) return false; ccHolder->setReservedSlot(0, ObjectValue(*call)); @@ -3296,13 +3297,13 @@ js_InitProxyClass(JSContext *cx, HandleObject obj) RootedFunction ctor(cx); ctor = global->createConstructor(cx, proxy, cx->names().Proxy, 2); if (!ctor) - return NULL; + return nullptr; if (!JS_DefineFunctions(cx, ctor, static_methods)) - return NULL; + return nullptr; if (!JS_DefineProperty(cx, obj, "Proxy", OBJECT_TO_JSVAL(ctor), JS_PropertyStub, JS_StrictPropertyStub, 0)) { - return NULL; + return nullptr; } MarkStandardClassInitializedNoProto(obj, &ProxyObject::uncallableClass_); diff --git a/js/src/jsproxy.h b/js/src/jsproxy.h index dad56790183b..0becf9b6a48f 100644 --- a/js/src/jsproxy.h +++ b/js/src/jsproxy.h @@ -397,7 +397,7 @@ class JS_FRIEND_API(AutoEnterPolicy) AutoEnterPolicy(JSContext *cx, BaseProxyHandler *handler, HandleObject wrapper, HandleId id, Action act, bool mayThrow) #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif { allow = handler->hasPolicy() ? handler->enter(cx, wrapper, id, act, &rv) @@ -420,7 +420,7 @@ class JS_FRIEND_API(AutoEnterPolicy) // no-op constructor for subclass AutoEnterPolicy() #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif {}; void reportErrorIfExceptionIsNotPending(JSContext *cx, jsid id); diff --git a/js/src/jspubtd.h b/js/src/jspubtd.h index c9913a10ffc1..4aa922eb8401 100644 --- a/js/src/jspubtd.h +++ b/js/src/jspubtd.h @@ -11,6 +11,7 @@ * JS public API typedefs. */ +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "jsprototypes.h" @@ -312,13 +313,13 @@ struct ContextFriendFields public: explicit ContextFriendFields(JSRuntime *rt) - : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + : runtime_(rt), compartment_(nullptr), zone_(nullptr), autoGCRooters(nullptr) { #ifdef JSGC_TRACK_EXACT_ROOTS mozilla::PodArrayZero(thingGCRooters); #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) - skipGCRooters = NULL; + skipGCRooters = nullptr; #endif } diff --git a/js/src/jsreflect.cpp b/js/src/jsreflect.cpp index 4b11a964484e..f59b2d2da2ca 100644 --- a/js/src/jsreflect.cpp +++ b/js/src/jsreflect.cpp @@ -86,14 +86,14 @@ char const * const js::nodeTypeNames[] = { #define ASTDEF(ast, str, method) str, #include "jsast.tbl" #undef ASTDEF - NULL + nullptr }; static char const * const callbackNames[] = { #define ASTDEF(ast, str, method) method, #include "jsast.tbl" #undef ASTDEF - NULL + nullptr }; enum YieldKind { Delegating, NotDelegating }; @@ -106,20 +106,20 @@ typedef AutoValueVector NodeVector; * parser and the AST serializer. We use these macros to check invariants on a * parse node and raise a dynamic error on failure. */ -#define LOCAL_ASSERT(expr) \ - JS_BEGIN_MACRO \ - JS_ASSERT(expr); \ - if (!(expr)) { \ - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PARSE_NODE); \ - return false; \ - } \ +#define LOCAL_ASSERT(expr) \ + JS_BEGIN_MACRO \ + JS_ASSERT(expr); \ + if (!(expr)) { \ + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PARSE_NODE); \ + return false; \ + } \ JS_END_MACRO -#define LOCAL_NOT_REACHED(expr) \ - JS_BEGIN_MACRO \ - MOZ_ASSERT(false); \ - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PARSE_NODE); \ - return false; \ +#define LOCAL_NOT_REACHED(expr) \ + JS_BEGIN_MACRO \ + MOZ_ASSERT(false); \ + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PARSE_NODE); \ + return false; \ JS_END_MACRO namespace { @@ -160,7 +160,7 @@ class NodeBuilder public: NodeBuilder(JSContext *c, bool l, char const *s) - : cx(c), tokenStream(NULL), saveLoc(l), src(s), srcval(c), + : cx(c), tokenStream(nullptr), saveLoc(l), src(s), srcval(c), callbacksRoots(c, callbacks, AST_LIMIT), userv(c), undefinedVal(c, UndefinedValue()) { MakeRangeGCSafe(callbacks, mozilla::ArrayLength(callbacks)); @@ -202,7 +202,7 @@ class NodeBuilder if (!funv.isObject() || !funv.toObject().is()) { js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_NOT_FUNCTION, - JSDVG_SEARCH_STACK, funv, NullPtr(), NULL, NULL); + JSDVG_SEARCH_STACK, funv, NullPtr(), nullptr, nullptr); return false; } @@ -1842,7 +1842,7 @@ ASTSerializer::variableDeclarator(ParseNode *pn, VarDeclKind *pkind, MutableHand if (pn->isKind(PNK_NAME)) { pnleft = pn; - pnright = pn->isUsed() ? NULL : pn->pn_expr; + pnright = pn->isUsed() ? nullptr : pn->pn_expr; JS_ASSERT_IF(pnright, pn->pn_pos.encloses(pnright->pn_pos)); } else if (pn->isKind(PNK_ASSIGN)) { pnleft = pn->pn_left; @@ -1852,7 +1852,7 @@ ASTSerializer::variableDeclarator(ParseNode *pn, VarDeclKind *pkind, MutableHand } else { /* This happens for a destructuring declarator in a for-in/of loop. */ pnleft = pn; - pnright = NULL; + pnright = nullptr; } RootedValue left(cx), right(cx); @@ -1958,7 +1958,7 @@ ASTSerializer::catchClause(ParseNode *pn, bool *isGuarded, MutableHandleValue ds RootedValue var(cx), guard(cx), body(cx); - if (!pattern(pn->pn_kid1, NULL, &var) || + if (!pattern(pn->pn_kid1, nullptr, &var) || !optExpression(pn->pn_kid2, &guard)) { return false; } @@ -2135,7 +2135,7 @@ ASTSerializer::statement(ParseNode *pn, MutableHandleValue dst) if (head->isKind(PNK_FORIN)) { RootedValue var(cx); return (!head->pn_kid1 - ? pattern(head->pn_kid2, NULL, &var) + ? pattern(head->pn_kid2, nullptr, &var) : head->pn_kid1->isKind(PNK_LEXICALSCOPE) ? variableDeclaration(head->pn_kid1->pn_expr, true, &var) : variableDeclaration(head->pn_kid1, false, &var)) && @@ -2177,7 +2177,7 @@ ASTSerializer::statement(ParseNode *pn, MutableHandleValue dst) { RootedValue label(cx); RootedAtom pnAtom(cx, pn->pn_atom); - return optIdentifier(pnAtom, NULL, &label) && + return optIdentifier(pnAtom, nullptr, &label) && (pn->isKind(PNK_BREAK) ? builder.breakStatement(label, &pn->pn_pos, dst) : builder.continueStatement(label, &pn->pn_pos, dst)); @@ -2189,7 +2189,7 @@ ASTSerializer::statement(ParseNode *pn, MutableHandleValue dst) RootedValue label(cx), stmt(cx); RootedAtom pnAtom(cx, pn->as().label()); - return identifier(pnAtom, NULL, &label) && + return identifier(pnAtom, nullptr, &label) && statement(pn->pn_expr, &stmt) && builder.labeledStatement(label, stmt, &pn->pn_pos, dst); } @@ -2268,7 +2268,7 @@ ASTSerializer::comprehensionBlock(ParseNode *pn, MutableHandleValue dst) bool isForOf = pn->pn_iflags & JSITER_FOR_OF; RootedValue patt(cx), src(cx); - return pattern(in->pn_kid2, NULL, &patt) && + return pattern(in->pn_kid2, nullptr, &patt) && expression(in->pn_kid3, &src) && builder.comprehensionBlock(patt, src, isForEach, isForOf, &in->pn_pos, dst); } @@ -2430,7 +2430,7 @@ ASTSerializer::expression(ParseNode *pn, MutableHandleValue dst) LOCAL_ASSERT(op > AOP_ERR && op < AOP_LIMIT); RootedValue lhs(cx), rhs(cx); - return pattern(pn->pn_left, NULL, &lhs) && + return pattern(pn->pn_left, nullptr, &lhs) && expression(pn->pn_right, &rhs) && builder.assignmentExpression(op, lhs, rhs, &pn->pn_pos, dst); } @@ -2528,7 +2528,7 @@ ASTSerializer::expression(ParseNode *pn, MutableHandleValue dst) RootedValue expr(cx), id(cx); RootedAtom pnAtom(cx, pn->pn_atom); return expression(pn->pn_expr, &expr) && - identifier(pnAtom, NULL, &id) && + identifier(pnAtom, nullptr, &id) && builder.memberExpression(false, expr, id, &pn->pn_pos, dst); } @@ -2576,7 +2576,7 @@ ASTSerializer::expression(ParseNode *pn, MutableHandleValue dst) { /* The parser notes any uninitialized properties by setting the PNX_DESTRUCT flag. */ if (pn->pn_xflags & PNX_DESTRUCT) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_OBJECT_INIT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_OBJECT_INIT); return false; } NodeVector elts(cx); @@ -2843,7 +2843,7 @@ ASTSerializer::function(ParseNode *pn, ASTType type, MutableHandleValue dst) RootedValue id(cx); RootedAtom funcAtom(cx, func->atom()); - if (!optIdentifier(funcAtom, NULL, &id)) + if (!optIdentifier(funcAtom, nullptr, &id)) return false; NodeVector args(cx); @@ -2871,7 +2871,7 @@ ASTSerializer::functionArgsAndBody(ParseNode *pn, NodeVector &args, NodeVector & pnargs = pn; pnbody = pn->last(); } else { - pnargs = NULL; + pnargs = nullptr; pnbody = pn; } @@ -2886,13 +2886,13 @@ ASTSerializer::functionArgsAndBody(ParseNode *pn, NodeVector &args, NodeVector & LOCAL_ASSERT(pndestruct); LOCAL_ASSERT(pndestruct->isKind(PNK_VAR)); } else { - pndestruct = NULL; + pndestruct = nullptr; } /* Serialize the arguments and body. */ switch (pnbody->getKind()) { case PNK_RETURN: /* expression closure, no destructured args */ - return functionArgs(pn, pnargs, NULL, pnbody, args, defaults, rest) && + return functionArgs(pn, pnargs, nullptr, pnbody, args, defaults, rest) && expression(pnbody->pn_kid, body); case PNK_SEQ: /* expression closure with destructured args */ @@ -2925,8 +2925,8 @@ ASTSerializer::functionArgs(ParseNode *pn, ParseNode *pnargs, ParseNode *pndestr MutableHandleValue rest) { uint32_t i = 0; - ParseNode *arg = pnargs ? pnargs->pn_head : NULL; - ParseNode *destruct = pndestruct ? pndestruct->pn_head : NULL; + ParseNode *arg = pnargs ? pnargs->pn_head : nullptr; + ParseNode *destruct = pndestruct ? pndestruct->pn_head : nullptr; RootedValue node(cx); /* @@ -2939,7 +2939,7 @@ ASTSerializer::functionArgs(ParseNode *pn, ParseNode *pnargs, ParseNode *pndestr */ while ((arg && arg != pnbody) || destruct) { if (destruct && destruct->pn_right->frameSlot() == i) { - if (!pattern(destruct->pn_left, NULL, &node) || !args.append(node)) + if (!pattern(destruct->pn_left, nullptr, &node) || !args.append(node)) return false; destruct = destruct->pn_next; } else if (arg && arg != pnbody) { @@ -3000,7 +3000,7 @@ reflect_parse(JSContext *cx, uint32_t argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "Reflect.parse", "0", "s"); return false; } @@ -3020,7 +3020,8 @@ reflect_parse(JSContext *cx, uint32_t argc, jsval *vp) if (!arg.isNullOrUndefined()) { if (!arg.isObject()) { js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_UNEXPECTED_TYPE, - JSDVG_SEARCH_STACK, arg, NullPtr(), "not an object", NULL); + JSDVG_SEARCH_STACK, arg, NullPtr(), + "not an object", nullptr); return false; } @@ -3077,7 +3078,8 @@ reflect_parse(JSContext *cx, uint32_t argc, jsval *vp) if (!prop.isNullOrUndefined()) { if (!prop.isObject()) { js_ReportValueErrorFlags(cx, JSREPORT_ERROR, JSMSG_UNEXPECTED_TYPE, - JSDVG_SEARCH_STACK, prop, NullPtr(), "not an object", NULL); + JSDVG_SEARCH_STACK, prop, NullPtr(), + "not an object", nullptr); return false; } builder = &prop.toObject(); @@ -3099,11 +3101,11 @@ reflect_parse(JSContext *cx, uint32_t argc, jsval *vp) options.setFileAndLine(filename, lineno); options.setCanLazilyParse(false); Parser parser(cx, &cx->tempLifoAlloc(), options, chars.get(), length, - /* foldConstants = */ false, NULL, NULL); + /* foldConstants = */ false, nullptr, nullptr); serialize.setParser(&parser); - ParseNode *pn = parser.parse(NULL); + ParseNode *pn = parser.parse(nullptr); if (!pn) return false; @@ -3126,17 +3128,18 @@ JS_PUBLIC_API(JSObject *) JS_InitReflect(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); - RootedObject Reflect(cx, NewObjectWithClassProto(cx, &JSObject::class_, NULL, obj, SingletonObject)); + RootedObject Reflect(cx, NewObjectWithClassProto(cx, &JSObject::class_, nullptr, + obj, SingletonObject)); if (!Reflect) - return NULL; + return nullptr; if (!JS_DefineProperty(cx, obj, "Reflect", OBJECT_TO_JSVAL(Reflect), JS_PropertyStub, JS_StrictPropertyStub, 0)) { - return NULL; + return nullptr; } if (!JS_DefineFunctions(cx, Reflect, static_methods)) - return NULL; + return nullptr; return Reflect; } diff --git a/js/src/jsscript.cpp b/js/src/jsscript.cpp index 0da089e497be..d994bc3e3231 100644 --- a/js/src/jsscript.cpp +++ b/js/src/jsscript.cpp @@ -72,7 +72,7 @@ Bindings::initWithTemporaryStorage(ExclusiveContext *cx, InternalBindingsHandle if (numArgs > UINT16_MAX || numVars > UINT16_MAX) { if (cx->isJSContext()) { - JS_ReportErrorNumber(cx->asJSContext(), js_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx->asJSContext(), js_GetErrorMessage, nullptr, self->numArgs_ > self->numVars_ ? JSMSG_TOO_MANY_FUN_ARGS : JSMSG_TOO_MANY_LOCALS); @@ -98,7 +98,7 @@ Bindings::initWithTemporaryStorage(ExclusiveContext *cx, InternalBindingsHandle gc::AllocKind allocKind = gc::FINALIZE_OBJECT2_BACKGROUND; JS_ASSERT(gc::GetGCKindSlots(allocKind) == CallObject::RESERVED_SLOTS); RootedShape initial(cx, - EmptyShape::getInitialShape(cx, &CallObject::class_, NULL, cx->global(), NULL, + EmptyShape::getInitialShape(cx, &CallObject::class_, nullptr, cx->global(), nullptr, allocKind, BaseShape::VAROBJ | BaseShape::DELEGATE)); if (!initial) return false; @@ -123,7 +123,7 @@ Bindings::initWithTemporaryStorage(ExclusiveContext *cx, InternalBindingsHandle return false; #endif - StackBaseShape base(cx, &CallObject::class_, cx->global(), NULL, + StackBaseShape base(cx, &CallObject::class_, cx->global(), nullptr, BaseShape::VAROBJ | BaseShape::DELEGATE); UnownedBaseShape *nbase = BaseShape::getUnowned(cx, base); @@ -939,7 +939,7 @@ void ScriptSourceObject::finalize(FreeOp *fop, JSObject *obj) { // ScriptSource::setSource automatically takes care of the refcount - obj->as().setSource(NULL); + obj->as().setSource(nullptr); } const Class ScriptSourceObject::class_ = { @@ -958,9 +958,9 @@ const Class ScriptSourceObject::class_ = { ScriptSourceObject * ScriptSourceObject::create(ExclusiveContext *cx, ScriptSource *source) { - RootedObject object(cx, NewObjectWithGivenProto(cx, &class_, NULL, cx->global())); + RootedObject object(cx, NewObjectWithGivenProto(cx, &class_, nullptr, cx->global())); if (!object) - return NULL; + return nullptr; RootedScriptSource sourceObject(cx, &object->as()); sourceObject->setSlot(SOURCE_SLOT, PrivateValue(source)); source->incref(); @@ -982,7 +982,7 @@ ScriptSource::adjustDataSize(size_t nbytes) return true; } - // |data.compressed| can be NULL. + // |data.compressed| can be nullptr. void *buf = js_realloc(data.compressed, nbytes); if (!buf && data.compressed != emptySource) js_free(data.compressed); @@ -997,7 +997,7 @@ JSScript::loadSource(JSContext *cx, ScriptSource *ss, bool *worked) *worked = false; if (!cx->runtime()->sourceHook || !ss->sourceRetrievable()) return true; - jschar *src = NULL; + jschar *src = nullptr; size_t length; if (!cx->runtime()->sourceHook->load(cx, ss->filename(), &src, &length)) return false; @@ -1019,10 +1019,10 @@ JSStableString * SourceDataCache::lookup(ScriptSource *ss) { if (!map_) - return NULL; + return nullptr; if (Map::Ptr p = map_->lookup(ss)) return p->value; - return NULL; + return nullptr; } void @@ -1045,7 +1045,7 @@ void SourceDataCache::purge() { js_delete(map_); - map_ = NULL; + map_ = nullptr; } const jschar * @@ -1062,18 +1062,18 @@ ScriptSource::chars(JSContext *cx) const size_t nbytes = sizeof(jschar) * (length_ + 1); jschar *decompressed = static_cast(js_malloc(nbytes)); if (!decompressed) - return NULL; + return nullptr; if (!DecompressString(data.compressed, compressedLength_, reinterpret_cast(decompressed), nbytes)) { JS_ReportOutOfMemory(cx); js_free(decompressed); - return NULL; + return nullptr; } decompressed[length_] = 0; cached = js_NewString(cx, decompressed, length_); if (!cached) { js_free(decompressed); - return NULL; + return nullptr; } cx->runtime()->sourceDataCache.put(this, cached); } @@ -1089,10 +1089,10 @@ ScriptSource::substring(JSContext *cx, uint32_t start, uint32_t stop) JS_ASSERT(start <= stop); const jschar *chars = this->chars(cx); if (!chars) - return NULL; + return nullptr; JSFlatString *flatStr = js_NewStringCopyN(cx, chars + start, stop - start); if (!flatStr) - return NULL; + return nullptr; return flatStr->ensureStable(cx); } @@ -1220,7 +1220,7 @@ size_t ScriptSource::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) { // |data| is a union, but both members are pointers to allocated memory, - // |emptySource|, or NULL, so just using |data.compressed| will work. + // |emptySource|, or nullptr, so just using |data.compressed| will work. size_t n = mallocSizeOf(this); n += (ready() && data.compressed != emptySource) ? mallocSizeOf(data.compressed) @@ -1265,7 +1265,7 @@ ScriptSource::performXDR(XDRState *xdr) if (!xdr->codeBytes(data.compressed, byteLen)) { if (mode == XDR_DECODE) { js_free(data.compressed); - data.compressed = NULL; + data.compressed = nullptr; } return false; } @@ -1292,7 +1292,7 @@ ScriptSource::performXDR(XDRState *xdr) if (!xdr->codeChars(sourceMapURL_, sourceMapURLLen)) { if (mode == XDR_DECODE) { js_free(sourceMapURL_); - sourceMapURL_ = NULL; + sourceMapURL_ = nullptr; } return false; } @@ -1317,7 +1317,7 @@ ScriptSource::performXDR(XDRState *xdr) if (!xdr->codeChars(sourceURL_, sourceURLLen)) { if (mode == XDR_DECODE) { js_free(sourceURL_); - sourceURL_ = NULL; + sourceURL_ = nullptr; } return false; } @@ -1363,7 +1363,7 @@ ScriptSource::setSourceURL(ExclusiveContext *cx, const jschar *sourceURL) if (hasSourceURL()) { if (cx->isJSContext() && !JS_ReportErrorFlagsAndNumber(cx->asJSContext(), JSREPORT_WARNING, - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_ALREADY_HAS_PRAGMA, filename_, "//# sourceURL")) { @@ -1393,7 +1393,7 @@ ScriptSource::setSourceMapURL(ExclusiveContext *cx, const jschar *sourceMapURL) if (hasSourceMapURL()) { if (cx->isJSContext() && !JS_ReportErrorFlagsAndNumber(cx->asJSContext(), JSREPORT_WARNING, - js_GetErrorMessage, NULL, + js_GetErrorMessage, nullptr, JSMSG_ALREADY_HAS_PRAGMA, filename_, "//# sourceMappingURL")) { @@ -1438,7 +1438,7 @@ js::SharedScriptData::new_(ExclusiveContext *cx, uint32_t codeLength, SharedScriptData *entry = (SharedScriptData *)cx->malloc_(length + dataOffset); if (!entry) - return NULL; + return nullptr; entry->length = length; entry->natoms = natoms; @@ -1467,8 +1467,8 @@ static bool SaveSharedScriptData(ExclusiveContext *cx, Handle script, SharedScriptData *ssd, uint32_t nsrcnotes) { - ASSERT(script != NULL); - ASSERT(ssd != NULL); + ASSERT(script != nullptr); + ASSERT(ssd != nullptr); AutoLockForExclusiveAccess lock(cx); @@ -1480,8 +1480,8 @@ SaveSharedScriptData(ExclusiveContext *cx, Handle script, SharedScri ssd = *p; } else { if (!cx->scriptDataTable().add(p, ssd)) { - script->code = NULL; - script->atoms = NULL; + script->code = nullptr; + script->atoms = nullptr; js_free(ssd); js_ReportOutOfMemory(cx); return false; @@ -1677,7 +1677,7 @@ JSScript::Create(ExclusiveContext *cx, HandleObject enclosingScope, bool savedCa RootedScript script(cx, js_NewGCScript(cx)); if (!script) - return NULL; + return nullptr; PodZero(script.get()); new (&script->bindings) Bindings; @@ -1700,9 +1700,9 @@ JSScript::Create(ExclusiveContext *cx, HandleObject enclosingScope, bool savedCa if (staticLevel > UINT16_MAX) { if (cx->isJSContext()) { JS_ReportErrorNumber(cx->asJSContext(), - js_GetErrorMessage, NULL, JSMSG_TOO_DEEP, js_function_str); + js_GetErrorMessage, nullptr, JSMSG_TOO_DEEP, js_function_str); } - return NULL; + return nullptr; } script->staticLevel = uint16_t(staticLevel); @@ -1718,7 +1718,7 @@ AllocScriptData(ExclusiveContext *cx, size_t size) { uint8_t *data = static_cast(cx->calloc_(JS_ROUNDUP(size, sizeof(Value)))); if (!data) - return NULL; + return nullptr; // All script data is optional, so size might be 0. In that case, we don't care about alignment. JS_ASSERT(size == 0 || size_t(data) % sizeof(Value) == 0); @@ -1856,12 +1856,12 @@ JSScript::fullyInitFromEmitter(ExclusiveContext *cx, HandleScript script, Byteco JS_ASSERT(nfixed < SLOTNO_LIMIT); script->nfixed = uint16_t(nfixed); if (script->nfixed + bce->maxStackDepth >= JS_BIT(16)) { - bce->reportError(NULL, JSMSG_NEED_DIET, "script"); + bce->reportError(nullptr, JSMSG_NEED_DIET, "script"); return false; } script->nslots = script->nfixed + bce->maxStackDepth; - FunctionBox *funbox = bce->sc->isFunctionBox() ? bce->sc->asFunctionBox() : NULL; + FunctionBox *funbox = bce->sc->isFunctionBox() ? bce->sc->asFunctionBox() : nullptr; if (bce->tryNoteList.length() != 0) bce->tryNoteList.finish(script->trynotes()); @@ -1891,7 +1891,7 @@ JSScript::fullyInitFromEmitter(ExclusiveContext *cx, HandleScript script, Byteco script->funLength = funbox->length; } - RootedFunction fun(cx, NULL); + RootedFunction fun(cx, nullptr); if (funbox) { JS_ASSERT(!bce->script->noScriptRval); script->isGeneratorExp = funbox->inGenexpLambda; @@ -1953,7 +1953,7 @@ JSScript::enclosingScriptsCompiledSuccessfully() const /* * When a nested script is succesfully compiled, it is eagerly given the * static JSFunction of its enclosing script. The enclosing function's - * 'script' field will be NULL until the enclosing script successfully + * 'script' field will be nullptr until the enclosing script successfully * compiles. Thus, we can detect failed compilation by looking for * JSFunctions in the enclosingScope chain without scripts. */ @@ -2031,7 +2031,7 @@ static const uint32_t GSN_CACHE_THRESHOLD = 100; void GSNCache::purge() { - code = NULL; + code = nullptr; if (map.initialized()) map.finish(); } @@ -2041,19 +2041,19 @@ js::GetSrcNote(GSNCache &cache, JSScript *script, jsbytecode *pc) { size_t target = pc - script->code; if (target >= size_t(script->length)) - return NULL; + return nullptr; if (cache.code == script->code) { JS_ASSERT(cache.map.initialized()); GSNCache::Map::Ptr p = cache.map.lookup(pc); - return p ? p->value : NULL; + return p ? p->value : nullptr; } size_t offset = 0; jssrcnote *result; for (jssrcnote *sn = script->notes(); ; sn = SN_NEXT(sn)) { if (SN_IS_TERMINATOR(sn)) { - result = NULL; + result = nullptr; break; } offset += SN_DELTA(sn); @@ -2073,7 +2073,7 @@ js::GetSrcNote(GSNCache &cache, JSScript *script, jsbytecode *pc) if (cache.code) { JS_ASSERT(cache.map.initialized()); cache.map.finish(); - cache.code = NULL; + cache.code = nullptr; } if (cache.map.init(nsrcnotes)) { pc = script->code; @@ -2224,7 +2224,7 @@ js::CurrentScriptFileLineOrigin(JSContext *cx, const char **file, unsigned *line JSPrincipals **origin, LineOption opt) { if (opt == CALLED_FROM_JSOP_EVAL) { - jsbytecode *pc = NULL; + jsbytecode *pc = nullptr; JSScript *script = cx->currentScript(&pc); JS_ASSERT(JSOp(*pc) == JSOP_EVAL || JSOp(*pc) == JSOP_SPREADEVAL); JS_ASSERT(*(pc + (JSOp(*pc) == JSOP_EVAL ? JSOP_EVAL_LENGTH @@ -2239,7 +2239,7 @@ js::CurrentScriptFileLineOrigin(JSContext *cx, const char **file, unsigned *line NonBuiltinScriptFrameIter iter(cx); if (iter.done()) { - *file = NULL; + *file = nullptr; *linenop = 0; *origin = cx->compartment()->principals; return; @@ -2275,7 +2275,7 @@ js::CloneScript(JSContext *cx, HandleObject enclosingScope, HandleFunction fun, size_t size = src->dataSize; uint8_t *data = AllocScriptData(cx, size); if (!data) - return NULL; + return nullptr; /* Bindings */ @@ -2283,7 +2283,7 @@ js::CloneScript(JSContext *cx, HandleObject enclosingScope, HandleFunction fun, InternalHandle bindingsHandle = InternalHandle::fromMarkedLocation(bindings.address()); if (!Bindings::clone(cx, bindingsHandle, data, src)) - return NULL; + return nullptr; /* Objects */ @@ -2312,7 +2312,7 @@ js::CloneScript(JSContext *cx, HandleObject enclosingScope, HandleFunction fun, if (innerFun->isInterpretedLazy()) { AutoCompartment ac(cx, innerFun); if (!innerFun->getOrCreateScript(cx)) - return NULL; + return nullptr; } RootedObject staticScope(cx, innerFun->nonLazyScript()->enclosingStaticScope()); StaticScopeIter ssi(cx, staticScope); @@ -2334,7 +2334,7 @@ js::CloneScript(JSContext *cx, HandleObject enclosingScope, HandleFunction fun, clone = CloneObjectLiteral(cx, cx->global(), obj); } if (!clone || !objects.append(clone)) - return NULL; + return nullptr; } } @@ -2346,7 +2346,7 @@ js::CloneScript(JSContext *cx, HandleObject enclosingScope, HandleFunction fun, for (unsigned i = 0; i < nregexps; i++) { JSObject *clone = CloneScriptRegExpObject(cx, vector[i]->as()); if (!clone || !regexps.append(clone)) - return NULL; + return nullptr; } } @@ -2363,14 +2363,14 @@ js::CloneScript(JSContext *cx, HandleObject enclosingScope, HandleFunction fun, /* Make sure we clone the script source object with the script */ RootedScriptSource sourceObject(cx, ScriptSourceObject::create(cx, src->scriptSource())); if (!sourceObject) - return NULL; + return nullptr; RootedScript dst(cx, JSScript::Create(cx, enclosingScope, src->savedCallerFun, options, src->staticLevel, sourceObject, src->sourceStart, src->sourceEnd)); if (!dst) { js_free(data); - return NULL; + return nullptr; } dst->bindings = bindings; @@ -2452,7 +2452,7 @@ js::CloneFunctionScript(JSContext *cx, HandleFunction original, HandleFunction c RootedObject scope(cx, script->enclosingStaticScope()); - clone->mutableScript().init(NULL); + clone->mutableScript().init(nullptr); JSScript *cscript = CloneScript(cx, scope, clone, script, newKind); if (!cscript) @@ -2463,7 +2463,7 @@ js::CloneFunctionScript(JSContext *cx, HandleFunction original, HandleFunction c script = clone->nonLazyScript(); CallNewScriptHook(cx, script, clone); - RootedGlobalObject global(cx, script->compileAndGo ? &script->global() : NULL); + RootedGlobalObject global(cx, script->compileAndGo ? &script->global() : nullptr); Debugger::onNewScript(cx, script, global); return true; @@ -2502,9 +2502,9 @@ JSScript::destroyDebugScript(FreeOp *fop) for (jsbytecode *pc = code; pc < end; pc++) { if (BreakpointSite *site = getBreakpointSite(pc)) { /* Breakpoints are swept before finalization. */ - JS_ASSERT(site->firstBreakpoint() == NULL); - site->clearTrap(fop, NULL, NULL); - JS_ASSERT(getBreakpointSite(pc) == NULL); + JS_ASSERT(site->firstBreakpoint() == nullptr); + site->clearTrap(fop, nullptr, nullptr); + JS_ASSERT(getBreakpointSite(pc) == nullptr); } } fop->free_(releaseDebugScript()); @@ -2558,7 +2558,7 @@ JSScript::recompileForStepMode(FreeOp *fop) { #ifdef JS_ION if (hasBaselineScript()) - baseline->toggleDebugTraps(this, NULL); + baseline->toggleDebugTraps(this, nullptr); #endif } @@ -2615,7 +2615,7 @@ JSScript::getOrCreateBreakpointSite(JSContext *cx, jsbytecode *pc) JS_ASSERT(size_t(pc - code) < length); if (!ensureHasDebugScript(cx)) - return NULL; + return nullptr; DebugScript *debug = debugScript(); BreakpointSite *&site = debug->breakpoints[pc - code]; @@ -2624,7 +2624,7 @@ JSScript::getOrCreateBreakpointSite(JSContext *cx, jsbytecode *pc) site = cx->runtime()->new_(this, pc); if (!site) { js_ReportOutOfMemory(cx); - return NULL; + return nullptr; } debug->numSites++; } @@ -2642,7 +2642,7 @@ JSScript::destroyBreakpointSite(FreeOp *fop, jsbytecode *pc) JS_ASSERT(site); fop->delete_(site); - site = NULL; + site = nullptr; if (--debug->numSites == 0 && !stepModeEnabled()) fop->free_(releaseDebugScript()); @@ -2927,10 +2927,10 @@ JSScript::formalLivesInArgumentsObject(unsigned argSlot) LazyScript::LazyScript(JSFunction *fun, void *table, uint32_t numFreeVariables, uint32_t numInnerFunctions, JSVersion version, uint32_t begin, uint32_t end, uint32_t lineno, uint32_t column) - : script_(NULL), + : script_(nullptr), function_(fun), - enclosingScope_(NULL), - sourceObject_(NULL), + enclosingScope_(nullptr), + sourceObject_(nullptr), table_(table), version_(version), numFreeVariables_(numFreeVariables), @@ -2969,7 +2969,7 @@ LazyScript::setParent(JSObject *enclosingScope, ScriptSourceObject *sourceObject ScriptSourceObject * LazyScript::sourceObject() const { - return sourceObject_ ? &sourceObject_->as() : NULL; + return sourceObject_ ? &sourceObject_->as() : nullptr; } /* static */ LazyScript * @@ -2982,16 +2982,16 @@ LazyScript::Create(ExclusiveContext *cx, HandleFunction fun, size_t bytes = (numFreeVariables * sizeof(HeapPtrAtom)) + (numInnerFunctions * sizeof(HeapPtrFunction)); - void *table = NULL; + void *table = nullptr; if (bytes) { table = cx->malloc_(bytes); if (!table) - return NULL; + return nullptr; } LazyScript *res = js_NewGCLazyScript(cx); if (!res) - return NULL; + return nullptr; return new (res) LazyScript(fun, table, numFreeVariables, numInnerFunctions, version, begin, end, lineno, column); @@ -3018,8 +3018,8 @@ JSScript::updateBaselineOrIonRaw() baselineOrIonRaw = baseline->method()->raw(); baselineOrIonSkipArgCheck = baseline->method()->raw(); } else { - baselineOrIonRaw = NULL; - baselineOrIonSkipArgCheck = NULL; + baselineOrIonRaw = nullptr; + baselineOrIonSkipArgCheck = nullptr; } #endif } diff --git a/js/src/jsscript.h b/js/src/jsscript.h index 414b83bc19bb..b35375f6243a 100644 --- a/js/src/jsscript.h +++ b/js/src/jsscript.h @@ -241,7 +241,7 @@ class ScriptCounts jit::IonScriptCounts *ionCounts; public: - ScriptCounts() : pcCountsVector(NULL), ionCounts(NULL) { } + ScriptCounts() : pcCountsVector(nullptr), ionCounts(nullptr) { } inline void destroy(FreeOp *fop); @@ -290,7 +290,7 @@ class ScriptSource union { // Before setSourceCopy or setSource are successfully called, this union - // has a NULL pointer. When the script source is ready, + // has a nullptr pointer. When the script source is ready, // compressedLength_ != 0 implies compressed holds the compressed data; // otherwise, source holds the uncompressed source. There is a special // pointer |emptySource| for source code for length 0. @@ -320,15 +320,15 @@ class ScriptSource : refs(0), length_(0), compressedLength_(0), - filename_(NULL), - sourceURL_(NULL), - sourceMapURL_(NULL), + filename_(nullptr), + sourceURL_(nullptr), + sourceMapURL_(nullptr), originPrincipals_(originPrincipals), sourceRetrievable_(false), argumentsNotIncluded_(false), ready_(true) { - data.source = NULL; + data.source = nullptr; if (originPrincipals_) JS_HoldPrincipals(originPrincipals_); } @@ -372,12 +372,12 @@ class ScriptSource // Source URLs bool setSourceURL(ExclusiveContext *cx, const jschar *sourceURL); const jschar *sourceURL(); - bool hasSourceURL() const { return sourceURL_ != NULL; } + bool hasSourceURL() const { return sourceURL_ != nullptr; } // Source maps bool setSourceMapURL(ExclusiveContext *cx, const jschar *sourceMapURL); const jschar *sourceMapURL(); - bool hasSourceMapURL() const { return sourceMapURL_ != NULL; } + bool hasSourceMapURL() const { return sourceMapURL_ != nullptr; } JSPrincipals *originPrincipals() const { return originPrincipals_; } @@ -486,8 +486,8 @@ class JSScript : public js::gc::BarrieredCell js::jit::IonScript *parallelIon; /* - * Pointer to either baseline->method()->raw() or ion->method()->raw(), or NULL - * if there's no Baseline or Ion script. + * Pointer to either baseline->method()->raw() or ion->method()->raw(), or + * nullptr if there's no Baseline or Ion script. */ uint8_t *baselineOrIonRaw; uint8_t *baselineOrIonSkipArgCheck; @@ -797,7 +797,7 @@ class JSScript : public js::gc::BarrieredCell /* * Original compiled function for the script, if it has a function. - * NULL for global and eval scripts. + * nullptr for global and eval scripts. */ JSFunction *function() const { return function_; } inline void setFunction(JSFunction *fun); @@ -851,7 +851,7 @@ class JSScript : public js::gc::BarrieredCell /* See StaticScopeIter comment. */ JSObject *enclosingStaticScope() const { if (isCallsiteClone) - return NULL; + return nullptr; return enclosingScopeOrOriginalFunction_; } @@ -1035,7 +1035,7 @@ class JSScript : public js::gc::BarrieredCell js::BreakpointSite *getBreakpointSite(jsbytecode *pc) { JS_ASSERT(size_t(pc - code) < length); - return hasDebugScript ? debugScript()->breakpoints[pc - code] : NULL; + return hasDebugScript ? debugScript()->breakpoints[pc - code] : nullptr; } js::BreakpointSite *getOrCreateBreakpointSite(JSContext *cx, jsbytecode *pc); @@ -1157,18 +1157,18 @@ class AliasedFormalIter // bytecode from its source. class LazyScript : public gc::BarrieredCell { - // If non-NULL, the script has been compiled and this is a forwarding + // If non-nullptr, the script has been compiled and this is a forwarding // pointer to the result. HeapPtrScript script_; // Original function with which the lazy script is associated. HeapPtrFunction function_; - // Function or block chain in which the script is nested, or NULL. + // Function or block chain in which the script is nested, or nullptr. HeapPtrObject enclosingScope_; - // Source code object, or NULL if the script in which this is nested has - // not been compiled yet. + // Source code object, or nullptr if the script in which this is nested + // has not been compiled yet. HeapPtrObject sourceObject_; // Heap allocated table with any free variables or inner functions. @@ -1364,7 +1364,7 @@ struct SharedScriptData HeapPtrAtom *atoms() { if (!natoms) - return NULL; + return nullptr; return reinterpret_cast(data + length - sizeof(JSAtom *) * natoms); } @@ -1439,18 +1439,18 @@ js_GetScriptLineExtent(JSScript *script); namespace js { extern unsigned -PCToLineNumber(JSScript *script, jsbytecode *pc, unsigned *columnp = NULL); +PCToLineNumber(JSScript *script, jsbytecode *pc, unsigned *columnp = nullptr); extern unsigned PCToLineNumber(unsigned startLine, jssrcnote *notes, jsbytecode *code, jsbytecode *pc, - unsigned *columnp = NULL); + unsigned *columnp = nullptr); /* * This function returns the file and line number of the script currently * executing on cx. If there is no current script executing on cx (e.g., a - * native called directly through JSAPI (e.g., by setTimeout)), NULL and 0 are - * returned as the file and line. Additionally, this function avoids the full - * linear scan to compute line number when the caller guarantees that the + * native called directly through JSAPI (e.g., by setTimeout)), nullptr and 0 + * are returned as the file and line. Additionally, this function avoids the + * full linear scan to compute line number when the caller guarantees that the * script compilation occurs at a JSOP_EVAL/JSOP_SPREADEVAL. */ @@ -1472,7 +1472,7 @@ CloneFunctionScript(JSContext *cx, HandleFunction original, HandleFunction clone NewObjectKind newKind = GenericObject); /* - * JSAPI clients are allowed to leave CompileOptions.originPrincipals NULL in + * JSAPI clients are allowed to leave CompileOptions.originPrincipals nullptr in * which case the JS engine sets options.originPrincipals = origin.principals. * This normalization step must occur before the originPrincipals get stored in * the JSScript/ScriptSource. diff --git a/js/src/jsscriptinlines.h b/js/src/jsscriptinlines.h index daf863bc9763..cce910b7863b 100644 --- a/js/src/jsscriptinlines.h +++ b/js/src/jsscriptinlines.h @@ -21,7 +21,7 @@ namespace js { inline Bindings::Bindings() - : callObjShape_(NULL), bindingArrayAndFlag_(TEMPORARY_STORAGE_BIT), numArgs_(0), numVars_(0) + : callObjShape_(nullptr), bindingArrayAndFlag_(TEMPORARY_STORAGE_BIT), numArgs_(0), numVars_(0) {} inline @@ -78,7 +78,7 @@ JSScript::functionOrCallerFunction() return function(); if (savedCallerFun) return getCallerFunction(); - return NULL; + return nullptr; } inline js::RegExpObject * @@ -110,7 +110,7 @@ JSScript::principals() inline JSFunction * JSScript::originalFunction() const { if (!isCallsiteClone) - return NULL; + return nullptr; return &enclosingScopeOrOriginalFunction_->as(); } diff --git a/js/src/jsstr.cpp b/js/src/jsstr.cpp index 94459a665697..124f7ae517eb 100644 --- a/js/src/jsstr.cpp +++ b/js/src/jsstr.cpp @@ -74,7 +74,7 @@ ArgToRootedString(JSContext *cx, CallArgs &args, unsigned argno) JSString *str = ToString(cx, args[argno]); if (!str) - return NULL; + return nullptr; args[argno].setString(str); return str->ensureLinear(cx); @@ -397,7 +397,7 @@ str_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, if (!str1) return false; RootedValue value(cx, StringValue(str1)); - if (!JSObject::defineElement(cx, obj, uint32_t(slot), value, NULL, NULL, + if (!JSObject::defineElement(cx, obj, uint32_t(slot), value, nullptr, nullptr, STRING_ELEMENT_ATTRS)) { return false; @@ -429,7 +429,7 @@ const Class StringObject::class_ = { static JS_ALWAYS_INLINE JSString * ThisToStringForStringProto(JSContext *cx, CallReceiver call) { - JS_CHECK_RECURSION(cx, return NULL); + JS_CHECK_RECURSION(cx, return nullptr); if (call.thisv().isString()) return call.thisv().toString(); @@ -445,14 +445,14 @@ ThisToStringForStringProto(JSContext *cx, CallReceiver call) } } } else if (call.thisv().isNullOrUndefined()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CONVERT_TO, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO, call.thisv().isNull() ? "null" : "undefined", "object"); - return NULL; + return nullptr; } JSString *str = ToStringSlow(cx, call.thisv()); if (!str) - return NULL; + return nullptr; call.setThis(StringValue(str)); return str; @@ -601,11 +601,11 @@ DoSubstr(JSContext *cx, JSString *str, size_t begin, size_t len) RootedString lhs(cx, js_NewDependentString(cx, ropeRoot->leftChild(), begin, lhsLength)); if (!lhs) - return NULL; + return nullptr; RootedString rhs(cx, js_NewDependentString(cx, ropeRoot->rightChild(), 0, rhsLength)); if (!rhs) - return NULL; + return nullptr; return JSRope::new_(cx, lhs, rhs, len); } @@ -678,18 +678,18 @@ js_toLowerCase(JSContext *cx, JSString *str) size_t n = str->length(); const jschar *s = str->getChars(cx); if (!s) - return NULL; + return nullptr; jschar *news = cx->pod_malloc(n + 1); if (!news) - return NULL; + return nullptr; for (size_t i = 0; i < n; i++) news[i] = unicode::ToLowerCase(s[i]); news[n] = 0; str = js_NewString(cx, news, n); if (!str) { js_free(news); - return NULL; + return nullptr; } return str; } @@ -746,17 +746,17 @@ js_toUpperCase(JSContext *cx, JSString *str) size_t n = str->length(); const jschar *s = str->getChars(cx); if (!s) - return NULL; + return nullptr; jschar *news = cx->pod_malloc(n + 1); if (!news) - return NULL; + return nullptr; for (size_t i = 0; i < n; i++) news[i] = unicode::ToUpperCase(s[i]); news[n] = 0; str = js_NewString(cx, news, n); if (!str) { js_free(news); - return NULL; + return nullptr; } return str; } @@ -1120,7 +1120,7 @@ class StringSegmentRange } bool empty() const { - return cur == NULL; + return cur == nullptr; } JSLinearString *front() const { @@ -1131,7 +1131,7 @@ class StringSegmentRange JS_WARN_UNUSED_RESULT bool popFront() { JS_ASSERT(!empty()); if (stack.empty()) { - cur = NULL; + cur = nullptr; return true; } return settle(stack.popCopy()); @@ -1665,7 +1665,7 @@ class MOZ_STACK_CLASS StringRegExpGuard { StringBuffer sb(cx); if (!sb.reserve(patstr->length())) - return NULL; + return nullptr; static const jschar ESCAPE_CHAR = '\\'; const jschar *chars = patstr->chars(); @@ -1673,10 +1673,10 @@ class MOZ_STACK_CLASS StringRegExpGuard for (const jschar *it = chars; it != chars + len; ++it) { if (IsRegExpMetaChar(*it)) { if (!sb.append(ESCAPE_CHAR) || !sb.append(*it)) - return NULL; + return nullptr; } else { if (!sb.append(*it)) - return NULL; + return nullptr; } } return sb.finishAtom(); @@ -1712,31 +1712,32 @@ class MOZ_STACK_CLASS StringRegExpGuard } /* - * Attempt to match |patstr| to |textstr|. A flags argument, metachars in the - * pattern string, or a lengthy pattern string can thwart this process. + * Attempt to match |patstr| to |textstr|. A flags argument, metachars in + * the pattern string, or a lengthy pattern string can thwart this process. * * |checkMetaChars| looks for regexp metachars in the pattern string. * * Return whether flat matching could be used. * - * N.B. tryFlatMatch returns NULL on OOM, so the caller must check cx->isExceptionPending(). + * N.B. tryFlatMatch returns nullptr on OOM, so the caller must check + * cx->isExceptionPending(). */ const FlatMatch * tryFlatMatch(JSContext *cx, JSString *textstr, unsigned optarg, unsigned argc, bool checkMetaChars = true) { if (re_.initialized()) - return NULL; + return nullptr; fm.pat = fm.patstr->chars(); fm.patlen = fm.patstr->length(); if (optarg < argc) - return NULL; + return nullptr; if (checkMetaChars && (fm.patlen > MAX_FLAT_PAT_LEN || HasRegExpMetaChars(fm.pat, fm.patlen))) { - return NULL; + return nullptr; } /* @@ -1745,7 +1746,7 @@ class MOZ_STACK_CLASS StringRegExpGuard */ if (textstr->isRope()) { if (!RopeMatch(cx, textstr, fm.pat, fm.patlen, &fm.match_)) - return NULL; + return nullptr; } else { const jschar *text = textstr->asLinear().chars(); size_t textlen = textstr->length(); @@ -1767,7 +1768,7 @@ class MOZ_STACK_CLASS StringRegExpGuard if (!opt) return false; } else { - opt = NULL; + opt = nullptr; } Rooted patstr(cx); @@ -1795,7 +1796,7 @@ class MOZ_STACK_CLASS StringRegExpGuard RegExpShared ®Exp() { return *re_; } - bool regExpIsObject() { return obj_ != NULL; } + bool regExpIsObject() { return obj_ != nullptr; } HandleObject regExpObject() { JS_ASSERT(regExpIsObject()); return obj_; @@ -2252,7 +2253,7 @@ FindReplaceLength(JSContext *cx, RegExpStatics *res, ReplaceData &rdata, size_t * Couldn't handle this property, fall through and despecialize to the * general lambda case. */ - rdata.elembase = NULL; + rdata.elembase = nullptr; } if (rdata.lambda) { @@ -2581,7 +2582,7 @@ FlattenSubstrings(JSContext *cx, const jschar *chars, JSShortString *str = js_NewGCShortString(cx); if (!str) - return NULL; + return nullptr; jschar *buf = str->init(outputLen); size_t pos = 0; @@ -2607,12 +2608,12 @@ AppendSubstrings(JSContext *cx, Handle stableStr, const jschar *chars = stableStr->getChars(cx); if (!chars) - return NULL; + return nullptr; /* Collect substrings into a rope */ size_t i = 0; RopeBuilder rope(cx); - RootedString part(cx, NULL); + RootedString part(cx, nullptr); while (i < rangesLen) { /* Find maximum range that fits in JSShortString */ @@ -2635,7 +2636,7 @@ AppendSubstrings(JSContext *cx, Handle stableStr, } if (!part) - return NULL; + return nullptr; /* Appending to the rope permanently roots the substring. */ rope.append(part); @@ -2911,15 +2912,15 @@ js::str_replace(JSContext *cx, unsigned argc, Value *vp) /* Extract replacement string/function. */ if (args.length() >= ReplaceOptArg && js_IsCallable(args[1])) { rdata.lambda = &args[1].toObject(); - rdata.elembase = NULL; - rdata.repstr = NULL; - rdata.dollar = rdata.dollarEnd = NULL; + rdata.elembase = nullptr; + rdata.repstr = nullptr; + rdata.dollar = rdata.dollarEnd = nullptr; if (!LambdaIsGetElem(cx, *rdata.lambda, &rdata.elembase)) return false; } else { - rdata.lambda = NULL; - rdata.elembase = NULL; + rdata.lambda = nullptr; + rdata.elembase = nullptr; rdata.repstr = ArgToRootedString(cx, args, 1); if (!rdata.repstr) return false; @@ -3008,7 +3009,7 @@ SplitHelper(JSContext *cx, Handle str, uint32_t limit, const Ma /* Step 11. */ if (strLength == 0) { if (!splitMatch(cx, str, 0, &result)) - return NULL; + return nullptr; /* * NB: Unlike in the non-empty string case, it's perfectly fine @@ -3037,7 +3038,7 @@ SplitHelper(JSContext *cx, Handle str, uint32_t limit, const Ma while (index < strLength) { /* Step 13(a). */ if (!splitMatch(cx, str, index, &result)) - return NULL; + return nullptr; /* * Step 13(b). @@ -3078,7 +3079,7 @@ SplitHelper(JSContext *cx, Handle str, uint32_t limit, const Ma size_t subLength = size_t(endIndex - sepLength - lastEndIndex); JSString *sub = js_NewDependentString(cx, str, lastEndIndex, subLength); if (!sub || !splits.append(StringValue(sub))) - return NULL; + return nullptr; /* Step 13(c)(iii)(4). */ if (splits.length() == limit) @@ -3098,12 +3099,12 @@ SplitHelper(JSContext *cx, Handle str, uint32_t limit, const Ma res->getParen(i + 1, &parsub); sub = js_NewStringCopyN(cx, parsub.chars, parsub.length); if (!sub || !splits.append(StringValue(sub))) - return NULL; + return nullptr; } else { /* Only string entries have been accounted for so far. */ - AddTypeProperty(cx, type, NULL, UndefinedValue()); + AddTypeProperty(cx, type, nullptr, UndefinedValue()); if (!splits.append(UndefinedValue())) - return NULL; + return nullptr; } /* Step 13(c)(iii)(7)(d). */ @@ -3119,7 +3120,7 @@ SplitHelper(JSContext *cx, Handle str, uint32_t limit, const Ma /* Steps 14-15. */ JSString *sub = js_NewDependentString(cx, str, lastEndIndex, strLength - lastEndIndex); if (!sub || !splits.append(StringValue(sub))) - return NULL; + return nullptr; /* Step 16. */ return NewDenseCopiedArray(cx, splits.length(), splits.begin()); @@ -3211,7 +3212,7 @@ js::str_split(JSContext *cx, unsigned argc, Value *vp) RootedTypeObject type(cx, GetTypeCallerInitObject(cx, JSProto_Array)); if (!type) return false; - AddTypeProperty(cx, type, NULL, Type::StringType()); + AddTypeProperty(cx, type, nullptr, Type::StringType()); /* Step 5: Use the second argument as the split limit, if given. */ uint32_t limit; @@ -3523,19 +3524,19 @@ tagify_value(JSContext *cx, CallArgs args, const char *begin, const char *end) static bool str_bold(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "b", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "b", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool str_italics(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "i", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "i", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool str_fixed(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "tt", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "tt", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool @@ -3565,37 +3566,37 @@ str_anchor(JSContext *cx, unsigned argc, Value *vp) static bool str_strike(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "strike", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "strike", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool str_small(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "small", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "small", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool str_big(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "big", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "big", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool str_blink(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "blink", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "blink", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool str_sup(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "sup", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "sup", NullPtr(), nullptr, CallReceiverFromVp(vp)); } static bool str_sub(JSContext *cx, unsigned argc, Value *vp) { - return tagify(cx, "sub", NullPtr(), NULL, CallReceiverFromVp(vp)); + return tagify(cx, "sub", NullPtr(), nullptr, CallReceiverFromVp(vp)); } #endif /* JS_HAS_STR_HTML_HELPERS */ @@ -3757,32 +3758,32 @@ js_InitStringClass(JSContext *cx, HandleObject obj) Rooted empty(cx, cx->runtime()->emptyString); RootedObject proto(cx, global->createBlankPrototype(cx, &StringObject::class_)); if (!proto || !proto->as().init(cx, empty)) - return NULL; + return nullptr; /* Now create the String function. */ RootedFunction ctor(cx); ctor = global->createConstructor(cx, js_String, cx->names().String, 1); if (!ctor) - return NULL; + return nullptr; if (!LinkConstructorAndPrototype(cx, ctor, proto)) - return NULL; + return nullptr; - if (!DefinePropertiesAndBrand(cx, proto, NULL, string_methods) || - !DefinePropertiesAndBrand(cx, ctor, NULL, string_static_methods)) + if (!DefinePropertiesAndBrand(cx, proto, nullptr, string_methods) || + !DefinePropertiesAndBrand(cx, ctor, nullptr, string_static_methods)) { - return NULL; + return nullptr; } if (!DefineConstructorAndPrototype(cx, global, JSProto_String, ctor, proto)) - return NULL; + return nullptr; /* * Define escape/unescape, the URI encode/decode functions, and maybe * uneval on the global object. */ if (!JS_DefineFunctions(cx, global, string_functions)) - return NULL; + return nullptr; return proto; } @@ -3808,7 +3809,7 @@ js_NewDependentString(JSContext *cx, JSString *baseArg, size_t start, size_t len JSLinearString *base = baseArg->ensureLinear(cx); if (!base) - return NULL; + return nullptr; if (start == 0 && length == base->length()) return base; @@ -3830,7 +3831,7 @@ js_NewStringCopyN(ExclusiveContext *cx, const jschar *s, size_t n) jschar *news = cx->pod_malloc(n + 1); if (!news) - return NULL; + return nullptr; js_strncpy(news, s, n); news[n] = 0; JSFlatString *str = js_NewString(cx, news, n); @@ -3854,7 +3855,7 @@ js_NewStringCopyN(ThreadSafeContext *cx, const char *s, size_t n) jschar *chars = InflateString(cx, s, &n); if (!chars) - return NULL; + return nullptr; JSFlatString *str = js_NewString(cx, chars, n); if (!str) js_free(chars); @@ -3878,7 +3879,7 @@ js_NewStringCopyZ(ExclusiveContext *cx, const jschar *s) size_t m = (n + 1) * sizeof(jschar); jschar *news = (jschar *) cx->malloc_(m); if (!news) - return NULL; + return nullptr; js_memcpy(news, s, m); JSFlatString *str = js_NewString(cx, news, n); if (!str) @@ -3915,10 +3916,10 @@ js_ValueToPrintable(JSContext *cx, const Value &vArg, JSAutoByteString *bytes, b else str = ToString(cx, v); if (!str) - return NULL; + return nullptr; str = js_QuoteString(cx, str, 0); if (!str) - return NULL; + return nullptr; return bytes->encodeLatin1(cx, str); } @@ -3932,10 +3933,10 @@ js::ToStringSlow(ExclusiveContext *cx, typename MaybeRooted::Han Value v = arg; if (!v.isPrimitive()) { if (!cx->shouldBeJSContext() || !allowGC) - return NULL; + return nullptr; RootedValue v2(cx, v); if (!ToPrimitive(cx->asJSContext(), JSTYPE_STRING, &v2)) - return NULL; + return nullptr; v = v2; } @@ -3965,7 +3966,7 @@ js::ToStringSlow(ExclusiveContext *cx, Value arg); JSString * js::ValueToSource(JSContext *cx, HandleValue v) { - JS_CHECK_RECURSION(cx, return NULL); + JS_CHECK_RECURSION(cx, return nullptr); assertSameCompartment(cx, v); if (v.isUndefined()) @@ -3986,11 +3987,11 @@ js::ValueToSource(JSContext *cx, HandleValue v) RootedValue fval(cx); RootedObject obj(cx, &v.toObject()); if (!JSObject::getProperty(cx, obj, obj, cx->names().toSource, &fval)) - return NULL; + return nullptr; if (js_IsCallable(fval)) { RootedValue rval(cx); - if (!Invoke(cx, ObjectValue(*obj), fval, 0, NULL, &rval)) - return NULL; + if (!Invoke(cx, ObjectValue(*obj), fval, 0, nullptr, &rval)) + return nullptr; return ToString(cx, rval); } @@ -4103,7 +4104,7 @@ js_strdup(js::ThreadSafeContext *cx, const jschar *s) size_t n = js_strlen(s); jschar *ret = cx->pod_malloc(n + 1); if (!ret) - return NULL; + return nullptr; js_strncpy(ret, s, n); ret[n] = '\0'; return ret; @@ -4117,7 +4118,7 @@ js_strchr_limit(const jschar *s, jschar c, const jschar *limit) return (jschar *)s; s++; } - return NULL; + return nullptr; } jschar * @@ -4141,7 +4142,7 @@ js::InflateString(ThreadSafeContext *cx, const char *bytes, size_t *lengthp) // For compatibility with callers of JS_DecodeBytes we must zero lengthp // on errors. *lengthp = 0; - return NULL; + return nullptr; } bool @@ -4154,7 +4155,7 @@ js::DeflateStringToBuffer(JSContext *maybecx, const jschar *src, size_t srclen, dst[i] = (char) src[i]; if (maybecx) { AutoSuppressGC suppress(maybecx); - JS_ReportErrorNumber(maybecx, js_GetErrorMessage, NULL, + JS_ReportErrorNumber(maybecx, js_GetErrorMessage, nullptr, JSMSG_BUFFER_TOO_SMALL); } return false; @@ -4344,7 +4345,7 @@ Encode(JSContext *cx, Handle str, const bool *unescapedSet, return false; } else { if ((c >= 0xDC00) && (c <= 0xDFFF)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_URI, NULL); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_URI, nullptr); return false; } uint32_t v; @@ -4353,14 +4354,14 @@ Encode(JSContext *cx, Handle str, const bool *unescapedSet, } else { k++; if (k == length) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, - JSMSG_BAD_URI, NULL); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, + JSMSG_BAD_URI, nullptr); return false; } jschar c2 = chars[k]; if ((c2 < 0xDC00) || (c2 > 0xDFFF)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, - JSMSG_BAD_URI, NULL); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, + JSMSG_BAD_URI, nullptr); return false; } v = ((c - 0xD800) << 10) + (c2 - 0xDC00) + 0x10000; @@ -4453,7 +4454,7 @@ Decode(JSContext *cx, Handle str, const bool *reservedSet, Muta return TransferBufferToString(sb, rval); report_bad_uri: - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_URI); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_URI); /* FALL THROUGH */ return false; @@ -4478,7 +4479,7 @@ str_decodeURI_Component(JSContext *cx, unsigned argc, Value *vp) if (!str) return false; - return Decode(cx, str, NULL, args.rval()); + return Decode(cx, str, nullptr, args.rval()); } static bool @@ -4500,7 +4501,7 @@ str_encodeURI_Component(JSContext *cx, unsigned argc, Value *vp) if (!str) return false; - return Encode(cx, str, js_isUriUnescaped, NULL, args.rval()); + return Encode(cx, str, js_isUriUnescaped, nullptr, args.rval()); } /* @@ -4554,7 +4555,7 @@ js::PutEscapedStringImpl(char *buffer, size_t bufferSize, FILE *fp, const jschar JS_ASSERT_IF(fp, !buffer); if (bufferSize == 0) - buffer = NULL; + buffer = nullptr; else bufferSize--; @@ -4638,7 +4639,7 @@ js::PutEscapedStringImpl(char *buffer, size_t bufferSize, FILE *fp, const jschar buffer[n] = c; } else { buffer[n] = '\0'; - buffer = NULL; + buffer = nullptr; } } else if (fp) { if (fputc(c, fp) < 0) diff --git a/js/src/jsstr.h b/js/src/jsstr.h index 0a8cd225e00e..a712d43043b1 100644 --- a/js/src/jsstr.h +++ b/js/src/jsstr.h @@ -318,7 +318,7 @@ PutEscapedStringImpl(char *buffer, size_t bufferSize, FILE *fp, const jschar *ch inline size_t PutEscapedString(char *buffer, size_t size, JSLinearString *str, uint32_t quote) { - size_t n = PutEscapedStringImpl(buffer, size, NULL, str, quote); + size_t n = PutEscapedStringImpl(buffer, size, nullptr, str, quote); /* PutEscapedStringImpl can only fail with a file. */ JS_ASSERT(n != size_t(-1)); @@ -328,7 +328,7 @@ PutEscapedString(char *buffer, size_t size, JSLinearString *str, uint32_t quote) inline size_t PutEscapedString(char *buffer, size_t bufferSize, const jschar *chars, size_t length, uint32_t quote) { - size_t n = PutEscapedStringImpl(buffer, bufferSize, NULL, chars, length, quote); + size_t n = PutEscapedStringImpl(buffer, bufferSize, nullptr, chars, length, quote); /* PutEscapedStringImpl can only fail with a file. */ JS_ASSERT(n != size_t(-1)); @@ -343,7 +343,7 @@ PutEscapedString(char *buffer, size_t bufferSize, const jschar *chars, size_t le inline bool FileEscapedString(FILE *fp, JSLinearString *str, uint32_t quote) { - return PutEscapedStringImpl(NULL, 0, fp, str, quote) != size_t(-1); + return PutEscapedStringImpl(nullptr, 0, fp, str, quote) != size_t(-1); } bool diff --git a/js/src/jsutil.cpp b/js/src/jsutil.cpp index 904d05d37922..5c3ef97aed92 100644 --- a/js/src/jsutil.cpp +++ b/js/src/jsutil.cpp @@ -46,10 +46,10 @@ Compressor::Compressor(const unsigned char *inp, size_t inplen) outbytes(0) { JS_ASSERT(inplen > 0); - zs.opaque = NULL; + zs.opaque = nullptr; zs.next_in = (Bytef *)inp; zs.avail_in = 0; - zs.next_out = NULL; + zs.next_out = nullptr; zs.avail_out = 0; zs.zalloc = zlib_alloc; zs.zfree = zlib_free; @@ -123,7 +123,7 @@ js::DecompressString(const unsigned char *inp, size_t inplen, unsigned char *out z_stream zs; zs.zalloc = zlib_alloc; zs.zfree = zlib_free; - zs.opaque = NULL; + zs.opaque = nullptr; zs.next_in = (Bytef *)inp; zs.avail_in = inplen; zs.next_out = out; diff --git a/js/src/jswatchpoint.cpp b/js/src/jswatchpoint.cpp index 7169b16d4588..32a68cc23dd8 100644 --- a/js/src/jswatchpoint.cpp +++ b/js/src/jswatchpoint.cpp @@ -264,7 +264,7 @@ WatchpointMap::trace(WeakMapTracer *trc) { for (Map::Range r = map.all(); !r.empty(); r.popFront()) { Map::Entry &entry = r.front(); - trc->callback(trc, NULL, + trc->callback(trc, nullptr, entry.key.object.get(), JSTRACE_OBJECT, entry.value.closure.get(), JSTRACE_OBJECT); } diff --git a/js/src/jsweakmap.cpp b/js/src/jsweakmap.cpp index 9271ddf767d9..0e62fc735619 100644 --- a/js/src/jsweakmap.cpp +++ b/js/src/jsweakmap.cpp @@ -65,10 +65,10 @@ WeakMapBase::traceAllMappings(WeakMapTracer *tracer) void WeakMapBase::resetCompartmentWeakMapList(JSCompartment *c) { - JS_ASSERT(WeakMapNotInList != NULL); + JS_ASSERT(WeakMapNotInList != nullptr); WeakMapBase *m = c->gcWeakMapList; - c->gcWeakMapList = NULL; + c->gcWeakMapList = nullptr; while (m) { WeakMapBase *n = m->next; m->next = WeakMapNotInList; @@ -117,8 +117,8 @@ static JSObject * GetKeyArg(JSContext *cx, CallArgs &args) { if (args[0].isPrimitive()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NOT_NONNULL_OBJECT); - return NULL; + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NOT_NONNULL_OBJECT); + return nullptr; } return &args[0].toObject(); } @@ -135,7 +135,7 @@ WeakMap_has_impl(JSContext *cx, CallArgs args) JS_ASSERT(IsWeakMap(args.thisv())); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "WeakMap.has", "0", "s"); return false; } @@ -188,7 +188,7 @@ WeakMap_get_impl(JSContext *cx, CallArgs args) JS_ASSERT(IsWeakMap(args.thisv())); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "WeakMap.get", "0", "s"); return false; } @@ -224,7 +224,7 @@ WeakMap_delete_impl(JSContext *cx, CallArgs args) JS_ASSERT(IsWeakMap(args.thisv())); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "WeakMap.delete", "0", "s"); return false; } @@ -261,7 +261,7 @@ TryPreserveReflector(JSContext *cx, HandleObject obj) { JS_ASSERT(cx->runtime()->preserveWrapperCallback); if (!cx->runtime()->preserveWrapperCallback(cx, obj)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_WEAKMAP_KEY); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_WEAKMAP_KEY); return false; } } @@ -274,7 +274,7 @@ WeakMap_set_impl(JSContext *cx, CallArgs args) JS_ASSERT(IsWeakMap(args.thisv())); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "WeakMap.set", "0", "s"); return false; } @@ -331,7 +331,7 @@ JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *objArg, JSObject **re RootedObject obj(cx, objArg); obj = UncheckedUnwrap(obj); if (!obj || !obj->is()) { - *ret = NULL; + *ret = nullptr; return true; } RootedObject arr(cx, NewDenseEmptyArray(cx)); @@ -398,10 +398,10 @@ const Class WeakMapObject::class_ = { JS_ResolveStub, JS_ConvertStub, WeakMap_finalize, - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* construct */ - NULL, /* xdrObject */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* construct */ + nullptr, /* xdrObject */ WeakMap_mark }; @@ -423,20 +423,20 @@ js_InitWeakMapClass(JSContext *cx, HandleObject obj) RootedObject weakMapProto(cx, global->createBlankPrototype(cx, &WeakMapObject::class_)); if (!weakMapProto) - return NULL; + return nullptr; RootedFunction ctor(cx, global->createConstructor(cx, WeakMap_construct, cx->names().WeakMap, 0)); if (!ctor) - return NULL; + return nullptr; if (!LinkConstructorAndPrototype(cx, ctor, weakMapProto)) - return NULL; + return nullptr; - if (!DefinePropertiesAndBrand(cx, weakMapProto, NULL, weak_map_methods)) - return NULL; + if (!DefinePropertiesAndBrand(cx, weakMapProto, nullptr, weak_map_methods)) + return nullptr; if (!DefineConstructorAndPrototype(cx, global, JSProto_WeakMap, ctor, weakMapProto)) - return NULL; + return nullptr; return weakMapProto; } diff --git a/js/src/jsweakmap.h b/js/src/jsweakmap.h index 8df2f74fc22c..4e00ec8b07c1 100644 --- a/js/src/jsweakmap.h +++ b/js/src/jsweakmap.h @@ -117,9 +117,10 @@ class WeakMapBase { private: // Link in a list of WeakMaps to mark iteratively and sweep in this garbage // collection, headed by JSCompartment::gcWeakMapList. The last element of - // the list has NULL as its next. Maps not in the list have WeakMapNotInList - // as their next. We must distinguish these cases to avoid creating - // infinite lists when a weak map gets traced twice due to delayed marking. + // the list has nullptr as its next. Maps not in the list have + // WeakMapNotInList as their next. We must distinguish these cases to + // avoid creating infinite lists when a weak map gets traced twice due to + // delayed marking. WeakMapBase *next; }; @@ -132,7 +133,7 @@ class WeakMap : public HashMap, publ typedef typename Base::Enum Enum; typedef typename Base::Range Range; - explicit WeakMap(JSContext *cx, JSObject *memOf=NULL) + explicit WeakMap(JSContext *cx, JSObject *memOf = nullptr) : Base(cx->runtime()), WeakMapBase(memOf, cx->compartment()) { } private: @@ -192,7 +193,7 @@ class WeakMap : public HashMap, publ gc::Mark(trc, &e.front().value, "WeakMap entry value"); markedAny = true; } - key.unsafeSet(NULL); + key.unsafeSet(nullptr); } return markedAny; } @@ -213,7 +214,7 @@ class WeakMap : public HashMap, publ assertEntriesNotAboutToBeFinalized(); } - /* memberOf can be NULL, which means that the map is not part of a JSObject. */ + /* memberOf can be nullptr, which means that the map is not part of a JSObject. */ void traceMappings(WeakMapTracer *tracer) { for (Range r = Base::all(); !r.empty(); r.popFront()) { gc::Cell *key = gc::ToMarkable(r.front().key); diff --git a/js/src/jsworkers.cpp b/js/src/jsworkers.cpp index 65dc50c94970..e2ba76f78d9c 100644 --- a/js/src/jsworkers.cpp +++ b/js/src/jsworkers.cpp @@ -30,7 +30,7 @@ js::EnsureWorkerThreadsInitialized(ExclusiveContext *cx) // If 'cx' is not a JSContext, we are already off the main thread and the // worker threads would have already been initialized. if (!cx->isJSContext()) { - JS_ASSERT(cx->workerThreadState() != NULL); + JS_ASSERT(cx->workerThreadState() != nullptr); return true; } @@ -44,7 +44,7 @@ js::EnsureWorkerThreadsInitialized(ExclusiveContext *cx) if (!rt->workerThreadState->init(rt)) { js_delete(rt->workerThreadState); - rt->workerThreadState = NULL; + rt->workerThreadState = nullptr; return false; } @@ -55,9 +55,9 @@ bool js::StartOffThreadAsmJSCompile(ExclusiveContext *cx, AsmJSParallelTask *asmData) { // Threads already initialized by the AsmJS compiler. - JS_ASSERT(cx->workerThreadState() != NULL); + JS_ASSERT(cx->workerThreadState() != nullptr); JS_ASSERT(asmData->mir); - JS_ASSERT(asmData->lir == NULL); + JS_ASSERT(asmData->lir == nullptr); WorkerThreadState &state = *cx->workerThreadState(); JS_ASSERT(state.numThreads); @@ -171,7 +171,7 @@ static const JSClass workerGlobalClass = { JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, - JS_ConvertStub, NULL + JS_ConvertStub, nullptr }; ParseTask::ParseTask(ExclusiveContext *cx, const CompileOptions &options, @@ -179,7 +179,7 @@ ParseTask::ParseTask(ExclusiveContext *cx, const CompileOptions &options, JS::OffThreadCompileCallback callback, void *callbackData) : cx(cx), options(options), chars(chars), length(length), alloc(JSRuntime::TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE), scopeChain(scopeChain), - callback(callback), callbackData(callbackData), script(NULL), errors(cx) + callback(callback), callbackData(callbackData), script(nullptr), errors(cx) { JSRuntime *rt = scopeChain->runtimeFromMainThread(); @@ -225,7 +225,7 @@ js::StartOffThreadParseScript(JSContext *cx, const CompileOptions &options, JS::CompartmentOptions compartmentOptions(cx->compartment()->options()); compartmentOptions.setZone(JS::FreshZone); - JSObject *global = JS_NewGlobalObject(cx, &workerGlobalClass, NULL, + JSObject *global = JS_NewGlobalObject(cx, &workerGlobalClass, nullptr, JS::FireOnNewGlobalHook, compartmentOptions); if (!global) return false; @@ -259,7 +259,7 @@ js::StartOffThreadParseScript(JSContext *cx, const CompileOptions &options, cx->runtime()->setUsedByExclusiveThread(global->zone()); ScopedJSDeletePtr workercx( - cx->new_(cx->runtime(), (PerThreadData *) NULL, + cx->new_(cx->runtime(), (PerThreadData *) nullptr, ThreadSafeContext::Context_Exclusive)); if (!workercx) return false; @@ -350,7 +350,7 @@ WorkerThreadState::init(JSRuntime *rt) for (size_t j = 0; j < numThreads; j++) threads[j].destroy(); js_free(threads); - threads = NULL; + threads = nullptr; numThreads = 0; return false; } @@ -371,13 +371,13 @@ WorkerThreadState::cleanup(JSRuntime *rt) for (size_t i = 0; i < numThreads; i++) threads[i].destroy(); js_free(threads); - threads = NULL; + threads = nullptr; numThreads = 0; } // Clean up any parse tasks which haven't been finished yet. while (!parseFinishedList.empty()) - finishParseTask(/* maybecx = */ NULL, rt, parseFinishedList[0]); + finishParseTask(/* maybecx = */ nullptr, rt, parseFinishedList[0]); } WorkerThreadState::~WorkerThreadState() @@ -410,7 +410,7 @@ WorkerThreadState::unlock() { JS_ASSERT(isLocked()); #ifdef DEBUG - lockOwner = NULL; + lockOwner = nullptr; #endif PR_Unlock(workerLock); } @@ -428,7 +428,7 @@ WorkerThreadState::wait(CondVar which, uint32_t millis) { JS_ASSERT(isLocked()); #ifdef DEBUG - lockOwner = NULL; + lockOwner = nullptr; #endif DebugOnly status = PR_WaitCondVar((which == CONSUMER) ? consumerWakeup : producerWakeup, @@ -523,7 +523,7 @@ CallNewScriptHookForAllScripts(JSContext *cx, HandleScript script) JSScript * WorkerThreadState::finishParseTask(JSContext *maybecx, JSRuntime *rt, void *token) { - ParseTask *parseTask = NULL; + ParseTask *parseTask = nullptr; // The token is a ParseTask* which should be in the finished list. // Find and remove its entry. @@ -581,7 +581,7 @@ WorkerThreadState::finishParseTask(JSContext *maybecx, JSRuntime *rt, void *toke if (script) { // The Debugger only needs to be told about the topmost script that was compiled. - GlobalObject *compileAndGoGlobal = NULL; + GlobalObject *compileAndGoGlobal = nullptr; if (script->compileAndGo) compileAndGoGlobal = &script->global(); Debugger::onNewScript(maybecx, script, compileAndGoGlobal); @@ -658,7 +658,7 @@ WorkerThread::handleAsmJSWorkload(WorkerThreadState &state) // On failure, signal parent for harvesting in CancelOutstandingJobs(). if (!success) { - asmData = NULL; + asmData = nullptr; state.noteAsmJSFailure(asmData->func); state.notifyAll(WorkerThreadState::CONSUMER); return; @@ -666,7 +666,7 @@ WorkerThread::handleAsmJSWorkload(WorkerThreadState &state) // On success, move work to the finished list. state.asmJSFinishedList.append(asmData); - asmData = NULL; + asmData = nullptr; // Notify the main thread in case it's blocked waiting for a LifoAlloc. state.notifyAll(WorkerThreadState::CONSUMER); @@ -699,7 +699,7 @@ WorkerThread::handleIonWorkload(WorkerThreadState &state) state.lock(); FinishOffThreadIonCompile(ionBuilder); - ionBuilder = NULL; + ionBuilder = nullptr; // Notify the main thread in case it is waiting for the compilation to finish. state.notifyAll(WorkerThreadState::CONSUMER); @@ -754,7 +754,7 @@ WorkerThread::handleParseWorkload(WorkerThreadState &state) // migrate it into the correct compartment. state.parseFinishedList.append(parseTask); - parseTask = NULL; + parseTask = nullptr; // Notify the main thread in case it is waiting for the parse/emit to finish. state.notifyAll(WorkerThreadState::CONSUMER); @@ -776,8 +776,8 @@ WorkerThread::handleCompressionWorkload(WorkerThreadState &state) compressionTask->setOOM(); } - compressionTask->workerThread = NULL; - compressionTask = NULL; + compressionTask->workerThread = nullptr; + compressionTask = nullptr; // Notify the main thread in case it is waiting for the compression to finish. state.notifyAll(WorkerThreadState::CONSUMER); @@ -834,8 +834,8 @@ SourceCompressionTask::complete() if (!oom) cx->updateMallocCounter(ss->computedSizeOfData()); - ss = NULL; - chars = NULL; + ss = nullptr; + chars = nullptr; } if (oom) { js_ReportOutOfMemory(cx); @@ -858,7 +858,7 @@ WorkerThreadState::compressionTaskForSource(ScriptSource *ss) if (task && task->source() == ss) return task; } - return NULL; + return nullptr; } const jschar * @@ -868,7 +868,7 @@ ScriptSource::getOffThreadCompressionChars(ExclusiveContext *cx) if (ready()) { // Compression has already finished on the source. - return NULL; + return nullptr; } WorkerThreadState &state = *cx->workerThreadState(); @@ -883,7 +883,7 @@ ScriptSource::getOffThreadCompressionChars(ExclusiveContext *cx) // queries on the worker thread state when getting the chars. ready_ = true; - return NULL; + return nullptr; } void @@ -1083,7 +1083,7 @@ const jschar * ScriptSource::getOffThreadCompressionChars(ExclusiveContext *cx) { JS_ASSERT(ready()); - return NULL; + return nullptr; } AutoPauseWorkersForGC::AutoPauseWorkersForGC(JSRuntime *rt MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL) diff --git a/js/src/jsworkers.h b/js/src/jsworkers.h index 2bb73232d9d6..73d042f6bd7e 100644 --- a/js/src/jsworkers.h +++ b/js/src/jsworkers.h @@ -122,7 +122,7 @@ class WorkerThreadState } void resetAsmJSFailureState() { numAsmJSFailedJobs = 0; - asmJSFailedFunction = NULL; + asmJSFailedFunction = nullptr; } void *maybeAsmJSFailedFunction() const { return asmJSFailedFunction; @@ -235,7 +235,7 @@ StartOffThreadIonCompile(JSContext *cx, jit::IonBuilder *builder); /* * Cancel a scheduled or in progress Ion compilation for script. If script is - * NULL, all compilations for the compartment are cancelled. + * nullptr, all compilations for the compartment are cancelled. */ void CancelOffThreadIonCompile(JSCompartment *compartment, JSScript *script); @@ -377,13 +377,13 @@ struct AsmJSParallelTask unsigned compileTime; AsmJSParallelTask(size_t defaultChunkSize) - : lifo(defaultChunkSize), func(NULL), mir(NULL), lir(NULL), compileTime(0) + : lifo(defaultChunkSize), func(nullptr), mir(nullptr), lir(nullptr), compileTime(0) { } void init(void *func, jit::MIRGenerator *mir) { this->func = func; this->mir = mir; - this->lir = NULL; + this->lir = nullptr; } }; #endif @@ -451,10 +451,10 @@ struct SourceCompressionTask public: explicit SourceCompressionTask(ExclusiveContext *cx) - : cx(cx), ss(NULL), chars(NULL), oom(false), abort_(0) + : cx(cx), ss(nullptr), chars(nullptr), oom(false), abort_(0) { #ifdef JS_WORKER_THREADS - workerThread = NULL; + workerThread = nullptr; #endif } diff --git a/js/src/jswrapper.cpp b/js/src/jswrapper.cpp index bf66c22f7660..95fb1acdeef1 100644 --- a/js/src/jswrapper.cpp +++ b/js/src/jswrapper.cpp @@ -109,7 +109,7 @@ js::UnwrapOneChecked(JSObject *obj, bool stopAtOuter) } Wrapper *handler = Wrapper::wrapperHandler(obj); - return handler->isSafeToUnwrap() ? Wrapper::wrappedObject(obj) : NULL; + return handler->isSafeToUnwrap() ? Wrapper::wrappedObject(obj) : nullptr; } bool @@ -364,7 +364,7 @@ struct AutoCloseIterator ~AutoCloseIterator() { if (obj) CloseIterator(cx, obj); } - void clear() { obj = NULL; } + void clear() { obj = nullptr; } private: JSContext *cx; @@ -550,10 +550,10 @@ CrossCompartmentWrapper::fun_toString(JSContext *cx, HandleObject wrapper, unsig AutoCompartment call(cx, wrappedObject(wrapper)); str = Wrapper::fun_toString(cx, wrapper, indent); if (!str) - return NULL; + return nullptr; } if (!cx->compartment()->wrap(cx, str.address())) - return NULL; + return nullptr; return str; } @@ -623,7 +623,7 @@ bool SecurityWrapper::preventExtensions(JSContext *cx, HandleObject wrapper) { // See above. - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNWRAP_DENIED); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNWRAP_DENIED); return false; } @@ -632,7 +632,7 @@ bool SecurityWrapper::enter(JSContext *cx, HandleObject wrapper, HandleId id, Wrapper::Action act, bool *bp) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNWRAP_DENIED); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNWRAP_DENIED); *bp = false; return false; } @@ -642,7 +642,7 @@ bool SecurityWrapper::nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNWRAP_DENIED); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNWRAP_DENIED); return false; } @@ -678,8 +678,8 @@ SecurityWrapper::defineProperty(JSContext *cx, HandleObject wrapper, { if (desc.getter() || desc.setter()) { JSString *str = IdToString(cx, id); - const jschar *prop = str ? str->getCharsZ(cx) : NULL; - JS_ReportErrorNumberUC(cx, js_GetErrorMessage, NULL, + const jschar *prop = str ? str->getCharsZ(cx) : nullptr; + JS_ReportErrorNumberUC(cx, js_GetErrorMessage, nullptr, JSMSG_ACCESSOR_DEF_DENIED, prop); return false; } @@ -707,7 +707,7 @@ DeadObjectProxy::isExtensible(JSContext *cx, HandleObject proxy, bool *extensibl bool DeadObjectProxy::preventExtensions(JSContext *cx, HandleObject proxy) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } @@ -715,7 +715,7 @@ bool DeadObjectProxy::getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, MutableHandle desc, unsigned flags) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } @@ -723,7 +723,7 @@ bool DeadObjectProxy::getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, MutableHandle desc, unsigned flags) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } @@ -731,7 +731,7 @@ bool DeadObjectProxy::defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, MutableHandle desc) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } @@ -739,56 +739,56 @@ bool DeadObjectProxy::getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::enumerate(JSContext *cx, HandleObject wrapper, AutoIdVector &props) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::call(JSContext *cx, HandleObject wrapper, const CallArgs &args) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::construct(JSContext *cx, HandleObject wrapper, const CallArgs &args) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::nativeCall(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::hasInstance(JSContext *cx, HandleObject proxy, MutableHandleValue v, bool *bp) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::objectClassIs(HandleObject obj, ESClassValue classValue, JSContext *cx) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } @@ -801,20 +801,20 @@ DeadObjectProxy::className(JSContext *cx, HandleObject wrapper) JSString * DeadObjectProxy::fun_toString(JSContext *cx, HandleObject proxy, unsigned indent) { - return NULL; + return nullptr; } bool DeadObjectProxy::regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::defaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } @@ -822,14 +822,14 @@ bool DeadObjectProxy::getElementIfPresent(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp, bool *present) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_DEAD_OBJECT); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); return false; } bool DeadObjectProxy::getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop) { - protop.set(NULL); + protop.set(nullptr); return true; } @@ -841,7 +841,7 @@ js::NewDeadProxyObject(JSContext *cx, JSObject *parent, const ProxyOptions &options) { return NewProxyObject(cx, &DeadObjectProxy::singleton, JS::NullHandleValue, - NULL, parent, options); + nullptr, parent, options); } bool diff --git a/js/src/jswrapper.h b/js/src/jswrapper.h index 9e1df683c4df..938db73ec8ad 100644 --- a/js/src/jswrapper.h +++ b/js/src/jswrapper.h @@ -234,7 +234,7 @@ IsWrapper(JSObject *obj) // previously wrapped. Otherwise, this returns the first object for // which JSObject::isWrapper returns false. JS_FRIEND_API(JSObject *) -UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = NULL); +UncheckedUnwrap(JSObject *obj, bool stopAtOuter = 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. Since checked diff --git a/js/src/shell/js.cpp b/js/src/shell/js.cpp index 25a7b32ee7f9..0015df08aeb2 100644 --- a/js/src/shell/js.cpp +++ b/js/src/shell/js.cpp @@ -144,25 +144,25 @@ CancelExecution(JSRuntime *rt); */ #ifdef JS_THREADSAFE -static PRLock *gWatchdogLock = NULL; -static PRCondVar *gWatchdogWakeup = NULL; -static PRThread *gWatchdogThread = NULL; +static PRLock *gWatchdogLock = nullptr; +static PRCondVar *gWatchdogWakeup = nullptr; +static PRThread *gWatchdogThread = nullptr; static bool gWatchdogHasTimeout = false; static int64_t gWatchdogTimeout = 0; -static PRCondVar *gSleepWakeup = NULL; +static PRCondVar *gSleepWakeup = nullptr; #else -static JSRuntime *gRuntime = NULL; +static JSRuntime *gRuntime = nullptr; #endif static int gExitCode = 0; static bool gQuitting = false; static bool gGotError = false; -static FILE *gErrFile = NULL; -static FILE *gOutFile = NULL; +static FILE *gErrFile = nullptr; +static FILE *gOutFile = nullptr; static bool reportWarnings = true; static bool compileOnly = false; @@ -255,7 +255,7 @@ GetLine(FILE *file, const char * prompt) if (errno == 251 || errno == 25 || errno == EINVAL) errno = 0; if (!linep) - return NULL; + return nullptr; if (linep[0] != '\0') add_history(linep); return linep; @@ -269,7 +269,7 @@ GetLine(FILE *file, const char * prompt) size = 80; buffer = (char *) malloc(size); if (!buffer) - return NULL; + return nullptr; char *current = buffer; while (fgets(current, size - len, file)) { len += strlen(current); @@ -284,7 +284,7 @@ GetLine(FILE *file, const char * prompt) char *tmp = (char *) realloc(buffer, size); if (!tmp) { free(buffer); - return NULL; + return nullptr; } buffer = tmp; } @@ -293,7 +293,7 @@ GetLine(FILE *file, const char * prompt) if (len && !ferror(file)) return buffer; free(buffer); - return NULL; + return nullptr; } static char * @@ -301,7 +301,7 @@ JSStringToUTF8(JSContext *cx, JSString *str) { JSLinearString *linear = str->ensureLinear(cx); if (!linear) - return NULL; + return nullptr; return TwoByteCharsToNewUTF8CharsZ(cx, linear->range()).c_str(); } @@ -323,12 +323,12 @@ NewContextData() { /* Prevent creation of new contexts after we have been canceled. */ if (gTimedOut) - return NULL; + return nullptr; JSShellContextData *data = (JSShellContextData *) calloc(sizeof(JSShellContextData), 1); if (!data) - return NULL; + return nullptr; data->startTime = PRMJ_Now(); return data; } @@ -353,7 +353,7 @@ ShellOperationCallback(JSContext *cx) bool result; if (!gTimeoutFunc.isNull()) { RootedValue returnedValue(cx); - if (!JS_CallFunctionValue(cx, NULL, gTimeoutFunc, 0, NULL, returnedValue.address())) + if (!JS_CallFunctionValue(cx, nullptr, gTimeoutFunc, 0, nullptr, returnedValue.address())) return false; if (returnedValue.isBoolean()) result = returnedValue.toBoolean(); @@ -429,7 +429,7 @@ RunFile(JSContext *cx, Handle obj, const char *filename, FILE *file, JS_SetOptions(cx, oldopts); JS_ASSERT_IF(!script, gGotError); if (script && !compileOnly) { - if (!JS_ExecuteScript(cx, obj, script, NULL)) { + if (!JS_ExecuteScript(cx, obj, script, nullptr)) { if (!gQuitting && !gTimedOut) gExitCode = EXITCODE_RUNTIME_ERROR; } @@ -553,7 +553,7 @@ Process(JSContext *cx, JSObject *obj_, const char *filename, bool forceTTY) } else { file = fopen(filename, "r"); if (!file) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_CANT_OPEN, filename, strerror(errno)); gExitCode = EXITCODE_FILE_NOT_FOUND; return; @@ -592,7 +592,7 @@ MapContextOptionNameToFlag(JSContext* cx, const char* name) return js_options[i].flag; } - char* msg = JS_sprintf_append(NULL, + char* msg = JS_sprintf_append(nullptr, "unknown option name '%s'." " The valid names are ", name); for (size_t i = 0; i < ArrayLength(js_options); ++i) { @@ -633,7 +633,7 @@ Version(JSContext *cx, unsigned argc, jsval *vp) v = int32_t(fv); } if (v < 0 || v > JSVERSION_LATEST) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "version"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "version"); return false; } JS_SetVersionForCompartment(js::GetContextCompartment(cx), JSVersion(v)); @@ -646,7 +646,7 @@ static JSScript * GetTopScript(JSContext *cx) { RootedScript script(cx); - JS_DescribeScriptedCaller(cx, &script, NULL); + JS_DescribeScriptedCaller(cx, &script, nullptr); return script; } @@ -663,7 +663,7 @@ ResolvePath(JSContext *cx, HandleString filenameStr, bool scriptRelative) { JSAutoByteString filename(cx, filenameStr); if (!filename) - return NULL; + return nullptr; const char *pathname = filename.ptr(); if (pathname[0] == '/') @@ -684,7 +684,7 @@ ResolvePath(JSContext *cx, HandleString filenameStr, bool scriptRelative) /* Get the currently executing script's name. */ RootedScript script(cx, GetTopScript(cx)); if (!script->filename()) - return NULL; + return nullptr; if (strcmp(script->filename(), "-e") == 0 || strcmp(script->filename(), "typein") == 0) scriptRelative = false; @@ -692,11 +692,11 @@ ResolvePath(JSContext *cx, HandleString filenameStr, bool scriptRelative) if (scriptRelative) { #ifdef XP_WIN // The docs say it can return EINVAL, but the compiler says it's void - _splitpath(script->filename(), NULL, buffer, NULL, NULL); + _splitpath(script->filename(), nullptr, buffer, nullptr, nullptr); #else strncpy(buffer, script->filename(), PATH_MAX+1); if (buffer[PATH_MAX] != '\0') - return NULL; + return nullptr; // dirname(buffer) might return buffer, or it might return a // statically-allocated string @@ -705,14 +705,14 @@ ResolvePath(JSContext *cx, HandleString filenameStr, bool scriptRelative) } else { const char *cwd = getcwd(buffer, PATH_MAX); if (!cwd) - return NULL; + return nullptr; } size_t len = strlen(buffer); buffer[len] = '/'; strncpy(buffer + len + 1, pathname, sizeof(buffer) - (len+1)); if (buffer[PATH_MAX] != '\0') - return NULL; + return nullptr; return JS_NewStringCopyZ(cx, buffer); } @@ -743,7 +743,7 @@ Options(JSContext *cx, unsigned argc, jsval *vp) } optset = JS_ToggleOptions(cx, optset); - names = NULL; + names = nullptr; found = false; for (size_t i = 0; i < ArrayLength(js_options); i++) { if (js_options[i].flag & optset) { @@ -780,7 +780,7 @@ LoadScript(JSContext *cx, unsigned argc, jsval *vp, bool scriptRelative) for (unsigned i = 0; i < args.length(); i++) { str = JS_ValueToString(cx, args[i]); if (!str) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "load"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "load"); return false; } str = ResolvePath(cx, str, scriptRelative); @@ -795,7 +795,7 @@ LoadScript(JSContext *cx, unsigned argc, jsval *vp, bool scriptRelative) CompileOptions opts(cx); opts.setUTF8(true).setCompileAndGo(true).setNoScriptRval(true); if ((compileOnly && !Compile(cx, thisobj, opts, filename.ptr())) || - !Evaluate(cx, thisobj, opts, filename.ptr(), NULL)) + !Evaluate(cx, thisobj, opts, filename.ptr(), nullptr)) { return false; } @@ -828,7 +828,7 @@ class AutoNewContext AutoNewContext(const AutoNewContext &) MOZ_DELETE; public: - AutoNewContext() : oldcx(NULL), newcx(NULL) {} + AutoNewContext() : oldcx(nullptr), newcx(nullptr) {} bool enter(JSContext *cx) { JS_ASSERT(!JS_IsExceptionPending(cx)); @@ -891,13 +891,13 @@ Evaluate(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1 || args.length() > 2) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, args.length() < 1 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS, "evaluate"); return false; } if (!args[0].isString() || (args.length() == 2 && args[1].isPrimitive())) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "evaluate"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "evaluate"); return false; } @@ -910,7 +910,7 @@ Evaluate(JSContext *cx, unsigned argc, jsval *vp) RootedString sourceURL(cx); RootedString sourceMapURL(cx); unsigned lineNumber = 1; - RootedObject global(cx, NULL); + RootedObject global(cx, nullptr); bool catchTermination = false; bool saveFrameChain = false; RootedObject callerGlobal(cx, cx->global()); @@ -954,7 +954,7 @@ Evaluate(JSContext *cx, unsigned argc, jsval *vp) if (!JS_GetProperty(cx, opts, "fileName", &v)) return false; if (JSVAL_IS_NULL(v)) { - fileName = NULL; + fileName = nullptr; } else if (!JSVAL_IS_VOID(v)) { JSString *s = JS_ValueToString(cx, v); if (!s) @@ -997,14 +997,14 @@ Evaluate(JSContext *cx, unsigned argc, jsval *vp) if (!JS_GetProperty(cx, opts, "global", &v)) return false; if (!JSVAL_IS_VOID(v)) { - global = JSVAL_IS_PRIMITIVE(v) ? NULL : JSVAL_TO_OBJECT(v); + global = JSVAL_IS_PRIMITIVE(v) ? nullptr : JSVAL_TO_OBJECT(v); if (global) { global = js::UncheckedUnwrap(global); if (!global) return false; } if (!global || !(JS_GetClass(global)->flags & JSCLASS_IS_GLOBAL)) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNEXPECTED_TYPE, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, "\"global\" passed to evaluate()", "not a global object"); return false; } @@ -1129,7 +1129,7 @@ FileAsString(JSContext *cx, const char *pathname) file = fopen(pathname, "rb"); if (!file) { JS_ReportError(cx, "can't open %s: %s", pathname, strerror(errno)); - return NULL; + return nullptr; } if (fseek(file, 0, SEEK_END) != 0) { @@ -1151,7 +1151,7 @@ FileAsString(JSContext *cx, const char *pathname) if (!ucbuf) { JS_ReportError(cx, "Invalid UTF-8 in file '%s'", pathname); gExitCode = EXITCODE_RUNTIME_ERROR; - return NULL; + return nullptr; } str = JS_NewUCStringCopyN(cx, ucbuf, len); free(ucbuf); @@ -1171,7 +1171,7 @@ FileAsTypedArray(JSContext *cx, const char *pathname) FILE *file = fopen(pathname, "rb"); if (!file) { JS_ReportError(cx, "can't open %s: %s", pathname, strerror(errno)); - return NULL; + return nullptr; } RootedObject obj(cx); @@ -1184,13 +1184,13 @@ FileAsTypedArray(JSContext *cx, const char *pathname) } else { obj = JS_NewUint8Array(cx, len); if (!obj) - return NULL; + return nullptr; char *buf = (char *) obj->as().viewData(); size_t cc = fread(buf, 1, len, file); if (cc != len) { JS_ReportError(cx, "can't read %s: %s", pathname, (ptrdiff_t(cc) < 0) ? strerror(errno) : "short read"); - obj = NULL; + obj = nullptr; } } } @@ -1208,7 +1208,7 @@ Run(JSContext *cx, unsigned argc, jsval *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (args.length() != 1) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "run"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "run"); return false; } @@ -1224,7 +1224,7 @@ Run(JSContext *cx, unsigned argc, jsval *vp) if (!filename) return false; - const jschar *ucbuf = NULL; + const jschar *ucbuf = nullptr; size_t buflen; str = FileAsString(cx, filename.ptr()); if (str) @@ -1239,7 +1239,7 @@ Run(JSContext *cx, unsigned argc, jsval *vp) int64_t startClock = PRMJ_Now(); RootedScript script(cx, JS_CompileUCScript(cx, thisobj, ucbuf, buflen, filename.ptr(), 1)); JS_SetOptions(cx, oldopts); - if (!script || !JS_ExecuteScript(cx, thisobj, script, NULL)) + if (!script || !JS_ExecuteScript(cx, thisobj, script, nullptr)) return false; int64_t endClock = PRMJ_Now(); @@ -1285,7 +1285,7 @@ ReadLine(JSContext *cx, unsigned argc, jsval *vp) tmp = (char *) JS_realloc(cx, buf, bufsize); } else { JS_ReportOutOfMemory(cx); - tmp = NULL; + tmp = nullptr; } if (!tmp) { @@ -1424,7 +1424,7 @@ AssertEq(JSContext *cx, unsigned argc, jsval *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (!(args.length() == 2 || (args.length() == 3 && args[2].isString()))) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, (args.length() < 2) ? JSSMSG_NOT_ENOUGH_ARGS : (args.length() == 3) @@ -1442,13 +1442,13 @@ AssertEq(JSContext *cx, unsigned argc, jsval *vp) const char *actual = ToSource(cx, args[0], &bytes0); const char *expected = ToSource(cx, args[1], &bytes1); if (args.length() == 2) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_ASSERT_EQ_FAILED, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_ASSERT_EQ_FAILED, actual, expected); } else { JSAutoByteString bytes2(cx, args[2].toString()); if (!bytes2) return false; - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_ASSERT_EQ_FAILED_MSG, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_ASSERT_EQ_FAILED_MSG, actual, expected, bytes2.ptr()); } return false; @@ -1458,12 +1458,12 @@ AssertEq(JSContext *cx, unsigned argc, jsval *vp) } static JSScript * -ValueToScript(JSContext *cx, jsval vArg, JSFunction **funp = NULL) +ValueToScript(JSContext *cx, jsval vArg, JSFunction **funp = nullptr) { RootedValue v(cx, vArg); RootedFunction fun(cx, JS_ValueToFunction(cx, v)); if (!fun) - return NULL; + return nullptr; // Unwrap bound functions. while (fun->isBoundFunction()) { @@ -1475,13 +1475,13 @@ ValueToScript(JSContext *cx, jsval vArg, JSFunction **funp = NULL) } if (!fun->isInterpreted()) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_SCRIPTS_ONLY); - return NULL; + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_SCRIPTS_ONLY); + return nullptr; } JSScript *script = fun->getOrCreateScript(cx); if (!script) - return NULL; + return nullptr; if (fun && funp) *funp = fun; @@ -1494,7 +1494,7 @@ SetDebug(JSContext *cx, unsigned argc, jsval *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (args.length() == 0 || !args[0].isBoolean()) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_NOT_ENOUGH_ARGS, "setDebug"); return false; } @@ -1584,7 +1584,7 @@ Trap(JSContext *cx, unsigned argc, jsval *vp) int32_t i; if (args.length() == 0) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_TRAP_USAGE); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_TRAP_USAGE); return false; } argc = args.length() - 1; @@ -1595,7 +1595,7 @@ Trap(JSContext *cx, unsigned argc, jsval *vp) if (!GetScriptAndPCArgs(cx, argc, args.array(), &script, &i)) return false; if (uint32_t(i) >= script->length) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_TRAP_USAGE); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_TRAP_USAGE); return false; } args.rval().setUndefined(); @@ -1611,7 +1611,7 @@ Untrap(JSContext *cx, unsigned argc, jsval *vp) if (!GetScriptAndPCArgs(cx, args.length(), args.array(), &script, &i)) return false; - JS_ClearTrap(cx, script, script->code + i, NULL, NULL); + JS_ClearTrap(cx, script, script->code + i, nullptr, nullptr); args.rval().setUndefined(); return true; } @@ -1628,7 +1628,7 @@ SetDebuggerHandler(JSContext *cx, unsigned argc, jsval *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (args.length() == 0) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_NOT_ENOUGH_ARGS, "setDebuggerHandler"); return false; } @@ -1648,7 +1648,7 @@ SetThrowHook(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); JSString *str; if (args.length() == 0) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_NOT_ENOUGH_ARGS, "setThrowHook"); return false; } @@ -1672,7 +1672,7 @@ LineToPC(JSContext *cx, unsigned argc, jsval *vp) jsbytecode *pc; if (args.length() == 0) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_LINE2PC_USAGE); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_LINE2PC_USAGE); return false; } script = GetTopScript(cx); @@ -2107,14 +2107,14 @@ DisassWithSrc(JSContext *cx, unsigned argc, jsval *vp) return false; if (!script->filename()) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_FILE_SCRIPTS_ONLY); return false; } file = fopen(script->filename(), "r"); if (!file) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_CANT_OPEN, script->filename(), strerror(errno)); return false; @@ -2155,7 +2155,7 @@ DisassWithSrc(JSContext *cx, unsigned argc, jsval *vp) bupline = 0; while (line1 < line2) { if (!fgets(linebuf, LINE_BUF_LEN, file)) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_UNEXPECTED_EOF, script->filename()); ok = false; @@ -2197,7 +2197,7 @@ DumpHeap(JSContext *cx, unsigned argc, jsval *vp) FILE *dumpFile; bool ok; - const char *fileName = NULL; + const char *fileName = nullptr; JSAutoByteString fileNameBytes; if (args.length() > 0) { v = args[0]; @@ -2228,7 +2228,7 @@ DumpHeap(JSContext *cx, unsigned argc, jsval *vp) } } - startThing = NULL; + startThing = nullptr; startTraceKind = JSTRACE_OBJECT; if (args.length() > 1) { v = args[1]; @@ -2241,7 +2241,7 @@ DumpHeap(JSContext *cx, unsigned argc, jsval *vp) } } - thingToFind = NULL; + thingToFind = nullptr; if (args.length() > 2) { v = args[2]; if (v.isMarkable()) { @@ -2252,7 +2252,7 @@ DumpHeap(JSContext *cx, unsigned argc, jsval *vp) } } - thingToIgnore = NULL; + thingToIgnore = nullptr; if (args.length() > 4) { v = args[4]; if (v.isMarkable()) { @@ -2349,7 +2349,7 @@ Clone(JSContext *cx, unsigned argc, jsval *vp) { Maybe ac; - RootedObject obj(cx, JSVAL_IS_PRIMITIVE(args[0]) ? NULL : &args[0].toObject()); + RootedObject obj(cx, JSVAL_IS_PRIMITIVE(args[0]) ? nullptr : &args[0].toObject()); if (obj && obj->is()) { obj = UncheckedUnwrap(obj); @@ -2368,7 +2368,7 @@ Clone(JSContext *cx, unsigned argc, jsval *vp) if (funobj->compartment() != cx->compartment()) { JSFunction *fun = &funobj->as(); if (fun->hasScript() && fun->nonLazyScript()->compileAndGo) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNEXPECTED_TYPE, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, "function", "compile-and-go"); return false; } @@ -2397,14 +2397,14 @@ GetPDA(JSContext *cx, unsigned argc, jsval *vp) JSPropertyDesc *pd; CallArgs args = CallArgsFromVp(argc, vp); - if (!JS_ValueToObject(cx, args[0], &vobj)) + if (!JS_ValueToObject(cx, args.get(0), &vobj)) return false; if (!vobj) { args.rval().setUndefined(); return true; } - RootedObject aobj(cx, JS_NewArrayObject(cx, 0, NULL)); + RootedObject aobj(cx, JS_NewArrayObject(cx, 0, nullptr)); if (!aobj) return false; args.rval().setObject(*aobj); @@ -2421,7 +2421,7 @@ GetPDA(JSContext *cx, unsigned argc, jsval *vp) RootedValue alias(cx); for (uint32_t i = 0; i < pda.length; i++, pd++) { - pdobj = JS_NewObject(cx, NULL, NULL, NULL); + pdobj = JS_NewObject(cx, nullptr, nullptr, nullptr); if (!pdobj) { ok = false; break; @@ -2521,7 +2521,7 @@ sandbox_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, return true; } } - objp.set(NULL); + objp.set(nullptr); return true; } @@ -2537,25 +2537,25 @@ static const JSClass sandbox_class = { static JSObject * NewSandbox(JSContext *cx, bool lazy) { - RootedObject obj(cx, JS_NewGlobalObject(cx, &sandbox_class, NULL, + RootedObject obj(cx, JS_NewGlobalObject(cx, &sandbox_class, nullptr, JS::DontFireOnNewGlobalHook)); if (!obj) - return NULL; + return nullptr; { JSAutoCompartment ac(cx, obj); if (!lazy && !JS_InitStandardClasses(cx, obj)) - return NULL; + return nullptr; RootedValue value(cx, BooleanValue(lazy)); if (!JS_SetProperty(cx, obj, "lazy", value)) - return NULL; + return nullptr; } JS_FireOnNewGlobalObject(cx, obj); if (!cx->compartment()->wrap(cx, &obj)) - return NULL; + return nullptr; return obj; } @@ -2650,7 +2650,7 @@ EvalInFrame(JSContext *cx, unsigned argc, jsval *vp) /* This is a copy of CheckDebugMode. */ if (!JS_GetDebugMode(cx)) { JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, - NULL, JSMSG_NEED_DEBUG_MODE); + nullptr, JSMSG_NEED_DEBUG_MODE); return false; } @@ -2713,7 +2713,7 @@ CopyProperty(JSContext *cx, HandleObject obj, HandleObject referent, HandleId id unsigned propFlags = 0; RootedObject obj2(cx); - objp.set(NULL); + objp.set(nullptr); if (referent->isNative()) { if (!LookupPropertyWithFlags(cx, referent, id, lookupFlags, &obj2, &shape)) return false; @@ -2801,8 +2801,8 @@ static const JSClass resolver_class = { static bool Resolver(JSContext *cx, unsigned argc, jsval *vp) { - RootedObject referent(cx, NULL); - RootedObject proto(cx, NULL); + RootedObject referent(cx, nullptr); + RootedObject proto(cx, nullptr); if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "o/o", &referent, &proto)) return false; @@ -2898,7 +2898,7 @@ KillWatchdog() * The watchdog thread is running, tell it to terminate waking it up * if necessary. */ - gWatchdogThread = NULL; + gWatchdogThread = nullptr; PR_NotifyCondVar(gWatchdogWakeup); } PR_Unlock(gWatchdogLock); @@ -3025,12 +3025,12 @@ ScheduleWatchdog(JSRuntime *rt, double t) { #ifdef XP_WIN if (gTimerHandle) { - DeleteTimerQueueTimer(NULL, gTimerHandle, NULL); + DeleteTimerQueueTimer(nullptr, gTimerHandle, nullptr); gTimerHandle = 0; } if (t > 0 && !CreateTimerQueueTimer(&gTimerHandle, - NULL, + nullptr, (WAITORTIMERCALLBACK)TimerCallback, rt, DWORD(ceil(t * 1000.0)), @@ -3043,7 +3043,7 @@ ScheduleWatchdog(JSRuntime *rt, double t) /* FIXME: use setitimer when available for sub-second resolution. */ if (t <= 0) { alarm(0); - signal(SIGALRM, NULL); + signal(SIGALRM, nullptr); } else { signal(SIGALRM, AlarmHandler); /* set the Alarm signal capture */ alarm(ceil(t)); @@ -3164,7 +3164,7 @@ static bool Compile(JSContext *cx, unsigned argc, jsval *vp) { if (argc < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "compile", "0", "s"); return false; } @@ -3195,7 +3195,7 @@ Parse(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "parse", "0", "s"); return false; } @@ -3212,9 +3212,9 @@ Parse(JSContext *cx, unsigned argc, jsval *vp) Parser parser(cx, &cx->tempLifoAlloc(), options, JS_GetStringCharsZ(cx, scriptContents), JS_GetStringLength(scriptContents), - /* foldConstants = */ true, NULL, NULL); + /* foldConstants = */ true, nullptr, nullptr); - ParseNode *pn = parser.parse(NULL); + ParseNode *pn = parser.parse(nullptr); if (!pn) return false; #ifdef DEBUG @@ -3233,7 +3233,7 @@ SyntaxParse(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "parse", "0", "s"); return false; } @@ -3251,9 +3251,9 @@ SyntaxParse(JSContext *cx, unsigned argc, jsval *vp) const jschar *chars = JS_GetStringCharsZ(cx, scriptContents); size_t length = JS_GetStringLength(scriptContents); Parser parser(cx, &cx->tempLifoAlloc(), - options, chars, length, false, NULL, NULL); + options, chars, length, false, nullptr, nullptr); - bool succeeded = parser.parse(NULL); + bool succeeded = parser.parse(nullptr); if (cx->isExceptionPending()) return false; @@ -3304,7 +3304,7 @@ class OffThreadState { JS_ASSERT(source); JS_RemoveStringRoot(cx, &source); - source = NULL; + source = nullptr; state = IDLE; } @@ -3324,7 +3324,7 @@ class OffThreadState { void *waitUntilDone(JSContext *cx) { AutoLockMonitor alm(monitor); if (state == IDLE) - return NULL; + return nullptr; if (state == COMPILING) { while (state != DONE) @@ -3333,11 +3333,11 @@ class OffThreadState { JS_ASSERT(source); JS_RemoveStringRoot(cx, &source); - source = NULL; + source = nullptr; JS_ASSERT(token); void *holdToken = token; - token = NULL; + token = nullptr; state = IDLE; return holdToken; } @@ -3363,7 +3363,7 @@ OffThreadCompileScript(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "offThreadCompileScript", "0", "s"); return false; } @@ -3396,7 +3396,7 @@ OffThreadCompileScript(JSContext *cx, unsigned argc, jsval *vp) } if (!JS::CompileOffThread(cx, cx->global(), options, chars, length, - OffThreadCompileScriptCallback, NULL)) + OffThreadCompileScriptCallback, nullptr)) { offThreadState.abandon(cx); return false; @@ -3432,7 +3432,7 @@ struct FreeOnReturn const char *ptr; MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - FreeOnReturn(JSContext *cx, const char *ptr = NULL + FreeOnReturn(JSContext *cx, const char *ptr = nullptr MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : cx(cx), ptr(ptr) { @@ -3455,14 +3455,14 @@ ReadFile(JSContext *cx, unsigned argc, jsval *vp, bool scriptRelative) CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1 || args.length() > 2) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, args.length() < 1 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS, "snarf"); return false; } if (!args[0].isString() || (args.length() == 2 && !args[1].isString())) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "snarf"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "snarf"); return false; } @@ -3515,7 +3515,7 @@ redirect(JSContext *cx, FILE* fp, HandleString relFilename) JSAutoByteString filenameABS(cx, filename); if (!filenameABS) return false; - if (freopen(filenameABS.ptr(), "wb", fp) == NULL) { + if (freopen(filenameABS.ptr(), "wb", fp) == nullptr) { JS_ReportError(cx, "cannot redirect to %s: %s", filenameABS.ptr(), strerror(errno)); return false; } @@ -3528,7 +3528,7 @@ RedirectOutput(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); if (args.length() < 1 || args.length() > 2) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "redirect"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "redirect"); return false; } @@ -3558,7 +3558,7 @@ System(JSContext *cx, unsigned argc, jsval *vp) JSString *str; if (argc != 1) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "system"); return false; } @@ -3609,7 +3609,7 @@ DecompileThisScript(JSContext *cx, unsigned argc, Value *vp) { CallArgs args = CallArgsFromVp(argc, vp); RootedScript script (cx); - if (!JS_DescribeScriptedCaller(cx, &script, NULL)) { + if (!JS_DescribeScriptedCaller(cx, &script, nullptr)) { args.rval().setString(cx->runtime()->emptyString); return true; } @@ -3625,7 +3625,7 @@ ThisFilename(JSContext *cx, unsigned argc, Value *vp) { CallArgs args = CallArgsFromVp(argc, vp); RootedScript script (cx); - if (!JS_DescribeScriptedCaller(cx, &script, NULL) || !script->filename()) { + if (!JS_DescribeScriptedCaller(cx, &script, nullptr) || !script->filename()) { args.rval().setString(cx->runtime()->emptyString); return true; } @@ -3667,7 +3667,7 @@ WrapWithProto(JSContext *cx, unsigned argc, jsval *vp) proto = JS_ARGV(cx, vp)[1]; } if (!obj.isObject() || !proto.isObjectOrNull()) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "wrapWithProto"); return false; } @@ -3688,7 +3688,7 @@ Serialize(JSContext *cx, unsigned argc, jsval *vp) jsval v = argc > 0 ? JS_ARGV(cx, vp)[0] : UndefinedValue(); uint64_t *datap; size_t nbytes; - if (!JS_WriteStructuredClone(cx, v, &datap, &nbytes, NULL, NULL, UndefinedValue())) + if (!JS_WriteStructuredClone(cx, v, &datap, &nbytes, nullptr, nullptr, UndefinedValue())) return false; JSObject *obj = JS_NewUint8Array(cx, nbytes); @@ -3711,21 +3711,21 @@ Deserialize(JSContext *cx, unsigned argc, jsval *vp) Rooted v(cx, argc > 0 ? JS_ARGV(cx, vp)[0] : UndefinedValue()); JSObject *obj; if (JSVAL_IS_PRIMITIVE(v) || !(obj = JSVAL_TO_OBJECT(v))->is()) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "deserialize"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "deserialize"); return false; } TypedArrayObject *tarr = &obj->as(); if ((tarr->byteLength() & 7) != 0) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, "deserialize"); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "deserialize"); return false; } if ((uintptr_t(tarr->viewData()) & 7) != 0) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_BAD_ALIGNMENT); + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_BAD_ALIGNMENT); return false; } if (!JS_ReadStructuredClone(cx, (uint64_t *) tarr->viewData(), tarr->byteLength(), - JS_STRUCTURED_CLONE_VERSION, v.address(), NULL, NULL)) { + JS_STRUCTURED_CLONE_VERSION, v.address(), nullptr, nullptr)) { return false; } JS_SET_RVAL(cx, vp, v); @@ -3772,7 +3772,7 @@ static bool EnableStackWalkingAssertion(JSContext *cx, unsigned argc, jsval *vp) { if (argc == 0 || !JSVAL_IS_BOOLEAN(JS_ARGV(cx, vp)[0])) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "enableStackWalkingAssertion"); return false; } @@ -3807,7 +3807,7 @@ ObjectEmulatingUndefined(JSContext *cx, unsigned argc, jsval *vp) JS_ConvertStub }; - RootedObject obj(cx, JS_NewObject(cx, &cls, NULL, NULL)); + RootedObject obj(cx, JS_NewObject(cx, &cls, nullptr, nullptr)); if (!obj) return false; JS_SET_RVAL(cx, vp, ObjectValue(*obj)); @@ -3820,7 +3820,7 @@ GetSelfHostedValue(JSContext *cx, unsigned argc, jsval *vp) CallArgs args = CallArgsFromVp(argc, vp); if (argc != 1 || !args[0].isString()) { - JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL, JSSMSG_INVALID_ARGS, + JS_ReportErrorNumber(cx, my_GetErrorMessage, nullptr, JSSMSG_INVALID_ARGS, "getSelfHostedValue"); return false; } @@ -3841,7 +3841,7 @@ class ShellSourceHook: public SourceHook { JSObject *fun; public: - ShellSourceHook() : rt(NULL), fun(NULL) { } + ShellSourceHook() : rt(nullptr), fun(nullptr) { } bool init(JSContext *cx, JSFunction &fun) { JS_ASSERT(!this->rt); JS_ASSERT(!this->fun); @@ -3912,7 +3912,7 @@ WithSourceHook(JSContext *cx, unsigned argc, jsval *vp) SourceHook *savedHook = js::ForgetSourceHook(cx->runtime()); js::SetSourceHook(cx->runtime(), hook); - bool result = Call(cx, UndefinedValue(), &args[1].toObject(), 0, NULL, args.rval()); + bool result = Call(cx, UndefinedValue(), &args[1].toObject(), 0, nullptr, args.rval()); js::SetSourceHook(cx->runtime(), savedHook); return result; } @@ -4408,7 +4408,7 @@ static const JSErrorFormatString * my_GetErrorMessage(void *userRef, const char *locale, const unsigned errorNumber) { if (errorNumber == 0 || errorNumber >= JSShellErr_Limit) - return NULL; + return nullptr; return &jsShell_ErrorFormatString[errorNumber]; } @@ -4449,7 +4449,7 @@ Exec(JSContext *cx, unsigned argc, jsval *vp) nargc = 1 + argc; - /* nargc + 1 accounts for the terminating NULL. */ + /* nargc + 1 accounts for the terminating nullptr. */ nargv = new (char *)[nargc + 1]; if (!nargv) return false; @@ -4539,7 +4539,7 @@ global_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, if (!name) return false; ok = true; - for (comp = strtok(path, ":"); comp; comp = strtok(NULL, ":")) { + for (comp = strtok(path, ":"); comp; comp = strtok(nullptr, ":")) { if (*comp != '\0') { full = JS_smprintf("%s/%s", comp, name.ptr()); if (!full) { @@ -4556,7 +4556,7 @@ global_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, if (found) { fun = JS_DefineFunction(cx, obj, name, Exec, 0, JSPROP_ENUMERATE); - ok = (fun != NULL); + ok = (fun != nullptr); if (ok) objp.set(obj); break; @@ -4574,7 +4574,7 @@ static const JSClass global_class = { JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, global_enumerate, (JSResolveOp) global_resolve, - JS_ConvertStub, NULL + JS_ConvertStub, nullptr }; static bool @@ -4632,14 +4632,14 @@ env_enumerate(JSContext *cx, HandleObject obj) if (reflected) return true; - for (evp = (char **)JS_GetPrivate(obj); (name = *evp) != NULL; evp++) { + for (evp = (char **)JS_GetPrivate(obj); (name = *evp) != nullptr; evp++) { value = strchr(name, '='); if (!value) continue; *value++ = '\0'; valstr = JS_NewStringCopyZ(cx, value); ok = valstr && JS_DefineProperty(cx, obj, name, STRING_TO_JSVAL(valstr), - NULL, NULL, JSPROP_ENUMERATE); + nullptr, nullptr, JSPROP_ENUMERATE); value[-1] = '='; if (!ok) return false; @@ -4667,7 +4667,7 @@ env_resolve(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, if (!valstr) return false; if (!JS_DefineProperty(cx, obj, name, STRING_TO_JSVAL(valstr), - NULL, NULL, JSPROP_ENUMERATE)) { + nullptr, nullptr, JSPROP_ENUMERATE)) { return false; } objp.set(obj); @@ -4764,7 +4764,7 @@ static const JSPropertySpec dom_props[] = { { (JSPropertyOp)dom_genericGetter, &dom_x_getterinfo }, { (JSStrictPropertyOp)dom_genericSetter, &dom_x_setterinfo } }, - {NULL,0,0,JSOP_NULLWRAPPER, JSOP_NULLWRAPPER} + {nullptr,0,0,JSOP_NULLWRAPPER, JSOP_NULLWRAPPER} }; static const JSFunctionSpec dom_methods[] = { @@ -4781,12 +4781,12 @@ static const JSClass dom_class = { JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, - NULL, /* finalize */ - NULL, /* checkAccess */ - NULL, /* call */ - NULL, /* hasInstance */ - NULL, /* construct */ - NULL, /* trace */ + nullptr, /* finalize */ + nullptr, /* checkAccess */ + nullptr, /* call */ + nullptr, /* hasInstance */ + nullptr, /* construct */ + nullptr, /* trace */ JSCLASS_NO_INTERNAL_MEMBERS }; @@ -4882,11 +4882,11 @@ dom_constructor(JSContext* cx, unsigned argc, JS::Value *vp) return false; if (!protov.isObject()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PROTOTYPE, "FakeDOMObject"); + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PROTOTYPE, "FakeDOMObject"); return false; } - RootedObject domObj(cx, JS_NewObject(cx, &dom_class, &protov.toObject(), NULL)); + RootedObject domObj(cx, JS_NewObject(cx, &dom_class, &protov.toObject(), nullptr)); if (!domObj) return false; @@ -4929,12 +4929,12 @@ NewContext(JSRuntime *rt) JSContext *cx; WITH_SIGNALS_DISABLED(cx = JS_NewContext(rt, gStackChunkSize)); if (!cx) - return NULL; + return nullptr; JSShellContextData *data = NewContextData(); if (!data) { DestroyContext(cx, false); - return NULL; + return nullptr; } JS_SetContextPrivate(cx, data); @@ -4954,7 +4954,7 @@ static void DestroyContext(JSContext *cx, bool withGC) { JSShellContextData *data = GetContextData(cx); - JS_SetContextPrivate(cx, NULL); + JS_SetContextPrivate(cx, nullptr); free(data); WITH_SIGNALS_DISABLED(withGC ? JS_DestroyContext(cx) : JS_DestroyContextNoGC(cx)); } @@ -4962,39 +4962,39 @@ DestroyContext(JSContext *cx, bool withGC) static JSObject * NewGlobalObject(JSContext *cx, JS::CompartmentOptions &options) { - RootedObject glob(cx, JS_NewGlobalObject(cx, &global_class, NULL, + RootedObject glob(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::DontFireOnNewGlobalHook, options)); if (!glob) - return NULL; + return nullptr; { JSAutoCompartment ac(cx, glob); #ifndef LAZY_STANDARD_CLASSES if (!JS_InitStandardClasses(cx, glob)) - return NULL; + return nullptr; #endif #ifdef JS_HAS_CTYPES if (!JS_InitCTypesClass(cx, glob)) - return NULL; + return nullptr; #endif if (!JS_InitReflect(cx, glob)) - return NULL; + return nullptr; if (!JS_DefineDebuggerObject(cx, glob)) - return NULL; + return nullptr; if (!JS::RegisterPerfMeasurement(cx, glob)) - return NULL; + return nullptr; if (!JS_DefineFunctionsWithHelp(cx, glob, shell_functions) || !JS_DefineProfilingFunctions(cx, glob)) { - return NULL; + return nullptr; } if (!js::DefineTestingFunctions(cx, glob)) - return NULL; + return nullptr; if (!fuzzingSafe && !JS_DefineFunctionsWithHelp(cx, glob, fuzzing_unsafe_functions)) - return NULL; + return nullptr; /* Initialize FakeDOMObject. */ static const js::DOMCallbacks DOMcallbacks = { @@ -5002,10 +5002,10 @@ NewGlobalObject(JSContext *cx, JS::CompartmentOptions &options) }; SetDOMCallbacks(cx->runtime(), &DOMcallbacks); - RootedObject domProto(cx, JS_InitClass(cx, glob, NULL, &dom_class, dom_constructor, 0, - dom_props, dom_methods, NULL, NULL)); + RootedObject domProto(cx, JS_InitClass(cx, glob, nullptr, &dom_class, dom_constructor, 0, + dom_props, dom_methods, nullptr, nullptr)); if (!domProto) - return NULL; + return nullptr; /* Initialize FakeDOMObject.prototype */ InitDOMObject(domProto); @@ -5023,18 +5023,19 @@ BindScriptArgs(JSContext *cx, JSObject *obj_, OptionParser *op) MultiStringRange msr = op->getMultiStringArg("scriptArgs"); RootedObject scriptArgs(cx); - scriptArgs = JS_NewArrayObject(cx, 0, NULL); + scriptArgs = JS_NewArrayObject(cx, 0, nullptr); if (!scriptArgs) return false; - if (!JS_DefineProperty(cx, obj, "scriptArgs", OBJECT_TO_JSVAL(scriptArgs), NULL, NULL, 0)) + if (!JS_DefineProperty(cx, obj, "scriptArgs", OBJECT_TO_JSVAL(scriptArgs), + nullptr, nullptr, 0)) return false; for (size_t i = 0; !msr.empty(); msr.popFront(), ++i) { const char *scriptArg = msr.front(); JSString *str = JS_NewStringCopyZ(cx, scriptArg); if (!str || - !JS_DefineElement(cx, scriptArgs, i, STRING_TO_JSVAL(str), NULL, NULL, + !JS_DefineElement(cx, scriptArgs, i, STRING_TO_JSVAL(str), nullptr, nullptr, JSPROP_ENUMERATE)) { return false; } @@ -5236,7 +5237,7 @@ ProcessArgs(JSContext *cx, JSObject *obj_, OptionParser *op) MultiStringRange codeChunks = op->getMultiStringOption('e'); if (filePaths.empty() && codeChunks.empty() && !op->getStringArg("script")) { - Process(cx, obj, NULL, true); /* Interactive. */ + Process(cx, obj, nullptr, true); /* Interactive. */ return gExitCode; } @@ -5266,7 +5267,7 @@ ProcessArgs(JSContext *cx, JSObject *obj_, OptionParser *op) } if (op->getBoolOption('i')) - Process(cx, obj, NULL, true); + Process(cx, obj, nullptr, true); return gExitCode ? gExitCode : EXIT_SUCCESS; } @@ -5298,7 +5299,7 @@ Shell(JSContext *cx, OptionParser *op, char **envp) JSAutoCompartment ac(cx, glob); js::SetDefaultObjectForContext(cx, glob); - JSObject *envobj = JS_DefineObject(cx, glob, "environment", &env_class, NULL, 0); + JSObject *envobj = JS_DefineObject(cx, glob, "environment", &env_class, nullptr, 0); if (!envobj) return 1; JS_SetPrivate(envobj, envp); @@ -5334,7 +5335,7 @@ CheckObjectAccess(JSContext *cx, HandleObject obj, HandleId id, JSAccessMode mod static const JSSecurityCallbacks securityCallbacks = { CheckObjectAccess, - NULL + nullptr }; /* Pretend we can always preserve wrappers for dummy DOM objects. */ @@ -5366,7 +5367,7 @@ main(int argc, char **argv, char **envp) #endif #ifdef JS_THREADSAFE - if (PR_FAILURE == PR_NewThreadPrivateIndex(&gStackBaseThreadIndex, NULL) || + if (PR_FAILURE == PR_NewThreadPrivateIndex(&gStackBaseThreadIndex, nullptr) || PR_FAILURE == PR_SetThreadPrivate(gStackBaseThreadIndex, &stackDummy)) { return 1; } diff --git a/js/src/shell/jsheaptools.cpp b/js/src/shell/jsheaptools.cpp index 33f0bd105e73..e86053737694 100644 --- a/js/src/shell/jsheaptools.cpp +++ b/js/src/shell/jsheaptools.cpp @@ -117,7 +117,7 @@ class HeapReverser : public JSTracer, public JS::CustomAutoRooter * resized. */ Edge(MoveRef rhs) : name(rhs->name), origin(rhs->origin) { - rhs->name = NULL; + rhs->name = nullptr; } Edge &operator=(MoveRef rhs) { this->~Edge(); @@ -134,8 +134,8 @@ class HeapReverser : public JSTracer, public JS::CustomAutoRooter char *name; /* - * The Cell from which this edge originates. NULL means a root. This is - * a cell address instead of a Node * because Nodes live in HashMap + * The Cell from which this edge originates. nullptr means a root. This + * is a cell address instead of a Node * because Nodes live in HashMap * table entries; if the HashMap reallocates its table, all pointers to * the Nodes it contains would become invalid. You should look up the * address here in |map| to find its Node. @@ -154,7 +154,7 @@ class HeapReverser : public JSTracer, public JS::CustomAutoRooter HeapReverser(JSContext *cx) : JS::CustomAutoRooter(cx), runtime(JS_GetRuntime(cx)), - parent(NULL) + parent(nullptr) { JS_TracerInit(this, runtime, traverseEdgeWithThis); JS::DisableGenerationalGC(runtime); @@ -176,7 +176,7 @@ class HeapReverser : public JSTracer, public JS::CustomAutoRooter /* * Return the name of the most recent edge this JSTracer has traversed. The * result is allocated with malloc; if we run out of memory, raise an error - * in this HeapReverser's context and return NULL. + * in this HeapReverser's context and return nullptr. * * This may not be called after that edge's call to traverseEdge has * returned. @@ -312,7 +312,7 @@ HeapReverser::getEdgeDescription() const char *arg = static_cast(debugPrintArg); char *name = js_pod_malloc(strlen(arg) + 1); if (!name) - return NULL; + return nullptr; strcpy(name, arg); return name; } @@ -321,7 +321,7 @@ HeapReverser::getEdgeDescription() static const int nameSize = 200; char *name = js_pod_malloc(nameSize); if (!name) - return NULL; + return nullptr; if (debugPrinter) debugPrinter(this, name, nameSize); else @@ -429,7 +429,7 @@ ReferenceFinder::visit(void *cell, Path *path) HeapReverser::Node *node = &p->value; /* Is |cell| a representable cell, reached via a non-empty path? */ - if (path != NULL) { + if (path != nullptr) { jsval representation = representable(cell, node->kind); if (!JSVAL_IS_VOID(representation)) return addReferrer(representation, path); @@ -466,7 +466,7 @@ ReferenceFinder::Path::computeName(JSContext *cx) char *path = cx->pod_malloc(size); if (!path) - return NULL; + return nullptr; /* * Walk the edge list again, and copy the edge names into place, with @@ -528,11 +528,11 @@ ReferenceFinder::addReferrer(jsval referrerArg, Path *path) JSObject * ReferenceFinder::findReferences(HandleObject target) { - result = JS_NewObject(context, NULL, NULL, NULL); + result = JS_NewObject(context, nullptr, nullptr, nullptr); if (!result) - return NULL; - if (!visit(target, NULL)) - return NULL; + return nullptr; + if (!visit(target, nullptr)) + return nullptr; return result; } @@ -542,14 +542,14 @@ bool FindReferences(JSContext *cx, unsigned argc, jsval *vp) { if (argc < 1) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED, "findReferences", "0", "s"); return false; } RootedValue target(cx, JS_ARGV(cx, vp)[0]); if (!target.isObject()) { - JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_UNEXPECTED_TYPE, + JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, "argument", "not an object"); return false; } diff --git a/js/src/shell/jsoptparse.cpp b/js/src/shell/jsoptparse.cpp index 208dbee719a7..0e4d100b0cb6 100644 --- a/js/src/shell/jsoptparse.cpp +++ b/js/src/shell/jsoptparse.cpp @@ -286,7 +286,7 @@ OptionParser::handleOption(Option *opt, size_t argc, char **argv, size_t *i, boo */ case OptionKindString: { - char *value = NULL; + char *value = nullptr; if (Result r = extractValue(argc, argv, i, &value)) return r; opt->asStringOption()->value = value; @@ -294,7 +294,7 @@ OptionParser::handleOption(Option *opt, size_t argc, char **argv, size_t *i, boo } case OptionKindInt: { - char *value = NULL; + char *value = nullptr; if (Result r = extractValue(argc, argv, i, &value)) return r; opt->asIntOption()->value = atoi(value); @@ -302,7 +302,7 @@ OptionParser::handleOption(Option *opt, size_t argc, char **argv, size_t *i, boo } case OptionKindMultiString: { - char *value = NULL; + char *value = nullptr; if (Result r = extractValue(argc, argv, i, &value)) return r; StringArg arg(value, *i); @@ -466,7 +466,7 @@ OptionParser::findOption(char shortflag) return *it; } - return helpOption.shortflag == shortflag ? &helpOption : NULL; + return helpOption.shortflag == shortflag ? &helpOption : nullptr; } const Option * @@ -496,7 +496,7 @@ OptionParser::findOption(const char *longflag) no_match:; } - return strcmp(helpOption.longflag, longflag) ? NULL : &helpOption; + return strcmp(helpOption.longflag, longflag) ? nullptr : &helpOption; } const Option * @@ -522,14 +522,14 @@ Option * OptionParser::findArgument(const char *name) { int index = findArgumentIndex(name); - return (index == -1) ? NULL : arguments[index]; + return (index == -1) ? nullptr : arguments[index]; } const Option * OptionParser::findArgument(const char *name) const { int index = findArgumentIndex(name); - return (index == -1) ? NULL : arguments[index]; + return (index == -1) ? nullptr : arguments[index]; } const char * @@ -605,7 +605,7 @@ OptionParser::addOptionalStringArg(const char *name, const char *help) { if (!arguments.reserve(arguments.length() + 1)) return false; - StringOption *so = js_new(1, name, help, (const char *) NULL); + StringOption *so = js_new(1, name, help, (const char *) nullptr); if (!so) return false; arguments.infallibleAppend(so); @@ -618,7 +618,7 @@ OptionParser::addOptionalMultiStringArg(const char *name, const char *help) JS_ASSERT_IF(!arguments.empty(), !arguments.back()->isVariadic()); if (!arguments.reserve(arguments.length() + 1)) return false; - MultiStringOption *mso = js_new(1, name, help, (const char *) NULL); + MultiStringOption *mso = js_new(1, name, help, (const char *) nullptr); if (!mso) return false; arguments.infallibleAppend(mso); diff --git a/js/src/shell/jsoptparse.h b/js/src/shell/jsoptparse.h index ed25180a3138..5c263544644e 100644 --- a/js/src/shell/jsoptparse.h +++ b/js/src/shell/jsoptparse.h @@ -116,7 +116,7 @@ struct StringOption : public ValuedOption const char *value; StringOption(char shortflag, const char *longflag, const char *help, const char *metavar) - : ValuedOption(OptionKindString, shortflag, longflag, help, metavar), value(NULL) + : ValuedOption(OptionKindString, shortflag, longflag, help, metavar), value(nullptr) {} virtual ~StringOption() {} @@ -234,7 +234,7 @@ class OptionParser public: explicit OptionParser(const char *usage) : helpOption('h', "help", "Display help information"), - usage(usage), ver(NULL), descr(NULL), descrWidth(80), helpWidth(80), + usage(usage), ver(nullptr), descr(nullptr), descrWidth(80), helpWidth(80), nextArgument(0), restArgument(-1) {} diff --git a/js/src/vm/ProxyObject.cpp b/js/src/vm/ProxyObject.cpp index 6d520ec31306..9a658e598455 100644 --- a/js/src/vm/ProxyObject.cpp +++ b/js/src/vm/ProxyObject.cpp @@ -37,7 +37,7 @@ ProxyObject::New(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, Tag if (proto.isObject() && !options.singleton()) { RootedObject protoObj(cx, proto.toObject()); if (!JSObject::setNewTypeUnknown(cx, clasp, protoObj)) - return NULL; + return nullptr; } NewObjectKind newKind = @@ -47,7 +47,7 @@ ProxyObject::New(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, Tag allocKind = GetBackgroundAllocKind(allocKind); RootedObject obj(cx, NewObjectWithGivenProto(cx, clasp, proto, parent, allocKind, newKind)); if (!obj) - return NULL; + return nullptr; Rooted proxy(cx, &obj->as()); proxy->initHandler(handler); diff --git a/js/src/vm/RegExpObject.cpp b/js/src/vm/RegExpObject.cpp index 343a8508a51a..6f802a8390fc 100644 --- a/js/src/vm/RegExpObject.cpp +++ b/js/src/vm/RegExpObject.cpp @@ -527,6 +527,9 @@ RegExpRunStatus RegExpShared::execute(JSContext *cx, const jschar *chars, size_t length, size_t *lastIndex, MatchPairs &matches) { + /* Protect inlined chars from root analysis poisoning. */ + SkipRoot skip(cx, &chars); + /* Compile the code at point-of-use. */ if (!compileIfNecessary(cx)) return RegExpRunStatus_Error; diff --git a/mobile/android/chrome/content/browser.js b/mobile/android/chrome/content/browser.js index c1d5952d0fc6..2edf6b855c40 100644 --- a/mobile/android/chrome/content/browser.js +++ b/mobile/android/chrome/content/browser.js @@ -18,7 +18,6 @@ Cu.import("resource://gre/modules/JNI.jsm"); Cu.import('resource://gre/modules/Payment.jsm'); Cu.import("resource://gre/modules/PermissionPromptHelper.jsm"); Cu.import("resource://gre/modules/ContactService.jsm"); -Cu.import("resource://gre/modules/NotificationDB.jsm"); #ifdef ACCESSIBILITY Cu.import("resource://gre/modules/accessibility/AccessFu.jsm"); diff --git a/mobile/android/installer/package-manifest.in b/mobile/android/installer/package-manifest.in index 9983801bbb59..399916a1a3bc 100644 --- a/mobile/android/installer/package-manifest.in +++ b/mobile/android/installer/package-manifest.in @@ -282,8 +282,6 @@ @BINPATH@/components/ContactManager.manifest @BINPATH@/components/PhoneNumberService.js @BINPATH@/components/PhoneNumberService.manifest -@BINPATH@/components/NotificationStorage.js -@BINPATH@/components/NotificationStorage.manifest @BINPATH@/components/SettingsManager.js @BINPATH@/components/SettingsManager.manifest @BINPATH@/components/SettingsService.js diff --git a/netwerk/cache2/CacheEntry.cpp b/netwerk/cache2/CacheEntry.cpp index 4c4bcbd2cf9e..5dfe7549e591 100644 --- a/netwerk/cache2/CacheEntry.cpp +++ b/netwerk/cache2/CacheEntry.cpp @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +#include "CacheLog.h" #include "CacheEntry.h" #include "CacheStorageService.h" -#include "CacheLog.h" #include "nsIInputStream.h" #include "nsIOutputStream.h" diff --git a/netwerk/cache2/OldWrappers.cpp b/netwerk/cache2/OldWrappers.cpp index cd52199b2a0b..1011fc47f129 100644 --- a/netwerk/cache2/OldWrappers.cpp +++ b/netwerk/cache2/OldWrappers.cpp @@ -211,7 +211,7 @@ _OldCacheEntryWrapper::_OldCacheEntryWrapper(nsICacheEntryDescriptor* desc) } _OldCacheEntryWrapper::_OldCacheEntryWrapper(nsICacheEntryInfo* info) -: mOldInfo(info) +: mOldDesc(nullptr), mOldInfo(info) { MOZ_COUNT_CTOR(_OldCacheEntryWrapper); LOG(("Creating _OldCacheEntryWrapper %p for info %p", this, info)); diff --git a/netwerk/test/unit/test_304_responses.js b/netwerk/test/unit/test_304_responses.js index ba0b9241889d..278656eac152 100644 --- a/netwerk/test/unit/test_304_responses.js +++ b/netwerk/test/unit/test_304_responses.js @@ -81,6 +81,7 @@ add_test(function test_304_stored_in_cache() { cacheEntry.setMetaDataElement("response-head", "HTTP/1.1 304 Not Modified\r\n" + "\r\n"); + cacheEntry.metaDataReady(); cacheEntry.close(); var chan = make_channel(baseURI + existingCached304); diff --git a/toolkit/components/places/PlacesBackups.jsm b/toolkit/components/places/PlacesBackups.jsm index 2d78525f3bcb..dbfbec7cd4ae 100644 --- a/toolkit/components/places/PlacesBackups.jsm +++ b/toolkit/components/places/PlacesBackups.jsm @@ -8,12 +8,15 @@ this.EXPORTED_SYMBOLS = ["PlacesBackups"]; const Ci = Components.interfaces; const Cu = Components.utils; +const Cc = Components.classes; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/PlacesUtils.jsm"); Cu.import("resource://gre/modules/BookmarkJSONUtils.jsm"); Cu.import("resource://gre/modules/Task.jsm"); +Cu.import("resource://gre/modules/osfile.jsm"); +Cu.import("resource://gre/modules/Deprecated.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm"); @@ -34,6 +37,10 @@ this.PlacesBackups = { }, get folder() { + Deprecated.warning( + "PlacesBackups.folder is deprecated and will be removed in a future version", + "https://bugzilla.mozilla.org/show_bug.cgi?id=859695"); + let bookmarksBackupDir = Services.dirsvc.get("ProfD", Ci.nsILocalFile); bookmarksBackupDir.append(this.profileRelativeFolderPath); if (!bookmarksBackupDir.exists()) { @@ -45,12 +52,39 @@ this.PlacesBackups = { return this.folder = bookmarksBackupDir; }, + /** + * Gets backup folder asynchronously. + * @return {Promise} + * @resolve the folder (the folder string path). + */ + getBackupFolder: function PB_getBackupFolder() { + return Task.spawn(function() { + if (this._folder) { + throw new Task.Result(this._folder); + } + let profileDir = OS.Constants.Path.profileDir; + let backupsDirPath = OS.Path.join(profileDir, this.profileRelativeFolderPath); + yield OS.File.makeDir(backupsDirPath, { ignoreExisting: true }).then( + function onSuccess() { + this._folder = backupsDirPath; + }.bind(this), + function onError() { + throw("Unable to create bookmarks backup folder"); + }); + throw new Task.Result(this._folder); + }.bind(this)); + }, + get profileRelativeFolderPath() "bookmarkbackups", /** * Cache current backups in a sorted (by date DESC) array. */ get entries() { + Deprecated.warning( + "PlacesBackups.entries is deprecated and will be removed in a future version", + "https://bugzilla.mozilla.org/show_bug.cgi?id=859695"); + delete this.entries; this.entries = []; let files = this.folder.directoryEntries; @@ -76,6 +110,44 @@ this.PlacesBackups = { return this.entries; }, + /** + * Cache current backups in a sorted (by date DESC) array. + * @return {Promise} + * @resolve a sorted array of string paths. + */ + getBackupFiles: function PB_getBackupFiles() { + return Task.spawn(function() { + if (this._backupFiles) { + throw new Task.Result(this._backupFiles); + } + this._backupFiles = []; + + let backupFolderPath = yield this.getBackupFolder(); + let iterator = new OS.File.DirectoryIterator(backupFolderPath); + yield iterator.forEach(function(aEntry) { + let matches = aEntry.name.match(this._filenamesRegex); + if (matches) { + // Remove bogus backups in future dates. + let filePath = aEntry.path; + if (this.getDateForFile(filePath) > new Date()) { + return OS.File.remove(filePath); + } else { + this._backupFiles.push(filePath); + } + } + }.bind(this)); + iterator.close(); + + this._backupFiles.sort(function(a, b) { + let aDate = this.getDateForFile(a); + let bDate = this.getDateForFile(b); + return aDate < bDate ? 1 : aDate > bDate ? -1 : 0; + }.bind(this)); + + throw new Task.Result(this._backupFiles); + }.bind(this)); + }, + /** * Creates a filename for bookmarks backup files. * @@ -96,11 +168,12 @@ this.PlacesBackups = { * creation date. * * @param aBackupFile - * nsIFile of the backup. + * nsIFile or string path of the backup. * @return A Date object for the backup's creation time. */ getDateForFile: function PB_getDateForFile(aBackupFile) { - let filename = aBackupFile.leafName; + let filename = (aBackupFile instanceof Ci.nsIFile) ? aBackupFile.leafName + : OS.Path.basename(aBackupFile); let matches = filename.match(this._filenamesRegex); if (!matches) throw("Invalid backup file name: " + filename); @@ -116,6 +189,10 @@ this.PlacesBackups = { * @returns nsIFile backup file */ getMostRecent: function PB_getMostRecent(aFileExt) { + Deprecated.warning( + "PlacesBackups.getMostRecent is deprecated and will be removed in a future version", + "https://bugzilla.mozilla.org/show_bug.cgi?id=859695"); + let fileExt = aFileExt || "(json|html)"; for (let i = 0; i < this.entries.length; i++) { let rx = new RegExp("\." + fileExt + "$"); @@ -125,6 +202,29 @@ this.PlacesBackups = { return null; }, + /** + * Get the most recent backup file. + * + * @param [optional] aFileExt + * Force file extension. Either "html" or "json". + * Will check for both if not defined. + * @return {Promise} + * @result the path to the file. + */ + getMostRecentBackup: function PB_getMostRecentBackup(aFileExt) { + return Task.spawn(function() { + let fileExt = aFileExt || "(json|html)"; + let entries = yield this.getBackupFiles(); + for (let entry of entries) { + let rx = new RegExp("\." + fileExt + "$"); + if (OS.Path.basename(entry).match(rx)) { + throw new Task.Result(entry); + } + } + throw new Task.Result(null); + }.bind(this)); + }, + /** * Serializes bookmarks using JSON, and writes to the supplied file. * Note: any item that should not be backed up must be annotated with @@ -137,17 +237,16 @@ this.PlacesBackups = { */ saveBookmarksToJSONFile: function PB_saveBookmarksToJSONFile(aFile) { return Task.spawn(function() { - if (!aFile.exists()) - aFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0600", 8)); - if (!aFile.exists() || !aFile.isWritable()) { - throw new Error("Unable to create bookmarks backup file: " + aFile.leafName); - } - let nodeCount = yield BookmarkJSONUtils.exportToFile(aFile); - if (aFile.parent.equals(this.folder)) { + let backupFolderPath = yield this.getBackupFolder(); + if (aFile.parent.path == backupFolderPath) { // Update internal cache. this.entries.push(aFile); + if (!this._backupFiles) { + yield this.getBackupFiles(); + } + this._backupFiles.push(aFile.path); } else { // If we are saving to a folder different than our backups folder, then // we also want to copy this new backup to it. @@ -156,19 +255,23 @@ this.PlacesBackups = { let name = this.getFilenameForDate(); let newFilename = this._appendMetaDataToFilename(name, { nodeCount: nodeCount }); - + let newFilePath = OS.Path.join(backupFolderPath, newFilename); let backupFile = yield this._getBackupFileForSameDate(name); + if (backupFile) { - backupFile.remove(false); + yield OS.File.remove(backupFile, { ignoreAbsent: true }); } else { - let file = this.folder.clone(); - file.append(newFilename); + let file = new FileUtils.File(newFilePath); // Update internal cache if we are not replacing an existing // backup file. this.entries.push(file); + if (!this._backupFiles) { + yield this.getBackupFiles(); + } + this._backupFiles.push(file.path); } - aFile.copyTo(this.folder, newFilename); + yield OS.File.copy(aFile.path, newFilePath); } throw new Task.Result(nodeCount); @@ -192,60 +295,71 @@ this.PlacesBackups = { return Task.spawn(function() { // Construct the new leafname. let newBackupFilename = this.getFilenameForDate(); - let mostRecentBackupFile = this.getMostRecent(); + let mostRecentBackupFile = yield this.getMostRecentBackup(); if (!aForceBackup) { let numberOfBackupsToDelete = 0; - if (aMaxBackups !== undefined && aMaxBackups > -1) - numberOfBackupsToDelete = this.entries.length - aMaxBackups; + if (aMaxBackups !== undefined && aMaxBackups > -1) { + let backupFiles = yield this.getBackupFiles(); + numberOfBackupsToDelete = backupFiles.length - aMaxBackups; + } if (numberOfBackupsToDelete > 0) { // If we don't have today's backup, remove one more so that // the total backups after this operation does not exceed the // number specified in the pref. if (!mostRecentBackupFile || - !this._isFilenameWithSameDate(mostRecentBackupFile.leafName, + !this._isFilenameWithSameDate(OS.Path.basename(mostRecentBackupFile), newBackupFilename)) numberOfBackupsToDelete++; while (numberOfBackupsToDelete--) { - let oldestBackup = this.entries.pop(); - oldestBackup.remove(false); + this.entries.pop(); + if (!this._backupFiles) { + yield this.getBackupFiles(); + } + let oldestBackup = this._backupFiles.pop(); + yield OS.File.remove(oldestBackup); } } // Do nothing if we already have this backup or we don't want backups. if (aMaxBackups === 0 || (mostRecentBackupFile && - this._isFilenameWithSameDate(mostRecentBackupFile.leafName, + this._isFilenameWithSameDate(OS.Path.basename(mostRecentBackupFile), newBackupFilename))) return; } let backupFile = yield this._getBackupFileForSameDate(newBackupFilename); if (backupFile) { - if (aForceBackup) - backupFile.remove(false); - else + if (aForceBackup) { + yield OS.File.remove(backupFile, { ignoreAbsent: true }); + } else { return; + } } // Save bookmarks to a backup file. - let newBackupFile = this.folder.clone(); + let backupFolderPath = yield this.getBackupFolder(); + let backupFolder = new FileUtils.File(backupFolderPath); + let newBackupFile = backupFolder.clone(); newBackupFile.append(newBackupFilename); - let nodeCount = yield this.saveBookmarksToJSONFile(newBackupFile); + let nodeCount = yield this.saveBookmarksToJSONFile(newBackupFile); // Rename the filename with metadata. let newFilenameWithMetaData = this._appendMetaDataToFilename( - newBackupFile.leafName, + newBackupFilename, { nodeCount: nodeCount }); - newBackupFile.moveTo(this.folder, newFilenameWithMetaData); + newBackupFile.moveTo(backupFolder, newFilenameWithMetaData); // Update internal cache. - let newFileWithMetaData = this.folder.clone(); + let newFileWithMetaData = backupFolder.clone(); newFileWithMetaData.append(newFilenameWithMetaData); this.entries.pop(); this.entries.push(newFileWithMetaData); + this._backupFiles.pop(); + this._backupFiles.push(newFileWithMetaData.path); }.bind(this)); }, @@ -260,14 +374,15 @@ this.PlacesBackups = { /** * Gets the bookmark count for backup file. * - * @param aFile - * String The backup file. + * @param aFilePath + * File path The backup file. * * @return the bookmark count or null. */ - getBookmarkCountForFile: function PB_getBookmarkCountForFile(aFile) { + getBookmarkCountForFile: function PB_getBookmarkCountForFile(aFilePath) { let count = null; - let matches = aFile.leafName.match(this._filenamesRegex); + let filename = OS.Path.basename(aFilePath); + let matches = filename.match(this._filenamesRegex); if (matches && matches[3]) count = matches[3].replace(/_/g, ""); @@ -288,12 +403,13 @@ this.PlacesBackups = { _getBackupFileForSameDate: function PB__getBackupFileForSameDate(aFilename) { return Task.spawn(function() { - let iterator = new OS.File.DirectoryIterator(this.folder.path); + let backupFolderPath = yield this.getBackupFolder(); + let iterator = new OS.File.DirectoryIterator(backupFolderPath); let backupFile; yield iterator.forEach(function(aEntry) { if (this._isFilenameWithSameDate(aEntry.name, aFilename)) { - backupFile = new FileUtils.File(aEntry.path); + backupFile = aEntry.path; return iterator.close(); } }.bind(this)); diff --git a/toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js b/toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js index 4e762778ccc2..a9b220ea3908 100644 --- a/toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js +++ b/toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js @@ -9,39 +9,40 @@ const NUMBER_OF_BACKUPS = 1; function run_test() { do_test_pending(); - // Get bookmarkBackups directory - var bookmarksBackupDir = PlacesBackups.folder; - - // Create an html dummy backup in the past - var htmlBackupFile = bookmarksBackupDir.clone(); - htmlBackupFile.append("bookmarks-2008-01-01.html"); - if (htmlBackupFile.exists()) - htmlBackupFile.remove(false); - do_check_false(htmlBackupFile.exists()); - htmlBackupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0600); - do_check_true(htmlBackupFile.exists()); - - // Create a json dummy backup in the past - var jsonBackupFile = bookmarksBackupDir.clone(); - jsonBackupFile.append("bookmarks-2008-01-31.json"); - if (jsonBackupFile.exists()) - jsonBackupFile.remove(false); - do_check_false(jsonBackupFile.exists()); - jsonBackupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0600); - do_check_true(jsonBackupFile.exists()); - - // Export bookmarks to JSON. - var backupFilename = PlacesBackups.getFilenameForDate(); - var rx = new RegExp("^" + backupFilename.replace(/\.json/, "") + "(_[0-9]+){0,1}\.json$"); - var files = bookmarksBackupDir.directoryEntries; - var entry; - while (files.hasMoreElements()) { - entry = files.getNext().QueryInterface(Ci.nsIFile); - if (entry.leafName.match(rx)) - entry.remove(false); - } - Task.spawn(function() { + // Get bookmarkBackups directory + let backupFolder = yield PlacesBackups.getBackupFolder(); + let bookmarksBackupDir = new FileUtils.File(backupFolder); + + // Create an html dummy backup in the past + var htmlBackupFile = bookmarksBackupDir.clone(); + htmlBackupFile.append("bookmarks-2008-01-01.html"); + if (htmlBackupFile.exists()) + htmlBackupFile.remove(false); + do_check_false(htmlBackupFile.exists()); + htmlBackupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0600); + do_check_true(htmlBackupFile.exists()); + + // Create a json dummy backup in the past + var jsonBackupFile = bookmarksBackupDir.clone(); + jsonBackupFile.append("bookmarks-2008-01-31.json"); + if (jsonBackupFile.exists()) + jsonBackupFile.remove(false); + do_check_false(jsonBackupFile.exists()); + jsonBackupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0600); + do_check_true(jsonBackupFile.exists()); + + // Export bookmarks to JSON. + var backupFilename = PlacesBackups.getFilenameForDate(); + var rx = new RegExp("^" + backupFilename.replace(/\.json/, "") + "(_[0-9]+){0,1}\.json$"); + var files = bookmarksBackupDir.directoryEntries; + var entry; + while (files.hasMoreElements()) { + entry = files.getNext().QueryInterface(Ci.nsIFile); + if (entry.leafName.match(rx)) + entry.remove(false); + } + yield PlacesBackups.create(NUMBER_OF_BACKUPS); files = bookmarksBackupDir.directoryEntries; while (files.hasMoreElements()) { diff --git a/toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js b/toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js index 6f0c79589788..9ba7b848c724 100644 --- a/toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js +++ b/toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js @@ -7,48 +7,50 @@ function run_test() { do_test_pending(); - let bookmarksBackupDir = PlacesBackups.folder; - // Remove all files from backups folder. - let files = bookmarksBackupDir.directoryEntries; - while (files.hasMoreElements()) { - let entry = files.getNext().QueryInterface(Ci.nsIFile); - entry.remove(false); - } - - // Create a json dummy backup in the future. - let dateObj = new Date(); - dateObj.setYear(dateObj.getFullYear() + 1); - let name = PlacesBackups.getFilenameForDate(dateObj); - do_check_eq(name, "bookmarks-" + dateObj.toLocaleFormat("%Y-%m-%d") + ".json"); - let rx = new RegExp("^" + name.replace(/\.json/, "") + "(_[0-9]+){0,1}\.json$"); - let files = bookmarksBackupDir.directoryEntries; - while (files.hasMoreElements()) { - let entry = files.getNext().QueryInterface(Ci.nsIFile); - if (entry.leafName.match(rx)) - entry.remove(false); - } - - let futureBackupFile = bookmarksBackupDir.clone(); - futureBackupFile.append(name); - futureBackupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0600); - do_check_true(futureBackupFile.exists()); - - do_check_eq(PlacesBackups.entries.length, 0); - Task.spawn(function() { + let backupFolder = yield PlacesBackups.getBackupFolder(); + let bookmarksBackupDir = new FileUtils.File(backupFolder); + // Remove all files from backups folder. + let files = bookmarksBackupDir.directoryEntries; + while (files.hasMoreElements()) { + let entry = files.getNext().QueryInterface(Ci.nsIFile); + entry.remove(false); + } + + // Create a json dummy backup in the future. + let dateObj = new Date(); + dateObj.setYear(dateObj.getFullYear() + 1); + let name = PlacesBackups.getFilenameForDate(dateObj); + do_check_eq(name, "bookmarks-" + dateObj.toLocaleFormat("%Y-%m-%d") + ".json"); + let rx = new RegExp("^" + name.replace(/\.json/, "") + "(_[0-9]+){0,1}\.json$"); + let files = bookmarksBackupDir.directoryEntries; + while (files.hasMoreElements()) { + let entry = files.getNext().QueryInterface(Ci.nsIFile); + if (entry.leafName.match(rx)) + entry.remove(false); + } + + let futureBackupFile = bookmarksBackupDir.clone(); + futureBackupFile.append(name); + futureBackupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0600); + do_check_true(futureBackupFile.exists()); + + do_check_eq((yield PlacesBackups.getBackupFiles()).length, 0); + yield PlacesBackups.create(); // Check that a backup for today has been created. - do_check_eq(PlacesBackups.entries.length, 1); - let mostRecentBackupFile = PlacesBackups.getMostRecent(); + do_check_eq((yield PlacesBackups.getBackupFiles()).length, 1); + let mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup(); do_check_neq(mostRecentBackupFile, null); let todayFilename = PlacesBackups.getFilenameForDate(); rx = new RegExp("^" + todayFilename.replace(/\.json/, "") + "(_[0-9]+){0,1}\.json$"); - do_check_true(mostRecentBackupFile.leafName.match(rx).length > 0); + do_check_true(OS.Path.basename(mostRecentBackupFile).match(rx).length > 0); // Check that future backup has been removed. do_check_false(futureBackupFile.exists()); // Cleanup. + mostRecentBackupFile = new FileUtils.File(mostRecentBackupFile); mostRecentBackupFile.remove(false); do_check_false(mostRecentBackupFile.exists()); diff --git a/toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js b/toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js index 7fe64805c20d..18323756e0b8 100644 --- a/toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js +++ b/toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js @@ -30,23 +30,23 @@ add_task(function test_saveBookmarksToJSONFile_and_create() // Ensure the backup would be copied to our backups folder when the original // backup is saved somewhere else. - let recentBackup = PlacesBackups.getMostRecent(); + let recentBackup = yield PlacesBackups.getMostRecentBackup(); let todayFilename = PlacesBackups.getFilenameForDate(); - do_check_eq(recentBackup.leafName, + do_check_eq(OS.Path.basename(recentBackup), todayFilename.replace(/\.json/, "_" + nodeCount + ".json")); // Clear all backups in our backups folder. yield PlacesBackups.create(0); - do_check_eq(PlacesBackups.entries.length, 0); + do_check_eq((yield PlacesBackups.getBackupFiles()).length, 0); // Test create() which saves bookmarks with metadata on the filename. yield PlacesBackups.create(); - do_check_eq(PlacesBackups.entries.length, 1); + do_check_eq((yield PlacesBackups.getBackupFiles()).length, 1); - mostRecentBackupFile = PlacesBackups.getMostRecent(); + mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup(); do_check_neq(mostRecentBackupFile, null); let rx = new RegExp("^" + todayFilename.replace(/\.json/, "") + "_([0-9]+)\.json$"); - let matches = mostRecentBackupFile.leafName.match(rx); + let matches = OS.Path.basename(recentBackup).match(rx); do_check_true(matches.length > 0 && parseInt(matches[1]) == nodeCount); // Cleanup diff --git a/toolkit/components/places/tests/head_common.js b/toolkit/components/places/tests/head_common.js index 0edae7969e12..e4a95f64c030 100644 --- a/toolkit/components/places/tests/head_common.js +++ b/toolkit/components/places/tests/head_common.js @@ -37,6 +37,8 @@ XPCOMUtils.defineLazyModuleGetter(this, "BookmarkJSONUtils", "resource://gre/modules/BookmarkJSONUtils.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "PlacesBackups", "resource://gre/modules/PlacesBackups.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); // This imports various other objects in addition to PlacesUtils. Cu.import("resource://gre/modules/PlacesUtils.jsm"); diff --git a/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js b/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js index a2aa64de8ce0..5ae169dd678d 100644 --- a/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js +++ b/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js @@ -44,7 +44,7 @@ add_task(function test_corrupt_file() { true); // Check that bookmarks that are not corrupt have been imported. - yield Task.spawn(database_check); + yield database_check(); }); add_task(function test_corrupt_database() { @@ -66,7 +66,7 @@ add_task(function test_corrupt_database() { // Import again and check for correctness. remove_all_bookmarks(); yield BookmarkHTMLUtils.importFromFile(bookmarksFile, true); - yield Task.spawn(database_check); + yield database_check(); }); /* @@ -77,113 +77,122 @@ add_task(function test_corrupt_database() { * @rejects Never. */ function database_check() { - // BOOKMARKS MENU - var query = hs.getNewQuery(); - query.setFolders([bs.bookmarksMenuFolder], 1); - var options = hs.getNewQueryOptions(); - options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS; - var result = hs.executeQuery(query, options); - var rootNode = result.root; - rootNode.containerOpen = true; - do_check_eq(rootNode.childCount, 2); + return Task.spawn(function() { + // BOOKMARKS MENU + var query = hs.getNewQuery(); + query.setFolders([bs.bookmarksMenuFolder], 1); + var options = hs.getNewQueryOptions(); + options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS; + var result = hs.executeQuery(query, options); + var rootNode = result.root; + rootNode.containerOpen = true; + do_check_eq(rootNode.childCount, 2); - // get test folder - var testFolder = rootNode.getChild(1); - do_check_eq(testFolder.type, testFolder.RESULT_TYPE_FOLDER); - do_check_eq(testFolder.title, "test"); - // add date - do_check_eq(bs.getItemDateAdded(testFolder.itemId)/1000000, 1177541020); - // last modified - do_check_eq(bs.getItemLastModified(testFolder.itemId)/1000000, 1177541050); - testFolder = testFolder.QueryInterface(Ci.nsINavHistoryQueryResultNode); - do_check_eq(testFolder.hasChildren, true); - // folder description - do_check_true(as.itemHasAnnotation(testFolder.itemId, - DESCRIPTION_ANNO)); - do_check_eq("folder test comment", - as.getItemAnnotation(testFolder.itemId, DESCRIPTION_ANNO)); - // open test folder, and test the children - testFolder.containerOpen = true; - var cc = testFolder.childCount; - do_check_eq(cc, 1); + // get test folder + var testFolder = rootNode.getChild(1); + do_check_eq(testFolder.type, testFolder.RESULT_TYPE_FOLDER); + do_check_eq(testFolder.title, "test"); + // add date + do_check_eq(bs.getItemDateAdded(testFolder.itemId)/1000000, 1177541020); + // last modified + do_check_eq(bs.getItemLastModified(testFolder.itemId)/1000000, 1177541050); + testFolder = testFolder.QueryInterface(Ci.nsINavHistoryQueryResultNode); + do_check_eq(testFolder.hasChildren, true); + // folder description + do_check_true(as.itemHasAnnotation(testFolder.itemId, + DESCRIPTION_ANNO)); + do_check_eq("folder test comment", + as.getItemAnnotation(testFolder.itemId, DESCRIPTION_ANNO)); + // open test folder, and test the children + testFolder.containerOpen = true; + var cc = testFolder.childCount; + do_check_eq(cc, 1); - // test bookmark 1 - var testBookmark1 = testFolder.getChild(0); - // url - do_check_eq("http://test/post", testBookmark1.uri); - // title - do_check_eq("test post keyword", testBookmark1.title); - // keyword - do_check_eq("test", bs.getKeywordForBookmark(testBookmark1.itemId)); - // sidebar - do_check_true(as.itemHasAnnotation(testBookmark1.itemId, - LOAD_IN_SIDEBAR_ANNO)); - // add date - do_check_eq(testBookmark1.dateAdded/1000000, 1177375336); - // last modified - do_check_eq(testBookmark1.lastModified/1000000, 1177375423); - // post data - do_check_true(as.itemHasAnnotation(testBookmark1.itemId, - POST_DATA_ANNO)); - do_check_eq("hidden1%3Dbar&text1%3D%25s", - as.getItemAnnotation(testBookmark1.itemId, POST_DATA_ANNO)); - // last charset - var testURI = uri(testBookmark1.uri); - do_check_eq((yield PlacesUtils.getCharsetForURI(testURI)), "ISO-8859-1"); + // test bookmark 1 + var testBookmark1 = testFolder.getChild(0); + // url + do_check_eq("http://test/post", testBookmark1.uri); + // title + do_check_eq("test post keyword", testBookmark1.title); + // keyword + do_check_eq("test", bs.getKeywordForBookmark(testBookmark1.itemId)); + // sidebar + do_check_true(as.itemHasAnnotation(testBookmark1.itemId, + LOAD_IN_SIDEBAR_ANNO)); + // add date + do_check_eq(testBookmark1.dateAdded/1000000, 1177375336); + // last modified + do_check_eq(testBookmark1.lastModified/1000000, 1177375423); + // post data + do_check_true(as.itemHasAnnotation(testBookmark1.itemId, + POST_DATA_ANNO)); + do_check_eq("hidden1%3Dbar&text1%3D%25s", + as.getItemAnnotation(testBookmark1.itemId, POST_DATA_ANNO)); + // last charset + var testURI = uri(testBookmark1.uri); + do_check_eq((yield PlacesUtils.getCharsetForURI(testURI)), "ISO-8859-1"); - // description - do_check_true(as.itemHasAnnotation(testBookmark1.itemId, - DESCRIPTION_ANNO)); - do_check_eq("item description", - as.getItemAnnotation(testBookmark1.itemId, - DESCRIPTION_ANNO)); + // description + do_check_true(as.itemHasAnnotation(testBookmark1.itemId, + DESCRIPTION_ANNO)); + do_check_eq("item description", + as.getItemAnnotation(testBookmark1.itemId, + DESCRIPTION_ANNO)); - // clean up - testFolder.containerOpen = false; - rootNode.containerOpen = false; + // clean up + testFolder.containerOpen = false; + rootNode.containerOpen = false; - // BOOKMARKS TOOLBAR - query.setFolders([bs.toolbarFolder], 1); - result = hs.executeQuery(query, hs.getNewQueryOptions()); - var toolbar = result.root; - toolbar.containerOpen = true; - do_check_eq(toolbar.childCount, 3); + // BOOKMARKS TOOLBAR + query.setFolders([bs.toolbarFolder], 1); + result = hs.executeQuery(query, hs.getNewQueryOptions()); + var toolbar = result.root; + toolbar.containerOpen = true; + do_check_eq(toolbar.childCount, 3); - // livemark - var livemark = toolbar.getChild(1); - // title - do_check_eq("Latest Headlines", livemark.title); - PlacesUtils.livemarks.getLivemark( - { id: livemark.itemId }, - function (aStatus, aLivemark) { - do_check_true(Components.isSuccessCode(aStatus)); - do_check_eq("http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/", - aLivemark.siteURI.spec); - do_check_eq("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml", - aLivemark.feedURI.spec); - } - ); + // livemark + var livemark = toolbar.getChild(1); + // title + do_check_eq("Latest Headlines", livemark.title); - // cleanup - toolbar.containerOpen = false; + let deferGetLivemark = Promise.defer(); + PlacesUtils.livemarks.getLivemark( + { id: livemark.itemId }, + function (aStatus, aLivemark) { + do_check_true(Components.isSuccessCode(aStatus)); + do_check_eq("http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/", + aLivemark.siteURI.spec); + do_check_eq("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml", + aLivemark.feedURI.spec); + deferGetLivemark.resolve(); + } + ); + yield deferGetLivemark.promise; - // UNFILED BOOKMARKS - query.setFolders([bs.unfiledBookmarksFolder], 1); - result = hs.executeQuery(query, hs.getNewQueryOptions()); - var unfiledBookmarks = result.root; - unfiledBookmarks.containerOpen = true; - do_check_eq(unfiledBookmarks.childCount, 1); - unfiledBookmarks.containerOpen = false; + // cleanup + toolbar.containerOpen = false; - // favicons - icos.getFaviconDataForPage(uri(TEST_FAVICON_PAGE_URL), - function DC_onComplete(aURI, aDataLen, aData, aMimeType) { - // aURI should never be null when aDataLen > 0. - do_check_neq(aURI, null); - // Favicon data is stored in the bookmarks file as a "data:" URI. For - // simplicity, instead of converting the data we receive to a "data:" URI - // and comparing it, we just check the data size. - do_check_eq(TEST_FAVICON_DATA_SIZE, aDataLen); - } - ); + // UNFILED BOOKMARKS + query.setFolders([bs.unfiledBookmarksFolder], 1); + result = hs.executeQuery(query, hs.getNewQueryOptions()); + var unfiledBookmarks = result.root; + unfiledBookmarks.containerOpen = true; + do_check_eq(unfiledBookmarks.childCount, 1); + unfiledBookmarks.containerOpen = false; + + // favicons + let deferGetFaviconData = Promise.defer(); + icos.getFaviconDataForPage(uri(TEST_FAVICON_PAGE_URL), + function DC_onComplete(aURI, aDataLen, aData, aMimeType) { + // aURI should never be null when aDataLen > 0. + do_check_neq(aURI, null); + // Favicon data is stored in the bookmarks file as a "data:" URI. For + // simplicity, instead of converting the data we receive to a "data:" URI + // and comparing it, we just check the data size. + do_check_eq(TEST_FAVICON_DATA_SIZE, aDataLen); + deferGetFaviconData.resolve(); + } + ); + yield deferGetFaviconData.promise; + }); } diff --git a/toolkit/components/places/tests/unit/test_utils_backups_create.js b/toolkit/components/places/tests/unit/test_utils_backups_create.js index 82beb8d2f6b7..92c87481cd24 100644 --- a/toolkit/components/places/tests/unit/test_utils_backups_create.js +++ b/toolkit/components/places/tests/unit/test_utils_backups_create.js @@ -32,32 +32,32 @@ function run_test() { // Sort dates from oldest to newest. dates.sort(); - // Get and cleanup the backups folder. - var bookmarksBackupDir = PlacesBackups.folder; - - // Fake backups are created backwards to ensure we won't consider file - // creation time. - // Create fake backups for the newest dates. - for (let i = dates.length - 1; i >= 0; i--) { - let backupFilename; - if (i > Math.floor(dates.length/2)) - backupFilename = PREFIX + dates[i] + SUFFIX; - else - backupFilename = LOCALIZED_PREFIX + dates[i] + SUFFIX; - dump("creating: " + backupFilename + "\n"); - let backupFile = bookmarksBackupDir.clone(); - backupFile.append(backupFilename); - backupFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0666); - do_check_true(backupFile.exists()); - } - - // Replace PlacesUtils getFormattedString so that it will return the localized - // string we want. - PlacesUtils.getFormattedString = function (aKey, aValue) { - return LOCALIZED_PREFIX + aValue; - } - Task.spawn(function() { + // Get and cleanup the backups folder. + let backupFolderPath = yield PlacesBackups.getBackupFolder(); + let bookmarksBackupDir = new FileUtils.File(backupFolderPath); + + // Fake backups are created backwards to ensure we won't consider file + // creation time. + // Create fake backups for the newest dates. + for (let i = dates.length - 1; i >= 0; i--) { + let backupFilename; + if (i > Math.floor(dates.length/2)) + backupFilename = PREFIX + dates[i] + SUFFIX; + else + backupFilename = LOCALIZED_PREFIX + dates[i] + SUFFIX; + let backupFile = bookmarksBackupDir.clone(); + backupFile.append(backupFilename); + backupFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0666); + do_check_true(backupFile.exists()); + } + + // Replace PlacesUtils getFormattedString so that it will return the localized + // string we want. + PlacesUtils.getFormattedString = function (aKey, aValue) { + return LOCALIZED_PREFIX + aValue; + } + yield PlacesBackups.create(Math.floor(dates.length/2)); // Add today's backup. dates.push(dateObj.toLocaleFormat("%Y-%m-%d")); @@ -100,9 +100,6 @@ function run_test() { } do_check_false(bookmarksBackupDir.directoryEntries.hasMoreElements()); - // Recreate the folder. - PlacesBackups.folder; - do_test_finished(); }); } diff --git a/xpcom/build/mozPoisonWriteMac.cpp b/xpcom/build/mozPoisonWriteMac.cpp index bd28532e3bb5..078d3c3b8dc4 100644 --- a/xpcom/build/mozPoisonWriteMac.cpp +++ b/xpcom/build/mozPoisonWriteMac.cpp @@ -192,7 +192,7 @@ void AbortOnBadWrite(int fd, const void *wbuf, size_t count) { if (!ValidWriteAssert(pos != -1)) return; ssize_t r = read(fd, wbuf2, count); - if (!ValidWriteAssert(r == count)) + if (!ValidWriteAssert(r == static_cast(count))) return; int cmp = memcmp(wbuf, wbuf2, count); if (!ValidWriteAssert(cmp == 0))