tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

commit dddfa6d699551d0fe0167377ea1b59fe755cc5e2
parent f3b66ee0060939a17048c33284d89ee949f7d470
Author: serge-sans-paille <sguelton@mozilla.com>
Date:   Tue, 14 Oct 2025 14:20:29 +0000

Bug 1769188 - Replace all instances of MOZ_TRY_VAR by MOZ_TRY r=emilio,profiler-reviewers,win-reviewers,firefox-style-system-reviewers,layout-reviewers,dom-worker-reviewers,canaltinova,gstoll

According to the doc of mfbt/Try.h, MOZ_TRY_VAR is obsolete. Yet it was
used a lot across the code base.

Solely relying on MOZ_TRY is both nicer to the eye and more generic, as
it allows setting variable that don't have a default constructor, and
event sometimes more efficient, if the default constructor is
non-trivial.

Differential Revision: https://phabricator.services.mozilla.com/D268466

Diffstat:
Mdocshell/base/nsDocShell.cpp | 5++---
Mdom/base/nsDOMWindowUtils.cpp | 22++++++++++------------
Mdom/ipc/ProcessIsolation.cpp | 6++----
Mdom/media/flac/FlacFrameParser.cpp | 28+++++++++++-----------------
Mdom/media/gtest/TestMediaDataEncoder.cpp | 8++++----
Mdom/media/mediasource/ContainerParser.cpp | 9+++------
Mdom/media/mp3/MP3FrameParser.cpp | 40++++++++++++++++------------------------
Mdom/media/mp4/MoofParser.cpp | 217++++++++++++++++++++++++++++++++-----------------------------------------------
Mdom/media/mp4/SinfParser.cpp | 18+++++++-----------
Mdom/media/platforms/agnostic/bytestreams/AnnexB.cpp | 26++++++++++----------------
Mdom/media/platforms/agnostic/bytestreams/H264.cpp | 13+++++--------
Mdom/media/platforms/ffmpeg/FFmpegVideoEncoder.cpp | 16++++++----------
Mdom/media/webcodecs/VideoFrame.cpp | 136++++++++++++++++++++++++++++++++++---------------------------------------------
Mdom/notification/NotificationUtils.cpp | 4++--
Mdom/quota/QuotaCommon.h | 9++++-----
Mdom/serviceworkers/ServiceWorkerManager.cpp | 10++++------
Mdom/serviceworkers/ServiceWorkerPrivate.cpp | 3+--
Mextensions/pref/autoconfig/src/nsAutoConfig.cpp | 5++---
Mgfx/tests/fuzz/TestMoz2D.cpp | 40++++++++++++++++++----------------------
Mjs/public/Result.h | 6+++---
Mjs/src/builtin/temporal/TemporalParser.cpp | 130+++++++++++++++++++++++++++++++++++++-------------------------------------------
Mjs/src/frontend/FoldConstants.h | 2+-
Mjs/src/frontend/FullParseHandler.h | 21++++++++-------------
Mjs/src/frontend/ParseNode.cpp | 3+--
Mjs/src/frontend/Parser.cpp | 1025++++++++++++++++++++++++++++++++-----------------------------------------------
Mjs/src/jit/WarpOracle.cpp | 13+++++--------
Mjs/src/vm/BigIntType.cpp | 3+--
Mjs/src/vm/JSContext.h | 2+-
Mjs/xpconnect/loader/ScriptPreloader.cpp | 6++----
Mjs/xpconnect/loader/URLPreloader.cpp | 17++++++-----------
Mjs/xpconnect/loader/mozJSModuleLoader.cpp | 3+--
Mjs/xpconnect/src/XPCComponents.cpp | 4++--
Mlayout/generic/nsIFrame.cpp | 4+---
Mlayout/style/PreloadedStyleSheet.cpp | 5++---
Mlayout/xul/tree/nsTreeBodyFrame.cpp | 5++---
Mmfbt/Try.h | 9---------
Mmfbt/tests/TestResult.cpp | 14--------------
Mmodules/libpref/Preferences.cpp | 31++++++++++---------------------
Mmozglue/android/APKOpen.cpp | 3+--
Mmozglue/misc/PreXULSkeletonUI.cpp | 85+++++++++++++++++++++++++++----------------------------------------------------
Mnetwerk/base/SimpleChannel.cpp | 4++--
Mnetwerk/protocol/res/ExtensionProtocolHandler.cpp | 13+++++--------
Msecurity/manager/ssl/nsNSSCertificateDB.cpp | 3+--
Mstartupcache/StartupCache.cpp | 11+++++------
Mtoolkit/components/backgroundhangmonitor/HangDetails.cpp | 43+++++++++++++++++--------------------------
Mtoolkit/components/extensions/ExtensionPolicyService.cpp | 3+--
Mtoolkit/components/glean/bindings/private/Ping.cpp | 85+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mtoolkit/components/startup/nsAppStartup.cpp | 6++----
Mtoolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp | 19++++++++-----------
Mtoolkit/components/viaduct/ViaductRequest.cpp | 11++++-------
Mtoolkit/mozapps/defaultagent/DefaultPDF.cpp | 5+----
Mtoolkit/mozapps/defaultagent/Registry.cpp | 6++----
Mtoolkit/mozapps/extensions/AddonManagerStartup.cpp | 26++++++++++----------------
Mtoolkit/xre/nsAppRunner.cpp | 15+++++----------
Mtools/fuzzing/common/FuzzingBufferReader.h | 7+++----
Mtools/profiler/core/platform.cpp | 14++++++--------
Mwidget/RemoteLookAndFeel.cpp | 12+++++-------
Mwidget/windows/filedialog/WinFileDialogCommands.cpp | 6++----
Mwidget/windows/nsWindow.cpp | 4++--
Mxpcom/base/MemoryTelemetry.cpp | 3+--
Mxpcom/base/nsINIParser.cpp | 3+--
Mxpcom/glue/standalone/nsXPCOMGlue.cpp | 3+--
Mxpcom/io/nsAnonymousTemporaryFile.cpp | 4++--
Mxpcom/string/nsTSubstring.h | 4++--
Mxpcom/threads/CPUUsageWatcher.cpp | 12++++--------
65 files changed, 939 insertions(+), 1389 deletions(-)

diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp @@ -5137,9 +5137,8 @@ nsDocShell::RefreshURI(nsIURI* aURI, nsIPrincipal* aPrincipal, nsCOMPtr<nsPIDOMWindowOuter> win = GetWindow(); NS_ENSURE_TRUE(win, NS_ERROR_FAILURE); - nsCOMPtr<nsITimer> timer; - MOZ_TRY_VAR(timer, NS_NewTimerWithCallback(refreshTimer, aDelay, - nsITimer::TYPE_ONE_SHOT)); + nsCOMPtr<nsITimer> timer = MOZ_TRY( + NS_NewTimerWithCallback(refreshTimer, aDelay, nsITimer::TYPE_ONE_SHOT)); mRefreshURIList->AppendElement(timer); // owning timer ref } diff --git a/dom/base/nsDOMWindowUtils.cpp b/dom/base/nsDOMWindowUtils.cpp @@ -1936,8 +1936,8 @@ Result<mozilla::LayoutDeviceRect, nsresult> nsDOMWindowUtils::ConvertTo( NS_IMETHODIMP nsDOMWindowUtils::ToScreenRectInCSSUnits(float aX, float aY, float aWidth, float aHeight, DOMRect** aResult) { - LayoutDeviceRect devRect; - MOZ_TRY_VAR(devRect, ConvertTo(aX, aY, aWidth, aHeight, CoordsType::Screen)); + LayoutDeviceRect devRect = + MOZ_TRY(ConvertTo(aX, aY, aWidth, aHeight, CoordsType::Screen)); nsPresContext* presContext = GetPresContext(); MOZ_ASSERT(presContext); @@ -1960,9 +1960,8 @@ nsDOMWindowUtils::ToScreenRectInCSSUnits(float aX, float aY, float aWidth, NS_IMETHODIMP nsDOMWindowUtils::ToScreenRect(float aX, float aY, float aWidth, float aHeight, DOMRect** aResult) { - LayoutDeviceRect devPixelsRect; - MOZ_TRY_VAR(devPixelsRect, - ConvertTo(aX, aY, aWidth, aHeight, CoordsType::Screen)); + LayoutDeviceRect devPixelsRect = + MOZ_TRY(ConvertTo(aX, aY, aWidth, aHeight, CoordsType::Screen)); ScreenRect rect = ViewAs<ScreenPixel>( devPixelsRect, PixelCastJustification::ScreenIsParentLayerForRoot); @@ -1976,9 +1975,8 @@ nsDOMWindowUtils::ToScreenRect(float aX, float aY, float aWidth, float aHeight, NS_IMETHODIMP nsDOMWindowUtils::ToTopLevelWidgetRect(float aX, float aY, float aWidth, float aHeight, DOMRect** aResult) { - LayoutDeviceRect rect; - MOZ_TRY_VAR(rect, - ConvertTo(aX, aY, aWidth, aHeight, CoordsType::TopLevelWidget)); + LayoutDeviceRect rect = + MOZ_TRY(ConvertTo(aX, aY, aWidth, aHeight, CoordsType::TopLevelWidget)); RefPtr<DOMRect> outRect = new DOMRect(mWindow); outRect->SetRect(rect.x, rect.y, rect.width, rect.height); @@ -3518,8 +3516,8 @@ nsDOMWindowUtils::GetFileReferences(const nsAString& aDatabaseName, int64_t aId, nsCOMPtr<nsPIDOMWindowOuter> window = do_QueryReferent(mWindow); NS_ENSURE_TRUE(window, NS_ERROR_FAILURE); - quota::PrincipalMetadata principalMetadata; - MOZ_TRY_VAR(principalMetadata, quota::GetInfoFromWindow(window)); + quota::PrincipalMetadata principalMetadata = + MOZ_TRY(quota::GetInfoFromWindow(window)); RefPtr<IndexedDatabaseManager> mgr = IndexedDatabaseManager::Get(); if (mgr) { @@ -3845,8 +3843,8 @@ nsDOMWindowUtils::AddSheet(nsIPreloadedStyleSheet* aSheet, nsCOMPtr<Document> doc = GetDocument(); NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE); - StyleSheet* sheet = nullptr; - MOZ_TRY_VAR(sheet, static_cast<PreloadedStyleSheet*>(aSheet)->GetSheet()); + StyleSheet* sheet = + MOZ_TRY(static_cast<PreloadedStyleSheet*>(aSheet)->GetSheet()); Document::additionalSheetType type = convertSheetType(aSheetType); return doc->AddAdditionalStyleSheet(type, sheet); diff --git a/dom/ipc/ProcessIsolation.cpp b/dom/ipc/ProcessIsolation.cpp @@ -792,8 +792,7 @@ Result<NavigationIsolationOptions, nsresult> IsolationOptionsForNavigation( // If the load has any special remote type handling, do so at this point. if (behavior != IsolationBehavior::WebContent) { - MOZ_TRY_VAR( - options.mRemoteType, + options.mRemoteType = MOZ_TRY( SpecialBehaviorRemoteType(behavior, aCurrentRemoteType, aParentWindow)); if (options.mRemoteType != aCurrentRemoteType && @@ -1035,8 +1034,7 @@ Result<WorkerIsolationOptions, nsresult> IsolationOptionsForWorker( } if (behavior != IsolationBehavior::WebContent) { - MOZ_TRY_VAR( - options.mRemoteType, + options.mRemoteType = MOZ_TRY( SpecialBehaviorRemoteType(behavior, preferredRemoteType, nullptr)); MOZ_LOG( diff --git a/dom/media/flac/FlacFrameParser.cpp b/dom/media/flac/FlacFrameParser.cpp @@ -69,8 +69,7 @@ Result<Ok, nsresult> FlacFrameParser::DecodeHeaderBlock(const uint8_t* aPacket, return Err(NS_ERROR_FAILURE); } } - uint8_t blockHeader; - MOZ_TRY_VAR(blockHeader, br.ReadU8()); + uint8_t blockHeader = MOZ_TRY(br.ReadU8()); // blockType is a misnomer as it could indicate here either a packet type // should it points to the start of a Flac in Ogg metadata, or an actual // block type as per the flac specification. @@ -82,18 +81,16 @@ Result<Ok, nsresult> FlacFrameParser::DecodeHeaderBlock(const uint8_t* aPacket, br.Remaining() != FLAC_STREAMINFO_SIZE + 12) { return Err(NS_ERROR_FAILURE); } - uint32_t major; - MOZ_TRY_VAR(major, br.ReadU8()); + uint32_t major = MOZ_TRY(br.ReadU8()); if (major != 1) { // unsupported version; return Err(NS_ERROR_FAILURE); } MOZ_TRY(br.ReadU8()); // minor version - uint32_t header; - MOZ_TRY_VAR(header, br.ReadU16()); + uint32_t header = MOZ_TRY(br.ReadU16()); mNumHeaders = Some(header); br.Read(4); // fLaC - MOZ_TRY_VAR(blockType, br.ReadU8()); + blockType = MOZ_TRY(br.ReadU8()); blockType &= BITMASK(7); // First METADATA_BLOCK_STREAMINFO if (blockType != FLAC_METADATA_TYPE_STREAMINFO) { @@ -102,8 +99,7 @@ Result<Ok, nsresult> FlacFrameParser::DecodeHeaderBlock(const uint8_t* aPacket, } } - uint32_t blockDataSize; - MOZ_TRY_VAR(blockDataSize, br.ReadU24()); + uint32_t blockDataSize = MOZ_TRY(br.ReadU24()); const uint8_t* blockDataStart = br.Peek(blockDataSize); if (!blockDataStart) { // Incomplete block. @@ -118,13 +114,12 @@ Result<Ok, nsresult> FlacFrameParser::DecodeHeaderBlock(const uint8_t* aPacket, return Err(NS_ERROR_FAILURE); } - MOZ_TRY_VAR(mMinBlockSize, br.ReadU16()); - MOZ_TRY_VAR(mMaxBlockSize, br.ReadU16()); - MOZ_TRY_VAR(mMinFrameSize, br.ReadU24()); - MOZ_TRY_VAR(mMaxFrameSize, br.ReadU24()); + mMinBlockSize = MOZ_TRY(br.ReadU16()); + mMaxBlockSize = MOZ_TRY(br.ReadU16()); + mMinFrameSize = MOZ_TRY(br.ReadU24()); + mMaxFrameSize = MOZ_TRY(br.ReadU24()); - uint64_t blob; - MOZ_TRY_VAR(blob, br.ReadU64()); + uint64_t blob = MOZ_TRY(br.ReadU64()); uint32_t sampleRate = (blob >> 44) & BITMASK(20); if (!sampleRate) { return Err(NS_ERROR_FAILURE); @@ -220,8 +215,7 @@ Result<bool, nsresult> FlacFrameParser::IsHeaderBlock(const uint8_t* aPacket, const uint8_t* signature = br.Read(4); if (signature && !memcmp(signature, "fLaC", 4)) { // Flac start header, must have STREAMINFO as first metadata block; - uint32_t blockType; - MOZ_TRY_VAR(blockType, br.ReadU8()); + uint32_t blockType = MOZ_TRY(br.ReadU8()); blockType &= 0x7f; return blockType == FLAC_METADATA_TYPE_STREAMINFO; } diff --git a/dom/media/gtest/TestMediaDataEncoder.cpp b/dom/media/gtest/TestMediaDataEncoder.cpp @@ -346,16 +346,16 @@ Result<Ok, nsresult> IsValidAVCC(const mozilla::MediaRawData* aSample, uint32_t nalLen; switch (aNALUSize) { case 1: - MOZ_TRY_VAR(nalLen, reader.ReadU8()); + nalLen = MOZ_TRY(reader.ReadU8()); break; case 2: - MOZ_TRY_VAR(nalLen, reader.ReadU16()); + nalLen = MOZ_TRY(reader.ReadU16()); break; case 3: - MOZ_TRY_VAR(nalLen, reader.ReadU24()); + nalLen = MOZ_TRY(reader.ReadU24()); break; case 4: - MOZ_TRY_VAR(nalLen, reader.ReadU32()); + nalLen = MOZ_TRY(reader.ReadU32()); break; default: return Err(NS_ERROR_INVALID_ARG); diff --git a/dom/media/mediasource/ContainerParser.cpp b/dom/media/mediasource/ContainerParser.cpp @@ -430,12 +430,9 @@ class MP4ContainerParser : public ContainerParser, }; while (reader.Remaining() >= 8) { - uint32_t tmp; - MOZ_TRY_VAR(tmp, reader.ReadU32()); - uint64_t size = tmp; + uint64_t size = MOZ_TRY(reader.ReadU32()); const uint8_t* typec = reader.Peek(4); - MOZ_TRY_VAR(tmp, reader.ReadU32()); - AtomType type(tmp); + AtomType type(MOZ_TRY(reader.ReadU32())); // We've seen fourcc not being ASCII in the wild. In this rare case, // print hex values instead of the ascii representation. if (isprint(typec[0]) && isprint(typec[1]) && isprint(typec[2]) && @@ -470,7 +467,7 @@ class MP4ContainerParser : public ContainerParser, } if (size == 1) { // 64 bits size. - MOZ_TRY_VAR(size, reader.ReadU64()); + size = MOZ_TRY(reader.ReadU64()); } else if (size == 0) { // Atom extends to the end of the buffer, it can't have what we're // looking for. diff --git a/dom/media/mp3/MP3FrameParser.cpp b/dom/media/mp3/MP3FrameParser.cpp @@ -404,17 +404,14 @@ Result<bool, nsresult> FrameParser::VBRHeader::ParseXing(BufferReader* aReader, MOZ_TRY(aReader->ReadU32()); mType = XING; - uint32_t flags; - MOZ_TRY_VAR(flags, aReader->ReadU32()); + uint32_t flags = MOZ_TRY(aReader->ReadU32()); if (flags & NUM_FRAMES) { - uint32_t frames; - MOZ_TRY_VAR(frames, aReader->ReadU32()); + uint32_t frames = MOZ_TRY(aReader->ReadU32()); mNumAudioFrames = Some(frames); } if (flags & NUM_BYTES) { - uint32_t bytes; - MOZ_TRY_VAR(bytes, aReader->ReadU32()); + uint32_t bytes = MOZ_TRY(aReader->ReadU32()); mNumBytes = Some(bytes); } if (flags & TOC && aReader->Remaining() >= vbr_header::TOC_SIZE) { @@ -424,22 +421,18 @@ Result<bool, nsresult> FrameParser::VBRHeader::ParseXing(BufferReader* aReader, } else { mTOC.clear(); mTOC.reserve(vbr_header::TOC_SIZE); - uint8_t data; for (size_t i = 0; i < vbr_header::TOC_SIZE; ++i) { - MOZ_TRY_VAR(data, aReader->ReadU8()); + uint8_t data = MOZ_TRY(aReader->ReadU8()); mTOC.push_back( AssertedCast<uint32_t>(1.0f / 256.0f * data * mNumBytes.value())); } } } if (flags & VBR_SCALE) { - uint32_t scale; - MOZ_TRY_VAR(scale, aReader->ReadU32()); - mScale = Some(scale); + mScale = Some(MOZ_TRY(aReader->ReadU32())); } - uint32_t lameOrLavcTag; - MOZ_TRY_VAR(lameOrLavcTag, aReader->ReadU32()); + uint32_t lameOrLavcTag = MOZ_TRY(aReader->ReadU32()); if (lameOrLavcTag == LAME_TAG || lameOrLavcTag == LAVC_TAG) { // Skip 17 bytes after the LAME tag: @@ -504,22 +497,21 @@ Result<bool, nsresult> FrameParser::VBRHeader::ParseVBRI( // VBRI have a fixed relative position, so let's check for it there. if (aReader->Remaining() > MIN_FRAME_SIZE) { aReader->Seek(prevReaderOffset + OFFSET); - uint32_t tag; - MOZ_TRY_VAR(tag, aReader->ReadU32()); + uint32_t tag = MOZ_TRY(aReader->ReadU32()); if (tag == TAG) { uint16_t vbriEncoderVersion, vbriEncoderDelay, vbriQuality; uint32_t vbriBytes, vbriFrames; uint16_t vbriSeekOffsetsTableSize, vbriSeekOffsetsScaleFactor, vbriSeekOffsetsBytesPerEntry, vbriSeekOffsetsFramesPerEntry; - MOZ_TRY_VAR(vbriEncoderVersion, aReader->ReadU16()); - MOZ_TRY_VAR(vbriEncoderDelay, aReader->ReadU16()); - MOZ_TRY_VAR(vbriQuality, aReader->ReadU16()); - MOZ_TRY_VAR(vbriBytes, aReader->ReadU32()); - MOZ_TRY_VAR(vbriFrames, aReader->ReadU32()); - MOZ_TRY_VAR(vbriSeekOffsetsTableSize, aReader->ReadU16()); - MOZ_TRY_VAR(vbriSeekOffsetsScaleFactor, aReader->ReadU32()); - MOZ_TRY_VAR(vbriSeekOffsetsBytesPerEntry, aReader->ReadU16()); - MOZ_TRY_VAR(vbriSeekOffsetsFramesPerEntry, aReader->ReadU16()); + vbriEncoderVersion = MOZ_TRY(aReader->ReadU16()); + vbriEncoderDelay = MOZ_TRY(aReader->ReadU16()); + vbriQuality = MOZ_TRY(aReader->ReadU16()); + vbriBytes = MOZ_TRY(aReader->ReadU32()); + vbriFrames = MOZ_TRY(aReader->ReadU32()); + vbriSeekOffsetsTableSize = MOZ_TRY(aReader->ReadU16()); + vbriSeekOffsetsScaleFactor = MOZ_TRY(aReader->ReadU32()); + vbriSeekOffsetsBytesPerEntry = MOZ_TRY(aReader->ReadU16()); + vbriSeekOffsetsFramesPerEntry = MOZ_TRY(aReader->ReadU16()); mTOC.reserve(vbriSeekOffsetsTableSize + 1); diff --git a/dom/media/mp4/MoofParser.cpp b/dom/media/mp4/MoofParser.cpp @@ -754,15 +754,13 @@ Result<Ok, nsresult> Moof::ParseTrun(Box& aBox, Mvhd& aMvhd, Mdhd& aMdhd, LOG_WARN(Moof, "Incomplete Box (missing flags)"); return Err(NS_ERROR_FAILURE); } - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); if (!reader->CanReadType<uint32_t>()) { LOG_WARN(Moof, "Incomplete Box (missing sampleCount)"); return Err(NS_ERROR_FAILURE); } - uint32_t sampleCount; - MOZ_TRY_VAR(sampleCount, reader->ReadU32()); + uint32_t sampleCount = MOZ_TRY(reader->ReadU32()); if (sampleCount == 0) { LOG_DEBUG(Trun, "Trun with no samples, returning."); return Ok(); @@ -770,13 +768,11 @@ Result<Ok, nsresult> Moof::ParseTrun(Box& aBox, Mvhd& aMvhd, Mdhd& aMdhd, uint64_t offset = mTfhd.mBaseDataOffset; if (flags & 0x01) { - uint32_t tmp; - MOZ_TRY_VAR(tmp, reader->ReadU32()); - offset += tmp; + offset += MOZ_TRY(reader->ReadU32()); } uint32_t firstSampleFlags = mTfhd.mDefaultSampleFlags; if (flags & 0x04) { - MOZ_TRY_VAR(firstSampleFlags, reader->ReadU32()); + firstSampleFlags = MOZ_TRY(reader->ReadU32()); } nsTArray<MP4Interval<TimeUnit>> timeRanges; uint64_t decodeTime = *aDecodeTime; @@ -789,19 +785,19 @@ Result<Ok, nsresult> Moof::ParseTrun(Box& aBox, Mvhd& aMvhd, Mdhd& aMdhd, for (size_t i = 0; i < sampleCount; i++) { uint32_t sampleDuration = mTfhd.mDefaultSampleDuration; if (flags & 0x100) { - MOZ_TRY_VAR(sampleDuration, reader->ReadU32()); + sampleDuration = MOZ_TRY(reader->ReadU32()); } uint32_t sampleSize = mTfhd.mDefaultSampleSize; if (flags & 0x200) { - MOZ_TRY_VAR(sampleSize, reader->ReadU32()); + sampleSize = MOZ_TRY(reader->ReadU32()); } uint32_t sampleFlags = i ? mTfhd.mDefaultSampleFlags : firstSampleFlags; if (flags & 0x400) { - MOZ_TRY_VAR(sampleFlags, reader->ReadU32()); + sampleFlags = MOZ_TRY(reader->ReadU32()); } int32_t ctsOffset = 0; if (flags & 0x800) { - MOZ_TRY_VAR(ctsOffset, reader->Read32()); + ctsOffset = MOZ_TRY(reader->Read32()); } if (sampleSize) { @@ -809,15 +805,15 @@ Result<Ok, nsresult> Moof::ParseTrun(Box& aBox, Mvhd& aMvhd, Mdhd& aMdhd, sample.mByteRange = MediaByteRange(offset, offset + sampleSize); offset += sampleSize; - TimeUnit decodeOffset, emptyOffset, startCts, endCts; - MOZ_TRY_VAR(decodeOffset, - aMdhd.ToTimeUnit((int64_t)decodeTime - aEdts.mMediaStart)); - MOZ_TRY_VAR(emptyOffset, aMvhd.ToTimeUnit(aEdts.mEmptyOffset)); + TimeUnit decodeOffset = + MOZ_TRY(aMdhd.ToTimeUnit((int64_t)decodeTime - aEdts.mMediaStart)); + TimeUnit emptyOffset = MOZ_TRY(aMvhd.ToTimeUnit(aEdts.mEmptyOffset)); sample.mDecodeTime = decodeOffset + emptyOffset; - MOZ_TRY_VAR(startCts, aMdhd.ToTimeUnit((int64_t)decodeTime + ctsOffset - - aEdts.mMediaStart)); - MOZ_TRY_VAR(endCts, aMdhd.ToTimeUnit((int64_t)decodeTime + ctsOffset + - sampleDuration - aEdts.mMediaStart)); + TimeUnit startCts = MOZ_TRY(aMdhd.ToTimeUnit( + (int64_t)decodeTime + ctsOffset - aEdts.mMediaStart)); + TimeUnit endCts = + MOZ_TRY(aMdhd.ToTimeUnit((int64_t)decodeTime + ctsOffset + + sampleDuration - aEdts.mMediaStart)); sample.mCompositionRange = MP4Interval<TimeUnit>(startCts + emptyOffset, endCts + emptyOffset); // Sometimes audio streams don't properly mark their samples as keyframes, @@ -830,8 +826,7 @@ Result<Ok, nsresult> Moof::ParseTrun(Box& aBox, Mvhd& aMvhd, Mdhd& aMdhd, } decodeTime += sampleDuration; } - TimeUnit roundTime; - MOZ_TRY_VAR(roundTime, aMdhd.ToTimeUnit(sampleCount)); + TimeUnit roundTime = MOZ_TRY(aMdhd.ToTimeUnit(sampleCount)); mMaxRoundingError = roundTime + mMaxRoundingError; *aDecodeTime = decodeTime; @@ -849,32 +844,26 @@ Tkhd::Tkhd(Box& aBox) : mTrackId(0) { Result<Ok, nsresult> Tkhd::Parse(Box& aBox) { BoxReader reader(aBox); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); uint8_t version = flags >> 24; if (version == 0) { - uint32_t creationTime, modificationTime, reserved, duration; - MOZ_TRY_VAR(creationTime, reader->ReadU32()); - MOZ_TRY_VAR(modificationTime, reader->ReadU32()); - MOZ_TRY_VAR(mTrackId, reader->ReadU32()); - MOZ_TRY_VAR(reserved, reader->ReadU32()); - MOZ_TRY_VAR(duration, reader->ReadU32()); - - (void)reserved; + uint32_t creationTime = MOZ_TRY(reader->ReadU32()); + uint32_t modificationTime = MOZ_TRY(reader->ReadU32()); + mTrackId = MOZ_TRY(reader->ReadU32()); + [[maybe_unused]] uint32_t reserved = MOZ_TRY(reader->ReadU32()); + uint32_t duration = MOZ_TRY(reader->ReadU32()); NS_ASSERTION(!reserved, "reserved should be 0"); mCreationTime = creationTime; mModificationTime = modificationTime; mDuration = duration; } else if (version == 1) { - uint32_t reserved; - MOZ_TRY_VAR(mCreationTime, reader->ReadU64()); - MOZ_TRY_VAR(mModificationTime, reader->ReadU64()); - MOZ_TRY_VAR(mTrackId, reader->ReadU32()); - MOZ_TRY_VAR(reserved, reader->ReadU32()); - (void)reserved; + mCreationTime = MOZ_TRY(reader->ReadU64()); + mModificationTime = MOZ_TRY(reader->ReadU64()); + mTrackId = MOZ_TRY(reader->ReadU32()); + [[maybe_unused]] uint32_t reserved = MOZ_TRY(reader->ReadU32()); NS_ASSERTION(!reserved, "reserved should be 0"); - MOZ_TRY_VAR(mDuration, reader->ReadU64()); + mDuration = MOZ_TRY(reader->ReadU64()); } return Ok(); } @@ -890,24 +879,22 @@ Mvhd::Mvhd(Box& aBox) Result<Ok, nsresult> Mvhd::Parse(Box& aBox) { BoxReader reader(aBox); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); uint8_t version = flags >> 24; if (version == 0) { - uint32_t creationTime, modificationTime, duration; - MOZ_TRY_VAR(creationTime, reader->ReadU32()); - MOZ_TRY_VAR(modificationTime, reader->ReadU32()); - MOZ_TRY_VAR(mTimescale, reader->ReadU32()); - MOZ_TRY_VAR(duration, reader->ReadU32()); + uint32_t creationTime = MOZ_TRY(reader->ReadU32()); + uint32_t modificationTime = MOZ_TRY(reader->ReadU32()); + mTimescale = MOZ_TRY(reader->ReadU32()); + uint32_t duration = MOZ_TRY(reader->ReadU32()); mCreationTime = creationTime; mModificationTime = modificationTime; mDuration = duration; } else if (version == 1) { - MOZ_TRY_VAR(mCreationTime, reader->ReadU64()); - MOZ_TRY_VAR(mModificationTime, reader->ReadU64()); - MOZ_TRY_VAR(mTimescale, reader->ReadU32()); - MOZ_TRY_VAR(mDuration, reader->ReadU64()); + mCreationTime = MOZ_TRY(reader->ReadU64()); + mModificationTime = MOZ_TRY(reader->ReadU64()); + mTimescale = MOZ_TRY(reader->ReadU32()); + mDuration = MOZ_TRY(reader->ReadU64()); } else { return Err(NS_ERROR_FAILURE); } @@ -932,12 +919,12 @@ Trex::Trex(Box& aBox) Result<Ok, nsresult> Trex::Parse(Box& aBox) { BoxReader reader(aBox); - MOZ_TRY_VAR(mFlags, reader->ReadU32()); - MOZ_TRY_VAR(mTrackId, reader->ReadU32()); - MOZ_TRY_VAR(mDefaultSampleDescriptionIndex, reader->ReadU32()); - MOZ_TRY_VAR(mDefaultSampleDuration, reader->ReadU32()); - MOZ_TRY_VAR(mDefaultSampleSize, reader->ReadU32()); - MOZ_TRY_VAR(mDefaultSampleFlags, reader->ReadU32()); + mFlags = MOZ_TRY(reader->ReadU32()); + mTrackId = MOZ_TRY(reader->ReadU32()); + mDefaultSampleDescriptionIndex = MOZ_TRY(reader->ReadU32()); + mDefaultSampleDuration = MOZ_TRY(reader->ReadU32()); + mDefaultSampleSize = MOZ_TRY(reader->ReadU32()); + mDefaultSampleFlags = MOZ_TRY(reader->ReadU32()); return Ok(); } @@ -956,23 +943,23 @@ Result<Ok, nsresult> Tfhd::Parse(Box& aBox) { BoxReader reader(aBox); - MOZ_TRY_VAR(mFlags, reader->ReadU32()); - MOZ_TRY_VAR(mTrackId, reader->ReadU32()); + mFlags = MOZ_TRY(reader->ReadU32()); + mTrackId = MOZ_TRY(reader->ReadU32()); mBaseDataOffset = aBox.Parent()->Parent()->Offset(); if (mFlags & 0x01) { - MOZ_TRY_VAR(mBaseDataOffset, reader->ReadU64()); + mBaseDataOffset = MOZ_TRY(reader->ReadU64()); } if (mFlags & 0x02) { - MOZ_TRY_VAR(mDefaultSampleDescriptionIndex, reader->ReadU32()); + mDefaultSampleDescriptionIndex = MOZ_TRY(reader->ReadU32()); } if (mFlags & 0x08) { - MOZ_TRY_VAR(mDefaultSampleDuration, reader->ReadU32()); + mDefaultSampleDuration = MOZ_TRY(reader->ReadU32()); } if (mFlags & 0x10) { - MOZ_TRY_VAR(mDefaultSampleSize, reader->ReadU32()); + mDefaultSampleSize = MOZ_TRY(reader->ReadU32()); } if (mFlags & 0x20) { - MOZ_TRY_VAR(mDefaultSampleFlags, reader->ReadU32()); + mDefaultSampleFlags = MOZ_TRY(reader->ReadU32()); } return Ok(); @@ -988,15 +975,12 @@ Tfdt::Tfdt(Box& aBox) : mBaseMediaDecodeTime(0) { Result<Ok, nsresult> Tfdt::Parse(Box& aBox) { BoxReader reader(aBox); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); uint8_t version = flags >> 24; if (version == 0) { - uint32_t tmp; - MOZ_TRY_VAR(tmp, reader->ReadU32()); - mBaseMediaDecodeTime = tmp; + mBaseMediaDecodeTime = MOZ_TRY(reader->ReadU32()); } else if (version == 1) { - MOZ_TRY_VAR(mBaseMediaDecodeTime, reader->ReadU64()); + mBaseMediaDecodeTime = MOZ_TRY(reader->ReadU64()); } return Ok(); } @@ -1015,25 +999,19 @@ Result<Ok, nsresult> Edts::Parse(Box& aBox) { } BoxReader reader(child); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); uint8_t version = flags >> 24; bool emptyEntry = false; - uint32_t entryCount; - MOZ_TRY_VAR(entryCount, reader->ReadU32()); + uint32_t entryCount = MOZ_TRY(reader->ReadU32()); for (uint32_t i = 0; i < entryCount; i++) { uint64_t segment_duration; int64_t media_time; if (version == 1) { - MOZ_TRY_VAR(segment_duration, reader->ReadU64()); - MOZ_TRY_VAR(media_time, reader->Read64()); + segment_duration = MOZ_TRY(reader->ReadU64()); + media_time = MOZ_TRY(reader->Read64()); } else { - uint32_t tmp; - MOZ_TRY_VAR(tmp, reader->ReadU32()); - segment_duration = tmp; - int32_t tmp2; - MOZ_TRY_VAR(tmp2, reader->Read32()); - media_time = tmp2; + segment_duration = MOZ_TRY(reader->ReadU32()); + media_time = MOZ_TRY(reader->Read32()); } if (media_time == -1 && i) { LOG_WARN(Edts, "Multiple empty edit, not handled"); @@ -1069,16 +1047,13 @@ Saiz::Saiz(Box& aBox, AtomType aDefaultType) Result<Ok, nsresult> Saiz::Parse(Box& aBox) { BoxReader reader(aBox); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); if (flags & 1) { - MOZ_TRY_VAR(mAuxInfoType, reader->ReadU32()); - MOZ_TRY_VAR(mAuxInfoTypeParameter, reader->ReadU32()); + mAuxInfoType = MOZ_TRY(reader->ReadU32()); + mAuxInfoTypeParameter = MOZ_TRY(reader->ReadU32()); } - uint8_t defaultSampleInfoSize; - MOZ_TRY_VAR(defaultSampleInfoSize, reader->ReadU8()); - uint32_t count; - MOZ_TRY_VAR(count, reader->ReadU32()); + uint8_t defaultSampleInfoSize = MOZ_TRY(reader->ReadU8()); + uint32_t count = MOZ_TRY(reader->ReadU32()); if (defaultSampleInfoSize) { if (!mSampleInfoSize.SetLength(count, fallible)) { LOG_ERROR(Saiz, "OOM"); @@ -1106,30 +1081,26 @@ Saio::Saio(Box& aBox, AtomType aDefaultType) Result<Ok, nsresult> Saio::Parse(Box& aBox) { BoxReader reader(aBox); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); uint8_t version = flags >> 24; if (flags & 1) { - MOZ_TRY_VAR(mAuxInfoType, reader->ReadU32()); - MOZ_TRY_VAR(mAuxInfoTypeParameter, reader->ReadU32()); + mAuxInfoType = MOZ_TRY(reader->ReadU32()); + mAuxInfoTypeParameter = MOZ_TRY(reader->ReadU32()); } - size_t count; - MOZ_TRY_VAR(count, reader->ReadU32()); + size_t count = MOZ_TRY(reader->ReadU32()); if (!mOffsets.SetCapacity(count, fallible)) { LOG_ERROR(Saiz, "OOM"); return Err(NS_ERROR_FAILURE); } if (version == 0) { - uint32_t offset; for (size_t i = 0; i < count; i++) { - MOZ_TRY_VAR(offset, reader->ReadU32()); + uint32_t offset = MOZ_TRY(reader->ReadU32()); MOZ_ALWAYS_TRUE(mOffsets.AppendElement(offset, fallible)); } } else { - uint64_t offset; for (size_t i = 0; i < count; i++) { - MOZ_TRY_VAR(offset, reader->ReadU64()); + uint64_t offset = MOZ_TRY(reader->ReadU64()); MOZ_ALWAYS_TRUE(mOffsets.AppendElement(offset, fallible)); } } @@ -1146,26 +1117,20 @@ Sbgp::Sbgp(Box& aBox) : mGroupingTypeParam(0) { Result<Ok, nsresult> Sbgp::Parse(Box& aBox) { BoxReader reader(aBox); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); const uint8_t version = flags >> 24; - uint32_t type; - MOZ_TRY_VAR(type, reader->ReadU32()); - mGroupingType = type; + mGroupingType = MOZ_TRY(reader->ReadU32()); if (version == 1) { - MOZ_TRY_VAR(mGroupingTypeParam, reader->ReadU32()); + mGroupingTypeParam = MOZ_TRY(reader->ReadU32()); } - uint32_t count; - MOZ_TRY_VAR(count, reader->ReadU32()); + uint32_t count = MOZ_TRY(reader->ReadU32()); for (uint32_t i = 0; i < count; i++) { - uint32_t sampleCount; - MOZ_TRY_VAR(sampleCount, reader->ReadU32()); - uint32_t groupDescriptionIndex; - MOZ_TRY_VAR(groupDescriptionIndex, reader->ReadU32()); + uint32_t sampleCount = MOZ_TRY(reader->ReadU32()); + uint32_t groupDescriptionIndex = MOZ_TRY(reader->ReadU32()); SampleToGroupEntry entry(sampleCount, groupDescriptionIndex); if (!mEntries.AppendElement(entry, mozilla::fallible)) { @@ -1186,31 +1151,26 @@ Sgpd::Sgpd(Box& aBox) { Result<Ok, nsresult> Sgpd::Parse(Box& aBox) { BoxReader reader(aBox); - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); const uint8_t version = flags >> 24; - uint32_t type; - MOZ_TRY_VAR(type, reader->ReadU32()); - mGroupingType = type; + mGroupingType = MOZ_TRY(reader->ReadU32()); const uint32_t entrySize = sizeof(uint32_t) + kKeyIdSize; uint32_t defaultLength = 0; if (version == 1) { - MOZ_TRY_VAR(defaultLength, reader->ReadU32()); + defaultLength = MOZ_TRY(reader->ReadU32()); if (defaultLength < entrySize && defaultLength != 0) { return Err(NS_ERROR_FAILURE); } } - uint32_t count; - MOZ_TRY_VAR(count, reader->ReadU32()); + uint32_t count = MOZ_TRY(reader->ReadU32()); for (uint32_t i = 0; i < count; ++i) { if (version == 1 && defaultLength == 0) { - uint32_t descriptionLength; - MOZ_TRY_VAR(descriptionLength, reader->ReadU32()); + uint32_t descriptionLength = MOZ_TRY(reader->ReadU32()); if (descriptionLength < entrySize) { return Err(NS_ERROR_FAILURE); } @@ -1233,16 +1193,14 @@ Result<Ok, nsresult> CencSampleEncryptionInfoEntry::Init(BoxReader& aReader) { // Skip a reserved byte. MOZ_TRY(aReader->ReadU8()); - uint8_t pattern; - MOZ_TRY_VAR(pattern, aReader->ReadU8()); + uint8_t pattern = MOZ_TRY(aReader->ReadU8()); mCryptByteBlock = pattern >> 4; mSkipByteBlock = pattern & 0x0f; - uint8_t isEncrypted; - MOZ_TRY_VAR(isEncrypted, aReader->ReadU8()); + uint8_t isEncrypted = MOZ_TRY(aReader->ReadU8()); mIsEncrypted = isEncrypted != 0; - MOZ_TRY_VAR(mIVSize, aReader->ReadU8()); + mIVSize = MOZ_TRY(aReader->ReadU8()); // Read the key id. if (!mKeyId.SetLength(kKeyIdSize, fallible)) { @@ -1250,7 +1208,7 @@ Result<Ok, nsresult> CencSampleEncryptionInfoEntry::Init(BoxReader& aReader) { return Err(NS_ERROR_FAILURE); } for (uint32_t i = 0; i < kKeyIdSize; ++i) { - MOZ_TRY_VAR(mKeyId.ElementAt(i), aReader->ReadU8()); + mKeyId.ElementAt(i) = MOZ_TRY(aReader->ReadU8()); } if (mIsEncrypted) { @@ -1260,8 +1218,7 @@ Result<Ok, nsresult> CencSampleEncryptionInfoEntry::Init(BoxReader& aReader) { } else if (mIVSize != 0) { // Protected content with 0 sized IV indicates a constant IV is present. // This is used for the cbcs scheme. - uint8_t constantIVSize; - MOZ_TRY_VAR(constantIVSize, aReader->ReadU8()); + uint8_t constantIVSize = MOZ_TRY(aReader->ReadU8()); if (constantIVSize != 8 && constantIVSize != 16) { LOG_WARN(CencSampleEncryptionInfoEntry, "Unexpected constantIVSize: %" PRIu8, constantIVSize); @@ -1272,7 +1229,7 @@ Result<Ok, nsresult> CencSampleEncryptionInfoEntry::Init(BoxReader& aReader) { return Err(NS_ERROR_FAILURE); } for (uint32_t i = 0; i < constantIVSize; ++i) { - MOZ_TRY_VAR(mConsantIV.ElementAt(i), aReader->ReadU8()); + mConsantIV.ElementAt(i) = MOZ_TRY(aReader->ReadU8()); } } diff --git a/dom/media/mp4/SinfParser.cpp b/dom/media/mp4/SinfParser.cpp @@ -37,7 +37,7 @@ Result<Ok, nsresult> SinfParser::ParseSchm(Box& aBox) { } MOZ_TRY(reader->ReadU32()); // flags -- ignore - MOZ_TRY_VAR(mSinf.mDefaultEncryptionType, reader->ReadU32()); + mSinf.mDefaultEncryptionType = MOZ_TRY(reader->ReadU32()); return Ok(); } @@ -57,15 +57,13 @@ Result<Ok, nsresult> SinfParser::ParseTenc(Box& aBox) { return Err(NS_ERROR_FAILURE); } - uint32_t flags; - MOZ_TRY_VAR(flags, reader->ReadU32()); + uint32_t flags = MOZ_TRY(reader->ReadU32()); uint8_t version = flags >> 24; // Skip reserved byte MOZ_TRY(reader->ReadU8()); if (version >= 1) { - uint8_t pattern; - MOZ_TRY_VAR(pattern, reader->ReadU8()); + uint8_t pattern = MOZ_TRY(reader->ReadU8()); mSinf.mDefaultCryptByteBlock = pattern >> 4; mSinf.mDefaultSkipByteBlock = pattern & 0x0f; } else { @@ -75,20 +73,18 @@ Result<Ok, nsresult> SinfParser::ParseTenc(Box& aBox) { mSinf.mDefaultSkipByteBlock = 0; } - uint8_t isEncrypted; - MOZ_TRY_VAR(isEncrypted, reader->ReadU8()); - MOZ_TRY_VAR(mSinf.mDefaultIVSize, reader->ReadU8()); + uint8_t isEncrypted = MOZ_TRY(reader->ReadU8()); + mSinf.mDefaultIVSize = MOZ_TRY(reader->ReadU8()); memcpy(mSinf.mDefaultKeyID, reader->Read(16), 16); if (isEncrypted && mSinf.mDefaultIVSize == 0) { - uint8_t defaultConstantIVSize; - MOZ_TRY_VAR(defaultConstantIVSize, reader->ReadU8()); + uint8_t defaultConstantIVSize = MOZ_TRY(reader->ReadU8()); if (!mSinf.mDefaultConstantIV.SetLength(defaultConstantIVSize, mozilla::fallible)) { return Err(NS_ERROR_FAILURE); } for (uint8_t i = 0; i < defaultConstantIVSize; i++) { - MOZ_TRY_VAR(mSinf.mDefaultConstantIV.ElementAt(i), reader->ReadU8()); + mSinf.mDefaultConstantIV.ElementAt(i) = MOZ_TRY(reader->ReadU8()); } } return Ok(); diff --git a/dom/media/platforms/agnostic/bytestreams/AnnexB.cpp b/dom/media/platforms/agnostic/bytestreams/AnnexB.cpp @@ -47,8 +47,7 @@ Result<Ok, nsresult> AnnexB::ConvertAVCCSampleToAnnexB( ByteWriter<BigEndian> writer(tmp); while (reader.Remaining() >= 4) { - uint32_t nalLen; - MOZ_TRY_VAR(nalLen, reader.ReadU32()); + uint32_t nalLen = MOZ_TRY(reader.ReadU32()); const uint8_t* p = reader.Read(nalLen); if (!writer.Write(kAnnexBDelimiter, std::size(kAnnexBDelimiter))) { @@ -122,8 +121,7 @@ Result<Ok, nsresult> AnnexB::ConvertHVCCSampleToAnnexB( nsTArray<uint8_t> tmp; ByteWriter<BigEndian> writer(tmp); while (reader.Remaining() >= 4) { - uint32_t nalLen; - MOZ_TRY_VAR(nalLen, reader.ReadU32()); + uint32_t nalLen = MOZ_TRY(reader.ReadU32()); const uint8_t* p = reader.Read(nalLen); if (!writer.Write(kAnnexBDelimiter, std::size(kAnnexBDelimiter))) { LOG("Failed to write kAnnexBDelimiter, OOM?"); @@ -234,8 +232,7 @@ already_AddRefed<mozilla::MediaByteBuffer> AnnexB::ConvertHVCCExtraDataToAnnexB( Result<mozilla::Ok, nsresult> AnnexB::ConvertSPSOrPPS( BufferReader& aReader, uint8_t aCount, mozilla::MediaByteBuffer* aAnnexB) { for (int i = 0; i < aCount; i++) { - uint16_t length; - MOZ_TRY_VAR(length, aReader.ReadU16()); + uint16_t length = MOZ_TRY(aReader.ReadU16()); const uint8_t* ptr = aReader.Read(length); if (!ptr) { @@ -259,8 +256,7 @@ static Result<Ok, nsresult> FindStartCodeInternal(BufferReader& aBr) { } while (aBr.Remaining() >= 6) { - uint32_t x32; - MOZ_TRY_VAR(x32, aBr.PeekU32()); + uint32_t x32 = MOZ_TRY(aBr.PeekU32()); if ((x32 - 0x01010101) & (~x32) & 0x80808080) { // Has 0x00 byte(s). if ((x32 >> 8) == 0x000001) { // 0x000001?? return Ok(); @@ -285,8 +281,7 @@ static Result<Ok, nsresult> FindStartCodeInternal(BufferReader& aBr) { } while (aBr.Remaining() >= 3) { - uint32_t data; - MOZ_TRY_VAR(data, aBr.PeekU24()); + uint32_t data = MOZ_TRY(aBr.PeekU24()); if (data == 0x000001) { return Ok(); } @@ -309,8 +304,7 @@ static Result<Ok, nsresult> FindStartCode(BufferReader& aBr, if (aBr.Offset()) { // Check if it's 4-bytes start code aBr.Rewind(1); - uint8_t data; - MOZ_TRY_VAR(data, aBr.ReadU8()); + uint8_t data = MOZ_TRY(aBr.ReadU8()); if (data == 0) { aStartSize = 4; } @@ -526,16 +520,16 @@ AnnexB::ConvertNALUTo4BytesNALU(mozilla::MediaRawData* aSample, uint32_t nalLen; switch (aNALUSize) { case 1: - MOZ_TRY_VAR(nalLen, reader.ReadU8()); + nalLen = MOZ_TRY(reader.ReadU8()); break; case 2: - MOZ_TRY_VAR(nalLen, reader.ReadU16()); + nalLen = MOZ_TRY(reader.ReadU16()); break; case 3: - MOZ_TRY_VAR(nalLen, reader.ReadU24()); + nalLen = MOZ_TRY(reader.ReadU24()); break; case 4: - MOZ_TRY_VAR(nalLen, reader.ReadU32()); + nalLen = MOZ_TRY(reader.ReadU32()); break; default: MOZ_ASSERT_UNREACHABLE("Bytes of the NAL body length must be in [1,4]"); diff --git a/dom/media/platforms/agnostic/bytestreams/H264.cpp b/dom/media/platforms/agnostic/bytestreams/H264.cpp @@ -399,17 +399,16 @@ class SPSNALIterator { } reader.Read(paramSets[i].mOffset); - uint8_t byte; - MOZ_TRY_VAR(byte, reader.ReadU8()); + uint8_t byte = MOZ_TRY(reader.ReadU8()); uint8_t nalUnitType = byte & 0x1f; if (nalUnitType == H264_NAL_PREFIX || nalUnitType == H264_NAL_SLICE_EXT) { bool svcExtensionFlag = false; - MOZ_TRY_VAR(byte, reader.ReadU8()); + byte = MOZ_TRY(reader.ReadU8()); svcExtensionFlag = byte & 0x80; if (svcExtensionFlag) { // Discard the first byte, and find the temporal id in the second byte MOZ_TRY(reader.ReadU8()); - MOZ_TRY_VAR(byte, reader.ReadU8()); + byte = MOZ_TRY(reader.ReadU8()); int temporalId = (byte & 0xE0) >> 5; return temporalId; } @@ -1145,13 +1144,11 @@ bool H264::CompareExtraData(const mozilla::MediaByteBuffer* aExtraData1, static inline Result<Ok, nsresult> ReadSEIInt(BufferReader& aBr, uint32_t& aOutput) { - uint8_t tmpByte; - aOutput = 0; - MOZ_TRY_VAR(tmpByte, aBr.ReadU8()); + uint8_t tmpByte = MOZ_TRY(aBr.ReadU8()); while (tmpByte == 0xFF) { aOutput += 255; - MOZ_TRY_VAR(tmpByte, aBr.ReadU8()); + tmpByte = MOZ_TRY(aBr.ReadU8()); } aOutput += tmpByte; // this is the last byte return Ok(); diff --git a/dom/media/platforms/ffmpeg/FFmpegVideoEncoder.cpp b/dom/media/platforms/ffmpeg/FFmpegVideoEncoder.cpp @@ -753,18 +753,14 @@ FFmpegVideoEncoder<LIBAV_VER>::GetExtraData(AVPacket* aPacket) { BufferReader reader(buf); // The first part is sps. - uint32_t spsSize; - MOZ_TRY_VAR(spsSize, reader.ReadU32()); - Span<const uint8_t> spsData; - MOZ_TRY_VAR(spsData, - reader.ReadSpan<const uint8_t>(static_cast<size_t>(spsSize))); + uint32_t spsSize = MOZ_TRY(reader.ReadU32()); + Span<const uint8_t> spsData = + MOZ_TRY(reader.ReadSpan<const uint8_t>(static_cast<size_t>(spsSize))); // The second part is pps. - uint32_t ppsSize; - MOZ_TRY_VAR(ppsSize, reader.ReadU32()); - Span<const uint8_t> ppsData; - MOZ_TRY_VAR(ppsData, - reader.ReadSpan<const uint8_t>(static_cast<size_t>(ppsSize))); + uint32_t ppsSize = MOZ_TRY(reader.ReadU32()); + Span<const uint8_t> ppsData = + MOZ_TRY(reader.ReadSpan<const uint8_t>(static_cast<size_t>(ppsSize))); // Ensure we have profile, constraints and level needed to create the extra // data. diff --git a/dom/media/webcodecs/VideoFrame.cpp b/dom/media/webcodecs/VideoFrame.cpp @@ -240,8 +240,8 @@ static Result<RefPtr<layers::Image>, MediaResult> CreateImageFromSourceSurface( } // Gecko favors BGRA so we convert surface into BGRA format first. - RefPtr<gfx::DataSourceSurface> bgraSurface; - MOZ_TRY_VAR(bgraSurface, AllocateBGRASurface(surface)); + RefPtr<gfx::DataSourceSurface> bgraSurface = + MOZ_TRY(AllocateBGRASurface(surface)); return RefPtr<layers::Image>( new layers::SourceSurfaceImage(bgraSurface.get())); @@ -262,8 +262,8 @@ static Result<RefPtr<layers::Image>, MediaResult> CreateImageFromRawData( } // Gecko favors BGRA so we convert surface into BGRA format first. - RefPtr<gfx::DataSourceSurface> bgraSurface; - MOZ_TRY_VAR(bgraSurface, AllocateBGRASurface(surface)); + RefPtr<gfx::DataSourceSurface> bgraSurface = + MOZ_TRY(AllocateBGRASurface(surface)); MOZ_ASSERT(bgraSurface); return RefPtr<layers::Image>( @@ -603,13 +603,12 @@ static Result<Maybe<gfx::IntSize>, nsCString> MaybeGetDisplaySize( Maybe<gfx::IntSize> displaySize; if (aInit.mDisplayWidth.WasPassed() && aInit.mDisplayHeight.WasPassed()) { - displaySize.emplace(); - MOZ_TRY_VAR(displaySize.ref(), ToIntSize(aInit.mDisplayWidth.Value(), - aInit.mDisplayHeight.Value()) - .mapErr([](nsCString error) { - error.Insert("display", 0); - return error; - })); + displaySize.emplace(MOZ_TRY( + ToIntSize(aInit.mDisplayWidth.Value(), aInit.mDisplayHeight.Value()) + .mapErr([](nsCString error) { + error.Insert("display", 0); + return error; + }))); } return displaySize; } @@ -619,27 +618,24 @@ static Result< std::tuple<gfx::IntSize, Maybe<gfx::IntRect>, Maybe<gfx::IntSize>>, nsCString> ValidateVideoFrameBufferInit(const VideoFrameBufferInit& aInit) { - gfx::IntSize codedSize; - MOZ_TRY_VAR(codedSize, ToIntSize(aInit.mCodedWidth, aInit.mCodedHeight) - .mapErr([](nsCString error) { - error.Insert("coded", 0); - return error; - })); + gfx::IntSize codedSize = + MOZ_TRY(ToIntSize(aInit.mCodedWidth, aInit.mCodedHeight) + .mapErr([](nsCString error) { + error.Insert("coded", 0); + return error; + })); Maybe<gfx::IntRect> visibleRect; if (aInit.mVisibleRect.WasPassed()) { - visibleRect.emplace(); - MOZ_TRY_VAR( - visibleRect.ref(), + visibleRect.emplace(MOZ_TRY( ToIntRect(aInit.mVisibleRect.Value()).mapErr([](nsCString error) { error.Insert("visibleRect's ", 0); return error; - })); + }))); MOZ_TRY(ValidateVisibility(visibleRect.ref(), codedSize)); } - Maybe<gfx::IntSize> displaySize; - MOZ_TRY_VAR(displaySize, MaybeGetDisplaySize(aInit)); + Maybe<gfx::IntSize> displaySize = MOZ_TRY(MaybeGetDisplaySize(aInit)); return std::make_tuple(codedSize, visibleRect, displaySize); } @@ -851,12 +847,11 @@ static Result<CombinedBufferLayout, MediaResult> ParseVideoFrameCopyToOptions( // TODO: We handle some edge cases that spec misses: // https://github.com/w3c/webcodecs/issues/513 // This comment should be removed once the issue is resolved. - overrideRect.emplace(); - MOZ_TRY_VAR(overrideRect.ref(), - ToIntRect(aOptions.mRect.Value()).mapErr([](nsCString error) { - error.Insert("rect's ", 0); - return MediaResult(NS_ERROR_INVALID_ARG, error); - })); + overrideRect.emplace( + MOZ_TRY(ToIntRect(aOptions.mRect.Value()).mapErr([](nsCString error) { + error.Insert("rect's ", 0); + return MediaResult(NS_ERROR_INVALID_ARG, error); + }))); MediaResult r = VerifyRectSizeAlignment(aFormat, overrideRect.ref()); if (NS_FAILED(r.Code())) { @@ -864,9 +859,8 @@ static Result<CombinedBufferLayout, MediaResult> ParseVideoFrameCopyToOptions( } } - gfx::IntRect parsedRect; - MOZ_TRY_VAR(parsedRect, ParseVisibleRect(aVisibleRect, overrideRect, - aCodedSize, aFormat)); + gfx::IntRect parsedRect = MOZ_TRY( + ParseVisibleRect(aVisibleRect, overrideRect, aCodedSize, aFormat)); const Sequence<PlaneLayout>* optLayout = OptionalToPointer(aOptions.mLayout); @@ -984,20 +978,17 @@ ValidateVideoFrameInit(const VideoFrameInit& aInit, Maybe<gfx::IntRect> visibleRect; if (aInit.mVisibleRect.WasPassed()) { - visibleRect.emplace(); - MOZ_TRY_VAR( - visibleRect.ref(), + visibleRect.emplace(MOZ_TRY( ToIntRect(aInit.mVisibleRect.Value()).mapErr([](nsCString error) { error.Insert("visibleRect's ", 0); return error; - })); + }))); MOZ_TRY(ValidateVisibility(visibleRect.ref(), aCodedSize)); MOZ_TRY(VerifyRectOffsetAlignment(aFormat, visibleRect.ref())); } - Maybe<gfx::IntSize> displaySize; - MOZ_TRY_VAR(displaySize, MaybeGetDisplaySize(aInit)); + Maybe<gfx::IntSize> displaySize = MOZ_TRY(MaybeGetDisplaySize(aInit)); return std::make_pair(visibleRect, displaySize); } @@ -1015,11 +1006,10 @@ static Result<RefPtr<VideoFrame>, MediaResult> CreateVideoFrameFromBuffer( "linear RGB is not supported"_ns)); } - std::tuple<gfx::IntSize, Maybe<gfx::IntRect>, Maybe<gfx::IntSize>> init; - MOZ_TRY_VAR(init, - ValidateVideoFrameBufferInit(aInit).mapErr([](nsCString error) { - return MediaResult(NS_ERROR_INVALID_ARG, error); - })); + std::tuple<gfx::IntSize, Maybe<gfx::IntRect>, Maybe<gfx::IntSize>> init = + MOZ_TRY(ValidateVideoFrameBufferInit(aInit).mapErr([](nsCString error) { + return MediaResult(NS_ERROR_INVALID_ARG, error); + })); gfx::IntSize codedSize = std::get<0>(init); Maybe<gfx::IntRect> visibleRect = std::get<1>(init); Maybe<gfx::IntSize> displaySize = std::get<2>(init); @@ -1033,44 +1023,37 @@ static Result<RefPtr<VideoFrame>, MediaResult> CreateVideoFrameFromBuffer( "coded width and/or height is invalid"_ns)); } - gfx::IntRect parsedRect; - MOZ_TRY_VAR(parsedRect, ParseVisibleRect(gfx::IntRect({0, 0}, codedSize), - visibleRect, codedSize, format)); + gfx::IntRect parsedRect = MOZ_TRY(ParseVisibleRect( + gfx::IntRect({0, 0}, codedSize), visibleRect, codedSize, format)); const Sequence<PlaneLayout>* optLayout = OptionalToPointer(aInit.mLayout); - CombinedBufferLayout combinedLayout; - MOZ_TRY_VAR(combinedLayout, - ComputeLayoutAndAllocationSize(parsedRect, format, optLayout)); + CombinedBufferLayout combinedLayout = + MOZ_TRY(ComputeLayoutAndAllocationSize(parsedRect, format, optLayout)); Maybe<uint64_t> duration = OptionalToMaybe(aInit.mDuration); VideoColorSpaceInternal colorSpace = PickColorSpace(OptionalToPointer(aInit.mColorSpace), aInit.mFormat); - RefPtr<layers::Image> data; - MOZ_TRY_VAR( - data, - aBuffer.ProcessFixedData( - [&](const Span<uint8_t>& aData) - -> Result<RefPtr<layers::Image>, MediaResult> { - if (aData.Length() < - static_cast<size_t>(combinedLayout.mAllocationSize)) { - return Err( - MediaResult(NS_ERROR_INVALID_ARG, "data is too small"_ns)); - } - - // TODO: If codedSize is (3, 3) and visibleRect is (0, 0, 1, 1) but - // the data is 2 x 2 RGBA buffer (2 x 2 x 4 bytes), it pass the - // above check. In this case, we can crop it to a 1 x 1-codedSize - // image (Bug 1782128). - if (aData.Length() < format.ByteCount(codedSize)) { - return Err( - MediaResult(NS_ERROR_INVALID_ARG, "data is too small"_ns)); - } - - return CreateImageFromBuffer(format, colorSpace, codedSize, aData); - })); + RefPtr<layers::Image> data = MOZ_TRY(aBuffer.ProcessFixedData( + [&](const Span<uint8_t>& aData) + -> Result<RefPtr<layers::Image>, MediaResult> { + if (aData.Length() < + static_cast<size_t>(combinedLayout.mAllocationSize)) { + return Err(MediaResult(NS_ERROR_INVALID_ARG, "data is too small"_ns)); + } + + // TODO: If codedSize is (3, 3) and visibleRect is (0, 0, 1, 1) but + // the data is 2 x 2 RGBA buffer (2 x 2 x 4 bytes), it pass the + // above check. In this case, we can crop it to a 1 x 1-codedSize + // image (Bug 1782128). + if (aData.Length() < format.ByteCount(codedSize)) { + return Err(MediaResult(NS_ERROR_INVALID_ARG, "data is too small"_ns)); + } + + return CreateImageFromBuffer(format, colorSpace, codedSize, aData); + })); MOZ_ASSERT(data); MOZ_ASSERT(data->GetSize() == codedSize); @@ -1144,8 +1127,8 @@ InitializeFrameWithResourceAndSize(nsIGlobalObject* aGlobal, return VideoFrame::Format(aFormat); }); - std::pair<Maybe<gfx::IntRect>, Maybe<gfx::IntSize>> init; - MOZ_TRY_VAR(init, ValidateVideoFrameInit(aInit, format, image->GetSize())); + std::pair<Maybe<gfx::IntRect>, Maybe<gfx::IntSize>> init = + MOZ_TRY(ValidateVideoFrameInit(aInit, format, image->GetSize())); Maybe<gfx::IntRect> visibleRect = init.first; Maybe<gfx::IntSize> displaySize = init.second; @@ -1193,9 +1176,8 @@ InitializeFrameFromOtherFrame(nsIGlobalObject* aGlobal, VideoFrameData&& aData, // to do in this case? } - std::pair<Maybe<gfx::IntRect>, Maybe<gfx::IntSize>> init; - MOZ_TRY_VAR(init, - ValidateVideoFrameInit(aInit, format, aData.mImage->GetSize())); + std::pair<Maybe<gfx::IntRect>, Maybe<gfx::IntSize>> init = + MOZ_TRY(ValidateVideoFrameInit(aInit, format, aData.mImage->GetSize())); Maybe<gfx::IntRect> visibleRect = init.first; Maybe<gfx::IntSize> displaySize = init.second; diff --git a/dom/notification/NotificationUtils.cpp b/dom/notification/NotificationUtils.cpp @@ -478,8 +478,8 @@ Result<IPCNotification, nsresult> NotificationStorageEntry::ToIPC( MOZ_TRY(aEntry.GetActions(actionEntries)); nsTArray<IPCNotificationAction> actions(actionEntries.Length()); for (const auto& actionEntry : actionEntries) { - IPCNotificationAction action; - MOZ_TRY_VAR(action, NotificationActionStorageEntry::ToIPC(*actionEntry)); + IPCNotificationAction action = + MOZ_TRY(NotificationActionStorageEntry::ToIPC(*actionEntry)); actions.AppendElement(std::move(action)); } options.actions() = std::move(actions); diff --git a/dom/quota/QuotaCommon.h b/dom/quota/QuotaCommon.h @@ -181,7 +181,7 @@ class NotNull; * return NS_OK; * } * - * 2. Using MOZ_TRY/MOZ_TRY_VAR macros + * 2. Using MOZ_TRY macro * * Typical use cases: * @@ -383,7 +383,7 @@ class NotNull; * return NS_OK; * } * - * QM_TRY/QM_TRY_UNWRAP/QM_TRY_INSPECT is like MOZ_TRY/MOZ_TRY_VAR but if an + * QM_TRY/QM_TRY_UNWRAP/QM_TRY_INSPECT is like MOZ_TRY but if an * error occurs it additionally calls a generic function HandleError to handle * the error and it can be used to return custom return values as well and even * call an additional cleanup function. @@ -1182,8 +1182,7 @@ auto CollectEach(Step aStep, const Body& aBody) typename std::invoke_result_t<Body, StepResultType&&>::ok_type>); while (true) { - StepResultType element; - MOZ_TRY_VAR(element, aStep()); + StepResultType element = MOZ_TRY(aStep()); if (!static_cast<bool>(element)) { break; @@ -1211,7 +1210,7 @@ auto ReduceEach(InputGenerator aInputGenerator, T aInit, [&res, &aBinaryOp](const auto& element) -> Result<Ok, typename std::invoke_result_t<InputGenerator>::err_type> { - MOZ_TRY_VAR(res, aBinaryOp(std::move(res), element)); + res = MOZ_TRY(aBinaryOp(std::move(res), element)); return Ok{}; })); diff --git a/dom/serviceworkers/ServiceWorkerManager.cpp b/dom/serviceworkers/ServiceWorkerManager.cpp @@ -1101,8 +1101,8 @@ ServiceWorkerManager::SendPushEvent(const nsACString& aOriginAttributes, nsresult ServiceWorkerManager::SendCookieChangeEvent( const OriginAttributes& aOriginAttributes, const nsACString& aScope, const net::CookieStruct& aCookie, bool aCookieDeleted) { - nsCOMPtr<nsIPrincipal> principal; - MOZ_TRY_VAR(principal, ScopeToPrincipal(aScope, aOriginAttributes)); + nsCOMPtr<nsIPrincipal> principal = + MOZ_TRY(ScopeToPrincipal(aScope, aOriginAttributes)); RefPtr<ServiceWorkerRegistrationInfo> registration = GetRegistration(principal, aScope); @@ -1129,8 +1129,7 @@ nsresult ServiceWorkerManager::SendPushEvent( return NS_ERROR_INVALID_ARG; } - nsCOMPtr<nsIPrincipal> principal; - MOZ_TRY_VAR(principal, ScopeToPrincipal(aScope, attrs)); + nsCOMPtr<nsIPrincipal> principal = MOZ_TRY(ScopeToPrincipal(aScope, attrs)); // The registration handling a push notification must have an exact scope // match. This will try to find an exact match, unlike how fetch may find the @@ -3033,8 +3032,7 @@ ServiceWorkerManager::WakeForExtensionAPIEvent( return NS_OK; } - nsCOMPtr<nsIPrincipal> principal; - MOZ_TRY_VAR(principal, ScopeToPrincipal(scopeURI, {})); + nsCOMPtr<nsIPrincipal> principal = MOZ_TRY(ScopeToPrincipal(scopeURI, {})); auto* addonPolicy = BasePrincipal::Cast(principal)->AddonPolicy(); if (NS_WARN_IF(!addonPolicy)) { diff --git a/dom/serviceworkers/ServiceWorkerPrivate.cpp b/dom/serviceworkers/ServiceWorkerPrivate.cpp @@ -1144,8 +1144,7 @@ nsresult ServiceWorkerPrivate::SendFetchEvent( Shutdown(); }); - IPCInternalRequest request; - MOZ_TRY_VAR(request, GetIPCInternalRequest(aChannel)); + IPCInternalRequest request = MOZ_TRY(GetIPCInternalRequest(aChannel)); scopeExit.release(); diff --git a/extensions/pref/autoconfig/src/nsAutoConfig.cpp b/extensions/pref/autoconfig/src/nsAutoConfig.cpp @@ -288,9 +288,8 @@ nsresult nsAutoConfig::downloadAutoConfig() { if (NS_SUCCEEDED(rv) && minutes > 0) { // Create a new timer and pass this nsAutoConfig // object as a timer callback. - MOZ_TRY_VAR(mTimer, - NS_NewTimerWithCallback(this, minutes * 60 * 1000, - nsITimer::TYPE_REPEATING_SLACK)); + mTimer = MOZ_TRY(NS_NewTimerWithCallback(this, minutes * 60 * 1000, + nsITimer::TYPE_REPEATING_SLACK)); } } // first_time diff --git a/gfx/tests/fuzz/TestMoz2D.cpp b/gfx/tests/fuzz/TestMoz2D.cpp @@ -12,43 +12,39 @@ static int testInitMoz2D(int* argc, char*** argv) { return 0; } static int testMoz2DRenderCallback(const uint8_t* buf, size_t size) { FuzzingBufferReader fuzzBuf(buf, size); - uint8_t imageFormat; - MOZ_TRY_VAR(imageFormat, fuzzBuf.Read<uint8_t>()); + uint8_t imageFormat = MOZ_TRY(fuzzBuf.Read<uint8_t>()); mozilla::wr::LayoutIntRect renderRect; - MOZ_TRY_VAR(renderRect.min.x, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(renderRect.min.y, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(renderRect.max.x, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(renderRect.max.y, fuzzBuf.Read<int32_t>()); + renderRect.min.x = MOZ_TRY(fuzzBuf.Read<int32_t>()); + renderRect.min.y = MOZ_TRY(fuzzBuf.Read<int32_t>()); + renderRect.max.x = MOZ_TRY(fuzzBuf.Read<int32_t>()); + renderRect.max.y = MOZ_TRY(fuzzBuf.Read<int32_t>()); mozilla::wr::DeviceIntRect visibleRect; - MOZ_TRY_VAR(visibleRect.min.x, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(visibleRect.min.y, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(visibleRect.max.x, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(visibleRect.max.y, fuzzBuf.Read<int32_t>()); + visibleRect.min.x = MOZ_TRY(fuzzBuf.Read<int32_t>()); + visibleRect.min.y = MOZ_TRY(fuzzBuf.Read<int32_t>()); + visibleRect.max.x = MOZ_TRY(fuzzBuf.Read<int32_t>()); + visibleRect.max.y = MOZ_TRY(fuzzBuf.Read<int32_t>()); - uint16_t tileSize; - MOZ_TRY_VAR(tileSize, fuzzBuf.Read<uint16_t>()); + uint16_t tileSize = MOZ_TRY(fuzzBuf.Read<uint16_t>()); mozilla::wr::TileOffset tileOffset; if (tileSize) { - MOZ_TRY_VAR(tileOffset.x, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(tileOffset.y, fuzzBuf.Read<int32_t>()); + tileOffset.x = MOZ_TRY(fuzzBuf.Read<int32_t>()); + tileOffset.y = MOZ_TRY(fuzzBuf.Read<int32_t>()); } - uint8_t haveDirtyRect; - MOZ_TRY_VAR(haveDirtyRect, fuzzBuf.Read<uint8_t>()); + uint8_t haveDirtyRect = MOZ_TRY(fuzzBuf.Read<uint8_t>()); mozilla::wr::LayoutIntRect dirtyRect; if (!!haveDirtyRect) { - MOZ_TRY_VAR(dirtyRect.min.x, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(dirtyRect.min.y, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(dirtyRect.max.x, fuzzBuf.Read<int32_t>()); - MOZ_TRY_VAR(dirtyRect.max.y, fuzzBuf.Read<int32_t>()); + dirtyRect.min.x = MOZ_TRY(fuzzBuf.Read<int32_t>()); + dirtyRect.min.y = MOZ_TRY(fuzzBuf.Read<int32_t>()); + dirtyRect.max.x = MOZ_TRY(fuzzBuf.Read<int32_t>()); + dirtyRect.max.y = MOZ_TRY(fuzzBuf.Read<int32_t>()); } - uint32_t outLength; - MOZ_TRY_VAR(outLength, fuzzBuf.Read<uint32_t>()); + uint32_t outLength = MOZ_TRY(fuzzBuf.Read<uint32_t>()); if (outLength >= 10 * 1024 * 1024) { return 0; } diff --git a/js/public/Result.h b/js/public/Result.h @@ -50,10 +50,10 @@ * * Indicate success with `return Ok();`. * - * If the function returns a value on success, use `MOZ_TRY_VAR` to get it: + * If the function returns a value on success, use `MOZ_TRY` to get it: * * RootedValue thrug(cx); - * MOZ_TRY_VAR(thrug, GetObjectThrug(cx, obj)); + * thrug = MOZ_TRY(GetObjectThrug(cx, obj)); * * This behaves the same as `MOZ_TRY` on error. On success, the success * value of `GetObjectThrug(cx, obj)` is assigned to the variable `thrug`. @@ -65,7 +65,7 @@ * responsibility to check for errors and root the object before continuing: * * RootedObject wrapper(cx); - * MOZ_TRY_VAR(wrapper, Enwrapify(cx, thing)); + * wrapper = MOZ_TRY(Enwrapify(cx, thing)); * * This is ideal. On error, there is no object to root; on success, the * assignment to wrapper roots it. GC safety is ensured. diff --git a/js/src/builtin/temporal/TemporalParser.cpp b/js/src/builtin/temporal/TemporalParser.cpp @@ -1174,12 +1174,12 @@ mozilla::Result<ISODate, ParserError> TemporalParser<CharT>::date() { ISODate result{}; - MOZ_TRY_VAR(result.year, dateYear()); + result.year = MOZ_TRY(dateYear()); // Optional |DateSeparator|. bool hasMonthSeparator = dateSeparator(); - MOZ_TRY_VAR(result.month, dateMonth()); + result.month = MOZ_TRY(dateMonth()); // Optional |DateSeparator|. bool hasDaySeparator = dateSeparator(); @@ -1189,7 +1189,7 @@ mozilla::Result<ISODate, ParserError> TemporalParser<CharT>::date() { return mozilla::Err(JSMSG_TEMPORAL_PARSER_INCONSISTENT_DATE_SEPARATOR); } - MOZ_TRY_VAR(result.day, dateDay()); + result.day = MOZ_TRY(dateDay()); return result; } @@ -1211,21 +1211,19 @@ mozilla::Result<Time, ParserError> TemporalParser<CharT>::time() { Time result{}; - MOZ_TRY_VAR(result.hour, hour()); + result.hour = MOZ_TRY(hour()); // Optional |TimeSeparator|. bool hasMinuteSeparator = timeSeparator(); - mozilla::Maybe<int32_t> minutes; - MOZ_TRY_VAR(minutes, minute(hasMinuteSeparator)); + mozilla::Maybe<int32_t> minutes = MOZ_TRY(minute(hasMinuteSeparator)); if (minutes) { result.minute = minutes.value(); // Optional |TimeSeparator|. bool hasSecondSeparator = timeSeparator(); - mozilla::Maybe<int32_t> seconds; - MOZ_TRY_VAR(seconds, timeSecond(hasSecondSeparator)); + mozilla::Maybe<int32_t> seconds = MOZ_TRY(timeSecond(hasSecondSeparator)); if (seconds) { result.second = seconds.value(); @@ -1259,13 +1257,13 @@ TemporalParser<CharT>::dateTime(bool allowZ) { ZonedDateTimeString result{}; - MOZ_TRY_VAR(result.date, date()); + result.date = MOZ_TRY(date()); if (dateTimeSeparator()) { - MOZ_TRY_VAR(result.time, time()); + result.time = MOZ_TRY(time()); if (hasDateTimeUTCOffsetStart()) { - MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(allowZ)); + result.timeZone = MOZ_TRY(dateTimeUTCOffset(allowZ)); } } else { result.startOfDay = true; @@ -1289,8 +1287,7 @@ TemporalParser<CharT>::dateTimeUTCOffset(bool allowZ) { } if (hasSign()) { - DateTimeUTCOffset offset; - MOZ_TRY_VAR(offset, utcOffsetSubMinutePrecision()); + DateTimeUTCOffset offset = MOZ_TRY(utcOffsetSubMinutePrecision()); return TimeZoneString::from(offset); } @@ -1321,13 +1318,12 @@ TemporalParser<CharT>::timeZoneUTCOffsetName() { } result.sign = sign(); - MOZ_TRY_VAR(result.hour, hour()); + result.hour = MOZ_TRY(hour()); // Optional |TimeSeparator|. bool hasMinuteSeparator = timeSeparator(); - mozilla::Maybe<int32_t> minutes; - MOZ_TRY_VAR(minutes, minute(hasMinuteSeparator)); + mozilla::Maybe<int32_t> minutes = MOZ_TRY(minute(hasMinuteSeparator)); if (minutes) { result.minute = minutes.value(); @@ -1362,21 +1358,19 @@ TemporalParser<CharT>::utcOffsetSubMinutePrecision() { } result.sign = sign(); - MOZ_TRY_VAR(result.hour, hour()); + result.hour = MOZ_TRY(hour()); // Optional |TimeSeparator|. bool hasMinuteSeparator = timeSeparator(); - mozilla::Maybe<int32_t> minutes; - MOZ_TRY_VAR(minutes, minute(hasMinuteSeparator)); + mozilla::Maybe<int32_t> minutes = MOZ_TRY(minute(hasMinuteSeparator)); if (minutes) { result.minute = minutes.value(); // Optional |TimeSeparator|. bool hasSecondSeparator = timeSeparator(); - mozilla::Maybe<int32_t> seconds; - MOZ_TRY_VAR(seconds, second(hasSecondSeparator)); + mozilla::Maybe<int32_t> seconds = MOZ_TRY(second(hasSecondSeparator)); if (seconds) { result.second = seconds.value(); @@ -1405,9 +1399,9 @@ TemporalParser<CharT>::timeZoneIdentifier() { TimeZoneAnnotation result{}; if (hasSign()) { - MOZ_TRY_VAR(result.offset, timeZoneUTCOffsetName()); + result.offset = MOZ_TRY(timeZoneUTCOffsetName()); } else { - MOZ_TRY_VAR(result.name, timeZoneIANAName()); + result.name = MOZ_TRY(timeZoneIANAName()); } return result; @@ -1498,18 +1492,18 @@ TemporalParser<CharT>::parseTemporalInstantString() { // // clang-format on - MOZ_TRY_VAR(result.date, date()); + result.date = MOZ_TRY(date()); if (!dateTimeSeparator()) { return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_DATE_TIME_SEPARATOR); } - MOZ_TRY_VAR(result.time, time()); + result.time = MOZ_TRY(time()); - MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(/* allowZ = */ true)); + result.timeZone = MOZ_TRY(dateTimeUTCOffset(/* allowZ = */ true)); if (hasTimeZoneAnnotationStart()) { - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); } if (hasAnnotationStart()) { @@ -1882,8 +1876,7 @@ TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) { break; } - double num; - MOZ_TRY_VAR(num, durationDigits(cx)); + double num = MOZ_TRY(durationDigits(cx)); // DurationYearsPart ::: // DecimalDigits[~Sep] YearsDesignator DurationMonthsPart @@ -1897,7 +1890,7 @@ TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) { if (hasTimeDesignator()) { break; } - MOZ_TRY_VAR(num, durationDigits(cx)); + num = MOZ_TRY(durationDigits(cx)); } // DurationMonthsPart ::: @@ -1911,7 +1904,7 @@ TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) { if (hasTimeDesignator()) { break; } - MOZ_TRY_VAR(num, durationDigits(cx)); + num = MOZ_TRY(durationDigits(cx)); } // DurationWeeksPart ::: @@ -1924,7 +1917,7 @@ TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) { if (hasTimeDesignator()) { break; } - MOZ_TRY_VAR(num, durationDigits(cx)); + num = MOZ_TRY(durationDigits(cx)); } // DurationDaysPart ::: @@ -1950,8 +1943,7 @@ TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) { return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_TIME_DESIGNATOR); } - double num; - MOZ_TRY_VAR(num, durationDigits(cx)); + double num = MOZ_TRY(durationDigits(cx)); auto frac = fraction(); @@ -1968,7 +1960,7 @@ TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) { return result; } - MOZ_TRY_VAR(num, durationDigits(cx)); + num = MOZ_TRY(durationDigits(cx)); frac = fraction(); } @@ -1987,7 +1979,7 @@ TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) { return result; } - MOZ_TRY_VAR(num, durationDigits(cx)); + num = MOZ_TRY(durationDigits(cx)); frac = fraction(); } @@ -2196,13 +2188,13 @@ mozilla::Result<Annotation, ParserError> TemporalParser<CharT>::annotation() { result.critical = annotationCriticalFlag(); - MOZ_TRY_VAR(result.key, annotationKey()); + result.key = MOZ_TRY(annotationKey()); if (!character('=')) { return mozilla::Err(JSMSG_TEMPORAL_PARSER_ASSIGNMENT_IN_ANNOTATION); } - MOZ_TRY_VAR(result.value, annotationValue()); + result.value = MOZ_TRY(annotationValue()); if (!character(']')) { return mozilla::Err(JSMSG_TEMPORAL_PARSER_BRACKET_AFTER_ANNOTATION); @@ -2222,8 +2214,7 @@ TemporalParser<CharT>::annotations() { CalendarName calendar; bool calendarWasCritical = false; while (hasAnnotationStart()) { - Annotation anno; - MOZ_TRY_VAR(anno, annotation()); + Annotation anno = MOZ_TRY(annotation()); auto [key, value, critical] = anno; @@ -2261,10 +2252,10 @@ TemporalParser<CharT>::annotatedTime() { size_t start = reader_.index(); bool hasTimeDesignator = timeDesignator(); - MOZ_TRY_VAR(result.time, time()); + result.time = MOZ_TRY(time()); if (hasDateTimeUTCOffsetStart()) { - MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(/* allowZ = */ false)); + result.timeZone = MOZ_TRY(dateTimeUTCOffset(/* allowZ = */ false)); } // Early error if `Time DateTimeUTCOffset[~Z]` can be parsed as either @@ -2304,11 +2295,11 @@ TemporalParser<CharT>::annotatedTime() { } if (hasTimeZoneAnnotationStart()) { - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); } if (hasAnnotationStart()) { - MOZ_TRY_VAR(result.calendar, annotations()); + result.calendar = MOZ_TRY(annotations()); } return result; @@ -2323,15 +2314,14 @@ TemporalParser<CharT>::annotatedDateTime() { // // When called as `AnnotatedDateTime[~Zoned, ~TimeRequired]`. - ZonedDateTimeString result; - MOZ_TRY_VAR(result, dateTime(/* allowZ = */ false)); + ZonedDateTimeString result = MOZ_TRY(dateTime(/* allowZ = */ false)); if (hasTimeZoneAnnotationStart()) { - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); } if (hasAnnotationStart()) { - MOZ_TRY_VAR(result.calendar, annotations()); + result.calendar = MOZ_TRY(annotations()); } return result; @@ -2352,24 +2342,24 @@ TemporalParser<CharT>::annotatedDateTimeTimeRequired() { ZonedDateTimeString result{}; - MOZ_TRY_VAR(result.date, date()); + result.date = MOZ_TRY(date()); if (!dateTimeSeparator()) { return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_DATE_TIME_SEPARATOR); } - MOZ_TRY_VAR(result.time, time()); + result.time = MOZ_TRY(time()); if (hasDateTimeUTCOffsetStart()) { - MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(/* allowZ = */ false)); + result.timeZone = MOZ_TRY(dateTimeUTCOffset(/* allowZ = */ false)); } if (hasTimeZoneAnnotationStart()) { - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); } if (hasAnnotationStart()) { - MOZ_TRY_VAR(result.calendar, annotations()); + result.calendar = MOZ_TRY(annotations()); } return result; @@ -2383,14 +2373,14 @@ TemporalParser<CharT>::annotatedYearMonth() { ZonedDateTimeString result{}; - MOZ_TRY_VAR(result.date, dateSpecYearMonth()); + result.date = MOZ_TRY(dateSpecYearMonth()); if (hasTimeZoneAnnotationStart()) { - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); } if (hasAnnotationStart()) { - MOZ_TRY_VAR(result.calendar, annotations()); + result.calendar = MOZ_TRY(annotations()); } return result; @@ -2404,14 +2394,14 @@ TemporalParser<CharT>::annotatedMonthDay() { ZonedDateTimeString result{}; - MOZ_TRY_VAR(result.date, dateSpecMonthDay()); + result.date = MOZ_TRY(dateSpecMonthDay()); if (hasTimeZoneAnnotationStart()) { - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); } if (hasAnnotationStart()) { - MOZ_TRY_VAR(result.calendar, annotations()); + result.calendar = MOZ_TRY(annotations()); } return result; @@ -2426,12 +2416,12 @@ TemporalParser<CharT>::dateSpecYearMonth() { ISODate result{}; - MOZ_TRY_VAR(result.year, dateYear()); + result.year = MOZ_TRY(dateYear()); // Optional |DateSeparator|. dateSeparator(); - MOZ_TRY_VAR(result.month, dateMonth()); + result.month = MOZ_TRY(dateMonth()); return result; } @@ -2450,12 +2440,12 @@ TemporalParser<CharT>::dateSpecMonthDay() { result.year = AbsentYear; - MOZ_TRY_VAR(result.month, dateMonth()); + result.month = MOZ_TRY(dateMonth()); // Optional |DateSeparator|. dateSeparator(); - MOZ_TRY_VAR(result.day, dateDay()); + result.day = MOZ_TRY(dateDay()); return result; } @@ -2474,7 +2464,7 @@ TemporalParser<CharT>::parseTemporalCalendarString() { if (hasTwoAsciiAlpha()) { ZonedDateTimeString result{}; - MOZ_TRY_VAR(result.calendar, parse(annotationValue())); + result.calendar = MOZ_TRY(parse(annotationValue())); return result; } @@ -2954,12 +2944,12 @@ TemporalParser<CharT>::parseTemporalZonedDateTimeString() { ZonedDateTimeString result{}; - MOZ_TRY_VAR(result, dateTime(/* allowZ = */ true)); + result = MOZ_TRY(dateTime(/* allowZ = */ true)); - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); if (hasAnnotationStart()) { - MOZ_TRY_VAR(result.calendar, annotations()); + result.calendar = MOZ_TRY(annotations()); } return complete(result); @@ -3088,14 +3078,14 @@ TemporalParser<CharT>::parseTemporalRelativeToString() { ZonedDateTimeString result{}; - MOZ_TRY_VAR(result, dateTime(/* allowZ = */ true)); + result = MOZ_TRY(dateTime(/* allowZ = */ true)); if (hasTimeZoneAnnotationStart()) { - MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation()); + result.timeZone.annotation = MOZ_TRY(timeZoneAnnotation()); } if (hasAnnotationStart()) { - MOZ_TRY_VAR(result.calendar, annotations()); + result.calendar = MOZ_TRY(annotations()); } return complete(result); diff --git a/js/src/frontend/FoldConstants.h b/js/src/frontend/FoldConstants.h @@ -29,7 +29,7 @@ class ParserAtomsTable; // the same node (unchanged or modified in place) or a new node. // // Usage: -// MOZ_TRY_VAR(pn, parser->statement()); +// pn = MOZ_TRY(parser->statement()); // if (!FoldConstants(fc, parserAtoms, bigInts, &pn, parser)) { // return errorResult(); // } diff --git a/js/src/frontend/FullParseHandler.h b/js/src/frontend/FullParseHandler.h @@ -163,9 +163,8 @@ class FullParseHandler { UnaryNodeResult newSyntheticComputedName(Node expr, uint32_t begin, uint32_t end) { TokenPos pos(begin, end); - UnaryNode* node; - MOZ_TRY_VAR(node, - newResult<UnaryNode>(ParseNodeKind::ComputedName, pos, expr)); + UnaryNode* node = + MOZ_TRY(newResult<UnaryNode>(ParseNodeKind::ComputedName, pos, expr)); node->setSyntheticComputedName(); return node; } @@ -204,11 +203,9 @@ class FullParseHandler { } CallSiteNodeResult newCallSiteObject(uint32_t begin) { - CallSiteNode* callSiteObj; - MOZ_TRY_VAR(callSiteObj, newResult<CallSiteNode>(begin)); + CallSiteNode* callSiteObj = MOZ_TRY(newResult<CallSiteNode>(begin)); - ListNode* rawNodes; - MOZ_TRY_VAR(rawNodes, newArrayLiteral(callSiteObj->pn_pos.begin)); + ListNode* rawNodes = MOZ_TRY(newArrayLiteral(callSiteObj->pn_pos.begin)); addArrayElement(callSiteObj, rawNodes); @@ -709,9 +706,8 @@ class FullParseHandler { BinaryNodeResult newExportFromDeclaration(uint32_t begin, Node exportSpecSet, Node moduleRequest) { - BinaryNode* decl; - MOZ_TRY_VAR(decl, newResult<BinaryNode>(ParseNodeKind::ExportFromStmt, - exportSpecSet, moduleRequest)); + BinaryNode* decl = MOZ_TRY(newResult<BinaryNode>( + ParseNodeKind::ExportFromStmt, exportSpecSet, moduleRequest)); decl->pn_pos.begin = begin; return decl; } @@ -765,9 +761,8 @@ class FullParseHandler { TernaryNodeResult newIfStatement(uint32_t begin, Node cond, Node thenBranch, Node elseBranch) { - TernaryNode* node; - MOZ_TRY_VAR(node, newResult<TernaryNode>(ParseNodeKind::IfStmt, cond, - thenBranch, elseBranch)); + TernaryNode* node = MOZ_TRY(newResult<TernaryNode>( + ParseNodeKind::IfStmt, cond, thenBranch, elseBranch)); node->pn_pos.begin = begin; return node; } diff --git a/js/src/frontend/ParseNode.cpp b/js/src/frontend/ParseNode.cpp @@ -90,8 +90,7 @@ ParseNodeResult ParseNode::appendOrCreateList(ParseNodeKind kind, } } - ListNode* list; - MOZ_TRY_VAR(list, handler->newResult<ListNode>(kind, left)); + ListNode* list = MOZ_TRY(handler->newResult<ListNode>(kind, left)); list->append(right); return list; diff --git a/js/src/frontend/Parser.cpp b/js/src/frontend/Parser.cpp @@ -392,8 +392,7 @@ GeneralParser<ParseHandler, Unit>::parse() { return errorResult(); } - ListNodeType stmtList; - MOZ_TRY_VAR(stmtList, statementList(YieldIsName)); + ListNodeType stmtList = MOZ_TRY(statementList(YieldIsName)); TokenKind tt; if (!tokenStream.getToken(&tt, TokenStream::SlashIsRegExp)) { @@ -1793,8 +1792,7 @@ Parser<FullParseHandler, Unit>::evalBody(EvalSharedContext* evalsc) { return errorResult(); } - ListNode* list; - MOZ_TRY_VAR(list, statementList(YieldIsName)); + ListNode* list = MOZ_TRY(statementList(YieldIsName)); if (!checkStatementsEOF()) { return errorResult(); @@ -1805,7 +1803,7 @@ Parser<FullParseHandler, Unit>::evalBody(EvalSharedContext* evalsc) { return errorResult(); } - MOZ_TRY_VAR(body, finishLexicalScope(lexicalScope, list)); + body = MOZ_TRY(finishLexicalScope(lexicalScope, list)); } #ifdef DEBUG @@ -1877,8 +1875,7 @@ FullParseHandler::ListNodeResult Parser<FullParseHandler, Unit>::globalBody( return errorResult(); } - ListNode* body; - MOZ_TRY_VAR(body, statementList(YieldIsName)); + ListNode* body = MOZ_TRY(statementList(YieldIsName)); if (!checkStatementsEOF()) { return errorResult(); @@ -1945,13 +1942,11 @@ FullParseHandler::ModuleNodeResult Parser<FullParseHandler, Unit>::moduleBody( return errorResult(); } - ModuleNodeType moduleNode; - MOZ_TRY_VAR(moduleNode, handler_.newModule(pos())); + ModuleNodeType moduleNode = MOZ_TRY(handler_.newModule(pos())); AutoAwaitIsKeyword<FullParseHandler, Unit> awaitIsKeyword( this, AwaitIsModuleKeyword); - ListNode* stmtList; - MOZ_TRY_VAR(stmtList, statementList(YieldIsName)); + ListNode* stmtList = MOZ_TRY(statementList(YieldIsName)); MOZ_ASSERT(stmtList->isKind(ParseNodeKind::StatementList)); moduleNode->setBody(&stmtList->template as<ListNode>()); @@ -2066,8 +2061,7 @@ Parser<SyntaxParseHandler, Unit>::moduleBody(ModuleSharedContext* modulesc) { template <class ParseHandler> typename ParseHandler::NameNodeResult PerHandlerParser<ParseHandler>::newInternalDotName(TaggedParserAtomIndex name) { - NameNodeType nameNode; - MOZ_TRY_VAR(nameNode, newName(name)); + NameNodeType nameNode = MOZ_TRY(newName(name)); if (!noteUsedName(name)) { return errorResult(); } @@ -2367,11 +2361,9 @@ Parser<FullParseHandler, Unit>::standaloneFunction( anyChars.ungetToken(); } - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, pos())); + FunctionNodeType funNode = MOZ_TRY(handler_.newFunction(syntaxKind, pos())); - ParamsBodyNodeType argsbody; - MOZ_TRY_VAR(argsbody, handler_.newParamsBody(pos())); + ParamsBodyNodeType argsbody = MOZ_TRY(handler_.newParamsBody(pos())); funNode->setBody(argsbody); bool isSelfHosting = options().selfHostingMode; @@ -2453,7 +2445,7 @@ GeneralParser<ParseHandler, Unit>::functionBody(InHandling inHandling, Node body; if (type == StatementListBody) { bool inheritedStrict = pc_->sc()->strict(); - MOZ_TRY_VAR(body, statementList(yieldHandling)); + body = MOZ_TRY(statementList(yieldHandling)); // When we transitioned from non-strict to strict mode, we need to // validate that all parameter names are valid strict mode names. @@ -2475,14 +2467,13 @@ GeneralParser<ParseHandler, Unit>::functionBody(InHandling inHandling, // assumed to be statement lists, to prepend initial `yield`. ListNodeType stmtList = null(); if (pc_->isAsync()) { - MOZ_TRY_VAR(stmtList, handler_.newStatementList(pos())); + stmtList = MOZ_TRY(handler_.newStatementList(pos())); } - Node kid; - MOZ_TRY_VAR(kid, - assignExpr(inHandling, yieldHandling, TripledotProhibited)); + Node kid = + MOZ_TRY(assignExpr(inHandling, yieldHandling, TripledotProhibited)); - MOZ_TRY_VAR(body, handler_.newExpressionBody(kid)); + body = MOZ_TRY(handler_.newExpressionBody(kid)); if (pc_->isAsync()) { handler_.addStatementToList(stmtList, body); @@ -2501,8 +2492,7 @@ GeneralParser<ParseHandler, Unit>::functionBody(InHandling inHandling, return errorResult(); } if (pc_->isGenerator()) { - NameNodeType generator; - MOZ_TRY_VAR(generator, newDotGeneratorName()); + NameNodeType generator = MOZ_TRY(newDotGeneratorName()); if (!handler_.prependInitialYield(handler_.asListNode(body), generator)) { return errorResult(); } @@ -3036,12 +3026,10 @@ template <class ParseHandler, typename Unit> typename ParseHandler::ListNodeResult GeneralParser<ParseHandler, Unit>::templateLiteral( YieldHandling yieldHandling) { - NameNodeType literal; - MOZ_TRY_VAR(literal, noSubstitutionUntaggedTemplate()); + NameNodeType literal = MOZ_TRY(noSubstitutionUntaggedTemplate()); - ListNodeType nodeList; - MOZ_TRY_VAR(nodeList, - handler_.newList(ParseNodeKind::TemplateStringListExpr, literal)); + ListNodeType nodeList = + MOZ_TRY(handler_.newList(ParseNodeKind::TemplateStringListExpr, literal)); TokenKind tt; do { @@ -3049,7 +3037,7 @@ GeneralParser<ParseHandler, Unit>::templateLiteral( return errorResult(); } - MOZ_TRY_VAR(literal, noSubstitutionUntaggedTemplate()); + literal = MOZ_TRY(noSubstitutionUntaggedTemplate()); handler_.addList(nodeList, literal); } while (tt == TokenKind::TemplateHead); @@ -3336,9 +3324,8 @@ GeneralParser<ParseHandler, Unit>::innerFunction( } funbox->initWithEnclosingParseContext(outerpc, kind); - FunctionNodeType innerFunc; - MOZ_TRY_VAR(innerFunc, - innerFunctionForFunctionBox(funNode, outerpc, funbox, inHandling, + FunctionNodeType innerFunc = + MOZ_TRY(innerFunctionForFunctionBox(funNode, outerpc, funbox, inHandling, yieldHandling, kind, newDirectives)); // Append possible Annex B function box only upon successfully parsing. @@ -3377,8 +3364,7 @@ Parser<FullParseHandler, Unit>::standaloneLazyFunction( MOZ_ASSERT(checkOptionsCalled_); FunctionSyntaxKind syntaxKind = input.functionSyntaxKind(); - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, pos())); + FunctionNodeType funNode = MOZ_TRY(handler_.newFunction(syntaxKind, pos())); TaggedParserAtomIndex displayAtom = this->getCompilationState().previousParseCache.displayAtom(); @@ -3764,8 +3750,7 @@ GeneralParser<ParseHandler, Unit>::functionStmt(uint32_t toStringStart, } FunctionSyntaxKind syntaxKind = FunctionSyntaxKind::Statement; - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, pos())); + FunctionNodeType funNode = MOZ_TRY(handler_.newFunction(syntaxKind, pos())); // Under sloppy mode, try Annex B.3.3 semantics. If making an additional // 'var' binding of the same name does not throw an early error, do so. @@ -3817,8 +3802,7 @@ GeneralParser<ParseHandler, Unit>::functionExpr(uint32_t toStringStart, } FunctionSyntaxKind syntaxKind = FunctionSyntaxKind::Expression; - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, pos())); + FunctionNodeType funNode = MOZ_TRY(handler_.newFunction(syntaxKind, pos())); if (invoked) { funNode = handler_.setLikelyIIFE(funNode); @@ -4034,8 +4018,7 @@ GeneralParser<ParseHandler, Unit>::statementList(YieldHandling yieldHandling) { return errorResult(); } - ListNodeType stmtList; - MOZ_TRY_VAR(stmtList, handler_.newStatementList(pos())); + ListNodeType stmtList = MOZ_TRY(handler_.newStatementList(pos())); bool canHaveDirectives = pc_->atBodyLevel(); if (canHaveDirectives) { @@ -4115,8 +4098,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::condition( return errorResult(); } - Node pn; - MOZ_TRY_VAR(pn, exprInParens(inHandling, yieldHandling, TripledotProhibited)); + Node pn = + MOZ_TRY(exprInParens(inHandling, yieldHandling, TripledotProhibited)); if (!mustMatchToken(TokenKind::RightParen, JSMSG_PAREN_AFTER_COND)) { return errorResult(); @@ -4288,12 +4271,10 @@ GeneralParser<ParseHandler, Unit>::bindingInitializer( pc_->functionBox()->hasParameterExprs = true; } - Node rhs; - MOZ_TRY_VAR(rhs, assignExpr(InAllowed, yieldHandling, TripledotProhibited)); + Node rhs = MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited)); - BinaryNodeType assign; - MOZ_TRY_VAR(assign, - handler_.newAssignment(ParseNodeKind::AssignExpr, lhs, rhs)); + BinaryNodeType assign = + MOZ_TRY(handler_.newAssignment(ParseNodeKind::AssignExpr, lhs, rhs)); return assign; } @@ -4307,8 +4288,7 @@ GeneralParser<ParseHandler, Unit>::bindingIdentifier( return errorResult(); } - NameNodeType binding; - MOZ_TRY_VAR(binding, newName(name)); + NameNodeType binding = MOZ_TRY(newName(name)); if (!noteDeclaredName(name, kind, pos())) { return errorResult(); } @@ -4348,8 +4328,7 @@ GeneralParser<ParseHandler, Unit>::objectBindingPattern( } uint32_t begin = pos().begin; - ListNodeType literal; - MOZ_TRY_VAR(literal, handler_.newObjectLiteral(begin)); + ListNodeType literal = MOZ_TRY(handler_.newObjectLiteral(begin)); Maybe<DeclarationKind> declKind = Some(kind); TaggedParserAtomIndex propAtom; @@ -4376,8 +4355,7 @@ GeneralParser<ParseHandler, Unit>::objectBindingPattern( return errorResult(); } - NameNodeType inner; - MOZ_TRY_VAR(inner, bindingIdentifier(kind, yieldHandling)); + NameNodeType inner = MOZ_TRY(bindingIdentifier(kind, yieldHandling)); if (!handler_.addSpreadProperty(literal, begin, inner)) { return errorResult(); @@ -4386,10 +4364,9 @@ GeneralParser<ParseHandler, Unit>::objectBindingPattern( TokenPos namePos = anyChars.nextToken().pos; PropertyType propType; - Node propName; - MOZ_TRY_VAR(propName, propertyOrMethodName( - yieldHandling, PropertyNameInPattern, declKind, - literal, &propType, &propAtom)); + Node propName = MOZ_TRY( + propertyOrMethodName(yieldHandling, PropertyNameInPattern, declKind, + literal, &propType, &propAtom)); if (propType == PropertyType::Normal) { // Handle e.g., |var {p: x} = o| and |var {p: x=0} = o|. @@ -4398,9 +4375,8 @@ GeneralParser<ParseHandler, Unit>::objectBindingPattern( return errorResult(); } - Node binding; - MOZ_TRY_VAR(binding, - bindingIdentifierOrPattern(kind, yieldHandling, tt)); + Node binding = + MOZ_TRY(bindingIdentifierOrPattern(kind, yieldHandling, tt)); bool hasInitializer; if (!tokenStream.matchToken(&hasInitializer, TokenKind::Assign, @@ -4410,8 +4386,8 @@ GeneralParser<ParseHandler, Unit>::objectBindingPattern( Node bindingExpr; if (hasInitializer) { - MOZ_TRY_VAR(bindingExpr, - bindingInitializer(binding, kind, yieldHandling)); + bindingExpr = + MOZ_TRY(bindingInitializer(binding, kind, yieldHandling)); } else { bindingExpr = binding; } @@ -4424,8 +4400,7 @@ GeneralParser<ParseHandler, Unit>::objectBindingPattern( // for |var {x: x, y: y} = o|. MOZ_ASSERT(TokenKindIsPossibleIdentifierName(tt)); - NameNodeType binding; - MOZ_TRY_VAR(binding, bindingIdentifier(kind, yieldHandling)); + NameNodeType binding = MOZ_TRY(bindingIdentifier(kind, yieldHandling)); if (!handler_.addShorthand(literal, handler_.asNameNode(propName), binding)) { @@ -4436,14 +4411,12 @@ GeneralParser<ParseHandler, Unit>::objectBindingPattern( // shorthand with default values. MOZ_ASSERT(TokenKindIsPossibleIdentifierName(tt)); - NameNodeType binding; - MOZ_TRY_VAR(binding, bindingIdentifier(kind, yieldHandling)); + NameNodeType binding = MOZ_TRY(bindingIdentifier(kind, yieldHandling)); tokenStream.consumeKnownToken(TokenKind::Assign); - BinaryNodeType bindingExpr; - MOZ_TRY_VAR(bindingExpr, - bindingInitializer(binding, kind, yieldHandling)); + BinaryNodeType bindingExpr = + MOZ_TRY(bindingInitializer(binding, kind, yieldHandling)); if (!handler_.addPropertyDefinition(literal, propName, bindingExpr)) { return errorResult(); @@ -4491,8 +4464,7 @@ GeneralParser<ParseHandler, Unit>::arrayBindingPattern( } uint32_t begin = pos().begin; - ListNodeType literal; - MOZ_TRY_VAR(literal, handler_.newArrayLiteral(begin)); + ListNodeType literal = MOZ_TRY(handler_.newArrayLiteral(begin)); uint32_t index = 0; for (;; index++) { @@ -4523,15 +4495,14 @@ GeneralParser<ParseHandler, Unit>::arrayBindingPattern( return errorResult(); } - Node inner; - MOZ_TRY_VAR(inner, bindingIdentifierOrPattern(kind, yieldHandling, tt)); + Node inner = MOZ_TRY(bindingIdentifierOrPattern(kind, yieldHandling, tt)); if (!handler_.addSpreadElement(literal, begin, inner)) { return errorResult(); } } else { - Node binding; - MOZ_TRY_VAR(binding, bindingIdentifierOrPattern(kind, yieldHandling, tt)); + Node binding = + MOZ_TRY(bindingIdentifierOrPattern(kind, yieldHandling, tt)); bool hasInitializer; if (!tokenStream.matchToken(&hasInitializer, TokenKind::Assign, @@ -4541,7 +4512,7 @@ GeneralParser<ParseHandler, Unit>::arrayBindingPattern( Node element; if (hasInitializer) { - MOZ_TRY_VAR(element, bindingInitializer(binding, kind, yieldHandling)); + element = MOZ_TRY(bindingInitializer(binding, kind, yieldHandling)); } else { element = binding; } @@ -4598,8 +4569,7 @@ GeneralParser<ParseHandler, Unit>::destructuringDeclarationWithoutYieldOrAwait( uint32_t startYieldOffset = pc_->lastYieldOffset; uint32_t startAwaitOffset = pc_->lastAwaitOffset; - Node res; - MOZ_TRY_VAR(res, destructuringDeclaration(kind, yieldHandling, tt)); + Node res = MOZ_TRY(destructuringDeclaration(kind, yieldHandling, tt)); if (pc_->lastYieldOffset != startYieldOffset) { errorAt(pc_->lastYieldOffset, JSMSG_YIELD_IN_PARAMETER); @@ -4625,8 +4595,7 @@ GeneralParser<ParseHandler, Unit>::blockStatement(YieldHandling yieldHandling, return errorResult(); } - ListNodeType list; - MOZ_TRY_VAR(list, statementList(yieldHandling)); + ListNodeType list = MOZ_TRY(statementList(yieldHandling)); if (!mustMatchToken(TokenKind::RightCurly, [this, errorNumber, openedPos](TokenKind actual) { @@ -4660,8 +4629,7 @@ GeneralParser<ParseHandler, Unit>::declarationPattern( MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::LeftBracket) || anyChars.isCurrentTokenType(TokenKind::LeftCurly)); - Node pattern; - MOZ_TRY_VAR(pattern, destructuringDeclaration(declKind, yieldHandling, tt)); + Node pattern = MOZ_TRY(destructuringDeclaration(declKind, yieldHandling, tt)); if (initialDeclaration && forHeadKind) { bool isForIn, isForOf; @@ -4678,8 +4646,8 @@ GeneralParser<ParseHandler, Unit>::declarationPattern( } if (*forHeadKind != ParseNodeKind::ForHead) { - MOZ_TRY_VAR(*forInOrOfExpression, - expressionAfterForInOrOf(*forHeadKind, yieldHandling)); + *forInOrOfExpression = + MOZ_TRY(expressionAfterForInOrOf(*forHeadKind, yieldHandling)); return pattern; } @@ -4689,9 +4657,8 @@ GeneralParser<ParseHandler, Unit>::declarationPattern( return errorResult(); } - Node init; - MOZ_TRY_VAR(init, assignExpr(forHeadKind ? InProhibited : InAllowed, - yieldHandling, TripledotProhibited)); + Node init = MOZ_TRY(assignExpr(forHeadKind ? InProhibited : InAllowed, + yieldHandling, TripledotProhibited)); return handler_.newAssignment(ParseNodeKind::AssignExpr, pattern, init); } @@ -4709,9 +4676,8 @@ GeneralParser<ParseHandler, Unit>::initializerInNameDeclaration( return errorResult(); } - Node initializer; - MOZ_TRY_VAR(initializer, assignExpr(forHeadKind ? InProhibited : InAllowed, - yieldHandling, TripledotProhibited)); + Node initializer = MOZ_TRY(assignExpr(forHeadKind ? InProhibited : InAllowed, + yieldHandling, TripledotProhibited)); if (forHeadKind && initialDeclaration) { bool isForIn, isForOf; @@ -4744,8 +4710,7 @@ GeneralParser<ParseHandler, Unit>::initializerInNameDeclaration( return errorResult(); } - MOZ_TRY_VAR( - *forInOrOfExpression, + *forInOrOfExpression = MOZ_TRY( expressionAfterForInOrOf(ParseNodeKind::ForIn, yieldHandling)); } else { *forHeadKind = ParseNodeKind::ForHead; @@ -4774,8 +4739,7 @@ GeneralParser<ParseHandler, Unit>::declarationName(DeclarationKind declKind, return errorResult(); } - NameNodeType binding; - MOZ_TRY_VAR(binding, newName(name)); + NameNodeType binding = MOZ_TRY(newName(name)); TokenPos namePos = pos(); @@ -4794,10 +4758,9 @@ GeneralParser<ParseHandler, Unit>::declarationName(DeclarationKind declKind, Node declaration; if (matched) { - MOZ_TRY_VAR(declaration, - initializerInNameDeclaration(binding, declKind, - initialDeclaration, yieldHandling, - forHeadKind, forInOrOfExpression)); + declaration = MOZ_TRY(initializerInNameDeclaration( + binding, declKind, initialDeclaration, yieldHandling, forHeadKind, + forInOrOfExpression)); } else { declaration = binding; @@ -4824,8 +4787,8 @@ GeneralParser<ParseHandler, Unit>::declarationName(DeclarationKind declKind, } if (forHeadKind && *forHeadKind != ParseNodeKind::ForHead) { - MOZ_TRY_VAR(*forInOrOfExpression, - expressionAfterForInOrOf(*forHeadKind, yieldHandling)); + *forInOrOfExpression = + MOZ_TRY(expressionAfterForInOrOf(*forHeadKind, yieldHandling)); } else { // Normal const declarations, and const declarations in for(;;) // heads, must be initialized. @@ -4889,8 +4852,8 @@ GeneralParser<ParseHandler, Unit>::declarationList( MOZ_CRASH("Unknown declaration kind"); } - DeclarationListNodeType decl; - MOZ_TRY_VAR(decl, handler_.newDeclarationList(kind, pos())); + DeclarationListNodeType decl = + MOZ_TRY(handler_.newDeclarationList(kind, pos())); bool moreDeclarations; bool initialDeclaration = true; @@ -4905,13 +4868,13 @@ GeneralParser<ParseHandler, Unit>::declarationList( Node binding; if (tt == TokenKind::LeftBracket || tt == TokenKind::LeftCurly) { - MOZ_TRY_VAR(binding, declarationPattern(declKind, tt, initialDeclaration, - yieldHandling, forHeadKind, - forInOrOfExpression)); - } else { - MOZ_TRY_VAR(binding, declarationName(declKind, tt, initialDeclaration, + binding = MOZ_TRY(declarationPattern(declKind, tt, initialDeclaration, yieldHandling, forHeadKind, forInOrOfExpression)); + } else { + binding = MOZ_TRY(declarationName(declKind, tt, initialDeclaration, + yieldHandling, forHeadKind, + forInOrOfExpression)); } handler_.addList(decl, binding); @@ -4960,7 +4923,6 @@ GeneralParser<ParseHandler, Unit>::lexicalDeclaration( * * See 8.1.1.1.6 and the note in 13.2.1. */ - DeclarationListNodeType decl; ParseNodeKind pnk; switch (kind) { case DeclarationKind::Const: @@ -4980,7 +4942,7 @@ GeneralParser<ParseHandler, Unit>::lexicalDeclaration( default: MOZ_CRASH("unexpected node kind"); } - MOZ_TRY_VAR(decl, declarationList(yieldHandling, pnk)); + DeclarationListNodeType decl = MOZ_TRY(declarationList(yieldHandling, pnk)); if (!matchOrInsertSemicolon()) { return errorResult(); } @@ -5252,9 +5214,8 @@ GeneralParser<ParseHandler, Unit>::importDeclaration() { return errorResult(); } - ListNodeType importSpecSet; - MOZ_TRY_VAR(importSpecSet, - handler_.newList(ParseNodeKind::ImportSpecList, pos())); + ListNodeType importSpecSet = + MOZ_TRY(handler_.newList(ParseNodeKind::ImportSpecList, pos())); if (tt == TokenKind::String) { // Handle the form |import 'a'| by leaving the list empty. This is @@ -5274,24 +5235,22 @@ GeneralParser<ParseHandler, Unit>::importDeclaration() { // specifier to the list, with 'default' as the import name and // 'a' as the binding name. This is equivalent to // |import { default as a } from 'b'|. - NameNodeType importName; - MOZ_TRY_VAR(importName, - newName(TaggedParserAtomIndex::WellKnown::default_())); + NameNodeType importName = + MOZ_TRY(newName(TaggedParserAtomIndex::WellKnown::default_())); TaggedParserAtomIndex bindingAtom = importedBinding(); if (!bindingAtom) { return errorResult(); } - NameNodeType bindingName; - MOZ_TRY_VAR(bindingName, newName(bindingAtom)); + NameNodeType bindingName = MOZ_TRY(newName(bindingAtom)); if (!noteDeclaredName(bindingAtom, DeclarationKind::Import, pos())) { return errorResult(); } - BinaryNodeType importSpec; - MOZ_TRY_VAR(importSpec, handler_.newImportSpec(importName, bindingName)); + BinaryNodeType importSpec = + MOZ_TRY(handler_.newImportSpec(importName, bindingName)); handler_.addList(importSpecSet, importSpec); @@ -5332,16 +5291,14 @@ GeneralParser<ParseHandler, Unit>::importDeclaration() { } } - NameNodeType moduleSpec; - MOZ_TRY_VAR(moduleSpec, stringLiteral()); + NameNodeType moduleSpec = MOZ_TRY(stringLiteral()); if (!tokenStream.peekToken(&tt, TokenStream::SlashIsRegExp)) { return errorResult(); } - ListNodeType importAttributeList; - MOZ_TRY_VAR(importAttributeList, - handler_.newList(ParseNodeKind::ImportAttributeList, pos())); + ListNodeType importAttributeList = + MOZ_TRY(handler_.newList(ParseNodeKind::ImportAttributeList, pos())); if (tt == TokenKind::With) { tokenStream.consumeKnownToken(tt, TokenStream::SlashIsRegExp); @@ -5355,14 +5312,11 @@ GeneralParser<ParseHandler, Unit>::importDeclaration() { return errorResult(); } - BinaryNodeType moduleRequest; - MOZ_TRY_VAR(moduleRequest, - handler_.newModuleRequest(moduleSpec, importAttributeList, - TokenPos(begin, pos().end))); + BinaryNodeType moduleRequest = MOZ_TRY(handler_.newModuleRequest( + moduleSpec, importAttributeList, TokenPos(begin, pos().end))); - BinaryNodeType node; - MOZ_TRY_VAR(node, handler_.newImportDeclaration(importSpecSet, moduleRequest, - TokenPos(begin, pos().end))); + BinaryNodeType node = MOZ_TRY(handler_.newImportDeclaration( + importSpecSet, moduleRequest, TokenPos(begin, pos().end))); if (!processImport(node)) { return errorResult(); } @@ -5687,8 +5641,7 @@ GeneralParser<ParseHandler, Unit>::exportFrom(uint32_t begin, Node specList) { return errorResult(); } - NameNodeType moduleSpec; - MOZ_TRY_VAR(moduleSpec, stringLiteral()); + NameNodeType moduleSpec = MOZ_TRY(stringLiteral()); TokenKind tt; if (!tokenStream.peekToken(&tt, TokenStream::SlashIsRegExp)) { @@ -5697,9 +5650,8 @@ GeneralParser<ParseHandler, Unit>::exportFrom(uint32_t begin, Node specList) { uint32_t moduleSpecPos = pos().begin; - ListNodeType importAttributeList; - MOZ_TRY_VAR(importAttributeList, - handler_.newList(ParseNodeKind::ImportAttributeList, pos())); + ListNodeType importAttributeList = + MOZ_TRY(handler_.newList(ParseNodeKind::ImportAttributeList, pos())); if (tt == TokenKind::With) { tokenStream.consumeKnownToken(tt, TokenStream::SlashIsRegExp); @@ -5712,14 +5664,11 @@ GeneralParser<ParseHandler, Unit>::exportFrom(uint32_t begin, Node specList) { return errorResult(); } - BinaryNodeType moduleRequest; - MOZ_TRY_VAR(moduleRequest, - handler_.newModuleRequest(moduleSpec, importAttributeList, - TokenPos(moduleSpecPos, pos().end))); + BinaryNodeType moduleRequest = MOZ_TRY(handler_.newModuleRequest( + moduleSpec, importAttributeList, TokenPos(moduleSpecPos, pos().end))); - BinaryNodeType node; - MOZ_TRY_VAR( - node, handler_.newExportFromDeclaration(begin, specList, moduleRequest)); + BinaryNodeType node = MOZ_TRY( + handler_.newExportFromDeclaration(begin, specList, moduleRequest)); if (!processExportFrom(node)) { return errorResult(); @@ -5738,8 +5687,8 @@ GeneralParser<ParseHandler, Unit>::exportBatch(uint32_t begin) { MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::Mul)); uint32_t beginExportSpec = pos().begin; - ListNodeType kid; - MOZ_TRY_VAR(kid, handler_.newList(ParseNodeKind::ExportSpecList, pos())); + ListNodeType kid = + MOZ_TRY(handler_.newList(ParseNodeKind::ExportSpecList, pos())); bool foundAs; if (!tokenStream.matchToken(&foundAs, TokenKind::As)) { @@ -5754,9 +5703,9 @@ GeneralParser<ParseHandler, Unit>::exportBatch(uint32_t begin) { NameNodeType exportName = null(); if (TokenKindIsPossibleIdentifierName(tt)) { - MOZ_TRY_VAR(exportName, newName(anyChars.currentName())); + exportName = MOZ_TRY(newName(anyChars.currentName())); } else if (tt == TokenKind::String) { - MOZ_TRY_VAR(exportName, moduleExportName()); + exportName = MOZ_TRY(moduleExportName()); } else { error(JSMSG_NO_EXPORT_NAME); return errorResult(); @@ -5766,16 +5715,14 @@ GeneralParser<ParseHandler, Unit>::exportBatch(uint32_t begin) { return errorResult(); } - UnaryNodeType exportSpec; - MOZ_TRY_VAR(exportSpec, - handler_.newExportNamespaceSpec(beginExportSpec, exportName)); + UnaryNodeType exportSpec = + MOZ_TRY(handler_.newExportNamespaceSpec(beginExportSpec, exportName)); handler_.addList(kid, exportSpec); } else { // Handle the form |export *| by adding a special export batch // specifier to the list. - NullaryNodeType exportSpec; - MOZ_TRY_VAR(exportSpec, handler_.newExportBatchSpec(pos())); + NullaryNodeType exportSpec = MOZ_TRY(handler_.newExportBatchSpec(pos())); handler_.addList(kid, exportSpec); } @@ -5831,8 +5778,8 @@ GeneralParser<ParseHandler, Unit>::exportClause(uint32_t begin) { MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::LeftCurly)); - ListNodeType kid; - MOZ_TRY_VAR(kid, handler_.newList(ParseNodeKind::ExportSpecList, pos())); + ListNodeType kid = + MOZ_TRY(handler_.newList(ParseNodeKind::ExportSpecList, pos())); TokenKind tt; while (true) { @@ -5848,9 +5795,9 @@ GeneralParser<ParseHandler, Unit>::exportClause(uint32_t begin) { NameNodeType bindingName = null(); if (TokenKindIsPossibleIdentifierName(tt)) { - MOZ_TRY_VAR(bindingName, newName(anyChars.currentName())); + bindingName = MOZ_TRY(newName(anyChars.currentName())); } else if (tt == TokenKind::String) { - MOZ_TRY_VAR(bindingName, moduleExportName()); + bindingName = MOZ_TRY(moduleExportName()); } else { error(JSMSG_NO_BINDING_NAME); return errorResult(); @@ -5869,18 +5816,18 @@ GeneralParser<ParseHandler, Unit>::exportClause(uint32_t begin) { } if (TokenKindIsPossibleIdentifierName(tt)) { - MOZ_TRY_VAR(exportName, newName(anyChars.currentName())); + exportName = MOZ_TRY(newName(anyChars.currentName())); } else if (tt == TokenKind::String) { - MOZ_TRY_VAR(exportName, moduleExportName()); + exportName = MOZ_TRY(moduleExportName()); } else { error(JSMSG_NO_EXPORT_NAME); return errorResult(); } } else { if (tt != TokenKind::String) { - MOZ_TRY_VAR(exportName, newName(anyChars.currentName())); + exportName = MOZ_TRY(newName(anyChars.currentName())); } else { - MOZ_TRY_VAR(exportName, moduleExportName()); + exportName = MOZ_TRY(moduleExportName()); } } @@ -5888,8 +5835,8 @@ GeneralParser<ParseHandler, Unit>::exportClause(uint32_t begin) { return errorResult(); } - BinaryNodeType exportSpec; - MOZ_TRY_VAR(exportSpec, handler_.newExportSpec(bindingName, exportName)); + BinaryNodeType exportSpec = + MOZ_TRY(handler_.newExportSpec(bindingName, exportName)); handler_.addList(kid, exportSpec); @@ -5940,9 +5887,8 @@ GeneralParser<ParseHandler, Unit>::exportClause(uint32_t begin) { return errorResult(); } - UnaryNodeType node; - MOZ_TRY_VAR(node, - handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); + UnaryNodeType node = + MOZ_TRY(handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -5960,8 +5906,8 @@ GeneralParser<ParseHandler, Unit>::exportVariableStatement(uint32_t begin) { MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::Var)); - DeclarationListNodeType kid; - MOZ_TRY_VAR(kid, declarationList(YieldIsName, ParseNodeKind::VarStmt)); + DeclarationListNodeType kid = + MOZ_TRY(declarationList(YieldIsName, ParseNodeKind::VarStmt)); if (!matchOrInsertSemicolon()) { return errorResult(); } @@ -5969,9 +5915,8 @@ GeneralParser<ParseHandler, Unit>::exportVariableStatement(uint32_t begin) { return errorResult(); } - UnaryNodeType node; - MOZ_TRY_VAR(node, - handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); + UnaryNodeType node = + MOZ_TRY(handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -5991,17 +5936,15 @@ GeneralParser<ParseHandler, Unit>::exportFunctionDeclaration( MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::Function)); - Node kid; - MOZ_TRY_VAR( - kid, functionStmt(toStringStart, YieldIsName, NameRequired, asyncKind)); + Node kid = MOZ_TRY( + functionStmt(toStringStart, YieldIsName, NameRequired, asyncKind)); if (!checkExportedNameForFunction(handler_.asFunctionNode(kid))) { return errorResult(); } - UnaryNodeType node; - MOZ_TRY_VAR(node, - handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); + UnaryNodeType node = + MOZ_TRY(handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -6019,16 +5962,15 @@ GeneralParser<ParseHandler, Unit>::exportClassDeclaration(uint32_t begin) { MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::Class)); - ClassNodeType kid; - MOZ_TRY_VAR(kid, classDefinition(YieldIsName, ClassStatement, NameRequired)); + ClassNodeType kid = + MOZ_TRY(classDefinition(YieldIsName, ClassStatement, NameRequired)); if (!checkExportedNameForClass(kid)) { return errorResult(); } - UnaryNodeType node; - MOZ_TRY_VAR(node, - handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); + UnaryNodeType node = + MOZ_TRY(handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -6051,15 +5993,13 @@ GeneralParser<ParseHandler, Unit>::exportLexicalDeclaration( MOZ_ASSERT_IF(kind == DeclarationKind::Let, anyChars.isCurrentTokenType(TokenKind::Let)); - DeclarationListNodeType kid; - MOZ_TRY_VAR(kid, lexicalDeclaration(YieldIsName, kind)); + DeclarationListNodeType kid = MOZ_TRY(lexicalDeclaration(YieldIsName, kind)); if (!checkExportedNamesForDeclarationList(kid)) { return errorResult(); } - UnaryNodeType node; - MOZ_TRY_VAR(node, - handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); + UnaryNodeType node = + MOZ_TRY(handler_.newExportDeclaration(kid, TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -6079,13 +6019,11 @@ GeneralParser<ParseHandler, Unit>::exportDefaultFunctionDeclaration( MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::Function)); - Node kid; - MOZ_TRY_VAR(kid, functionStmt(toStringStart, YieldIsName, AllowDefaultName, - asyncKind)); + Node kid = MOZ_TRY( + functionStmt(toStringStart, YieldIsName, AllowDefaultName, asyncKind)); - BinaryNodeType node; - MOZ_TRY_VAR(node, handler_.newExportDefaultDeclaration( - kid, null(), TokenPos(begin, pos().end))); + BinaryNodeType node = MOZ_TRY(handler_.newExportDefaultDeclaration( + kid, null(), TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -6104,13 +6042,11 @@ GeneralParser<ParseHandler, Unit>::exportDefaultClassDeclaration( MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::Class)); - ClassNodeType kid; - MOZ_TRY_VAR(kid, - classDefinition(YieldIsName, ClassStatement, AllowDefaultName)); + ClassNodeType kid = + MOZ_TRY(classDefinition(YieldIsName, ClassStatement, AllowDefaultName)); - BinaryNodeType node; - MOZ_TRY_VAR(node, handler_.newExportDefaultDeclaration( - kid, null(), TokenPos(begin, pos().end))); + BinaryNodeType node = MOZ_TRY(handler_.newExportDefaultDeclaration( + kid, null(), TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -6127,22 +6063,19 @@ GeneralParser<ParseHandler, Unit>::exportDefaultAssignExpr(uint32_t begin) { } TaggedParserAtomIndex name = TaggedParserAtomIndex::WellKnown::default_(); - NameNodeType nameNode; - MOZ_TRY_VAR(nameNode, newName(name)); + NameNodeType nameNode = MOZ_TRY(newName(name)); if (!noteDeclaredName(name, DeclarationKind::Const, pos())) { return errorResult(); } - Node kid; - MOZ_TRY_VAR(kid, assignExpr(InAllowed, YieldIsName, TripledotProhibited)); + Node kid = MOZ_TRY(assignExpr(InAllowed, YieldIsName, TripledotProhibited)); if (!matchOrInsertSemicolon()) { return errorResult(); } - BinaryNodeType node; - MOZ_TRY_VAR(node, handler_.newExportDefaultDeclaration( - kid, nameNode, TokenPos(begin, pos().end))); + BinaryNodeType node = MOZ_TRY(handler_.newExportDefaultDeclaration( + kid, nameNode, TokenPos(begin, pos().end))); if (!processExport(node)) { return errorResult(); @@ -6272,9 +6205,8 @@ typename ParseHandler::UnaryNodeResult GeneralParser<ParseHandler, Unit>::expressionStatement( YieldHandling yieldHandling, InvokedPrediction invoked) { anyChars.ungetToken(); - Node pnexpr; - MOZ_TRY_VAR(pnexpr, expr(InAllowed, yieldHandling, TripledotProhibited, - /* possibleError = */ nullptr, invoked)); + Node pnexpr = MOZ_TRY(expr(InAllowed, yieldHandling, TripledotProhibited, + /* possibleError = */ nullptr, invoked)); if (!matchOrInsertSemicolon()) { return errorResult(); } @@ -6323,11 +6255,9 @@ GeneralParser<ParseHandler, Unit>::consequentOrAlternative( } TokenPos funcPos = pos(); - Node fun; - MOZ_TRY_VAR(fun, functionStmt(pos().begin, yieldHandling, NameRequired)); + Node fun = MOZ_TRY(functionStmt(pos().begin, yieldHandling, NameRequired)); - ListNodeType block; - MOZ_TRY_VAR(block, handler_.newStatementList(funcPos)); + ListNodeType block = MOZ_TRY(handler_.newStatementList(funcPos)); handler_.addStatementToList(block, fun); return finishLexicalScope(scope, block); @@ -6349,16 +6279,14 @@ GeneralParser<ParseHandler, Unit>::ifStatement(YieldHandling yieldHandling) { uint32_t begin = pos().begin; /* An IF node has three kids: condition, then, and optional else. */ - Node cond; - MOZ_TRY_VAR(cond, condition(InAllowed, yieldHandling)); + Node cond = MOZ_TRY(condition(InAllowed, yieldHandling)); TokenKind tt; if (!tokenStream.peekToken(&tt, TokenStream::SlashIsRegExp)) { return errorResult(); } - Node thenBranch; - MOZ_TRY_VAR(thenBranch, consequentOrAlternative(yieldHandling)); + Node thenBranch = MOZ_TRY(consequentOrAlternative(yieldHandling)); if (!condList.append(cond) || !thenList.append(thenBranch) || !posList.append(begin)) { @@ -6378,7 +6306,7 @@ GeneralParser<ParseHandler, Unit>::ifStatement(YieldHandling yieldHandling) { if (matched) { continue; } - MOZ_TRY_VAR(elseBranch, consequentOrAlternative(yieldHandling)); + elseBranch = MOZ_TRY(consequentOrAlternative(yieldHandling)); } else { elseBranch = null(); } @@ -6387,8 +6315,8 @@ GeneralParser<ParseHandler, Unit>::ifStatement(YieldHandling yieldHandling) { TernaryNodeType ifNode; for (int i = condList.length() - 1; i >= 0; i--) { - MOZ_TRY_VAR(ifNode, handler_.newIfStatement(posList[i], condList[i], - thenList[i], elseBranch)); + ifNode = MOZ_TRY(handler_.newIfStatement(posList[i], condList[i], + thenList[i], elseBranch)); elseBranch = ifNode; } @@ -6401,13 +6329,11 @@ GeneralParser<ParseHandler, Unit>::doWhileStatement( YieldHandling yieldHandling) { uint32_t begin = pos().begin; ParseContext::Statement stmt(pc_, StatementKind::DoLoop); - Node body; - MOZ_TRY_VAR(body, statement(yieldHandling)); + Node body = MOZ_TRY(statement(yieldHandling)); if (!mustMatchToken(TokenKind::While, JSMSG_WHILE_AFTER_DO)) { return errorResult(); } - Node cond; - MOZ_TRY_VAR(cond, condition(InAllowed, yieldHandling)); + Node cond = MOZ_TRY(condition(InAllowed, yieldHandling)); // The semicolon after do-while is even more optional than most // semicolons in JS. Web compat required this by 2004: @@ -6428,10 +6354,8 @@ typename ParseHandler::BinaryNodeResult GeneralParser<ParseHandler, Unit>::whileStatement(YieldHandling yieldHandling) { uint32_t begin = pos().begin; ParseContext::Statement stmt(pc_, StatementKind::WhileLoop); - Node cond; - MOZ_TRY_VAR(cond, condition(InAllowed, yieldHandling)); - Node body; - MOZ_TRY_VAR(body, statement(yieldHandling)); + Node cond = MOZ_TRY(condition(InAllowed, yieldHandling)); + Node body = MOZ_TRY(statement(yieldHandling)); return handler_.newWhileStatement(begin, cond, body); } @@ -6879,7 +6803,7 @@ GeneralParser<ParseHandler, Unit>::forStatement(YieldHandling yieldHandling) { if (tt == TokenKind::Semi) { test = null(); } else { - MOZ_TRY_VAR(test, expr(InAllowed, yieldHandling, TripledotProhibited)); + test = MOZ_TRY(expr(InAllowed, yieldHandling, TripledotProhibited)); } if (!mustMatchToken(TokenKind::Semi, JSMSG_SEMI_AFTER_FOR_COND)) { @@ -6894,7 +6818,7 @@ GeneralParser<ParseHandler, Unit>::forStatement(YieldHandling yieldHandling) { if (tt == TokenKind::RightParen) { update = null(); } else { - MOZ_TRY_VAR(update, expr(InAllowed, yieldHandling, TripledotProhibited)); + update = MOZ_TRY(expr(InAllowed, yieldHandling, TripledotProhibited)); } if (!mustMatchToken(TokenKind::RightParen, JSMSG_PAREN_AFTER_FOR_CTRL)) { @@ -6902,7 +6826,7 @@ GeneralParser<ParseHandler, Unit>::forStatement(YieldHandling yieldHandling) { } TokenPos headPos(begin, pos().end); - MOZ_TRY_VAR(forHead, handler_.newForHead(init, test, update, headPos)); + forHead = MOZ_TRY(handler_.newForHead(init, test, update, headPos)); } else { MOZ_ASSERT(headKind == ParseNodeKind::ForIn || headKind == ParseNodeKind::ForOf); @@ -6927,15 +6851,14 @@ GeneralParser<ParseHandler, Unit>::forStatement(YieldHandling yieldHandling) { } TokenPos headPos(begin, pos().end); - MOZ_TRY_VAR(forHead, handler_.newForInOrOfHead(headKind, target, - iteratedExpr, headPos)); + forHead = MOZ_TRY( + handler_.newForInOrOfHead(headKind, target, iteratedExpr, headPos)); } - Node body; - MOZ_TRY_VAR(body, statement(yieldHandling)); + Node body = MOZ_TRY(statement(yieldHandling)); - ForNodeType forLoop; - MOZ_TRY_VAR(forLoop, handler_.newForStatement(begin, forHead, body, iflags)); + ForNodeType forLoop = + MOZ_TRY(handler_.newForStatement(begin, forHead, body, iflags)); if (forLoopLexicalScope) { return finishLexicalScope(*forLoopLexicalScope, forLoop); @@ -6955,9 +6878,8 @@ GeneralParser<ParseHandler, Unit>::switchStatement( return errorResult(); } - Node discriminant; - MOZ_TRY_VAR(discriminant, - exprInParens(InAllowed, yieldHandling, TripledotProhibited)); + Node discriminant = + MOZ_TRY(exprInParens(InAllowed, yieldHandling, TripledotProhibited)); if (!mustMatchToken(TokenKind::RightParen, JSMSG_PAREN_AFTER_SWITCH)) { return errorResult(); @@ -6972,8 +6894,7 @@ GeneralParser<ParseHandler, Unit>::switchStatement( return errorResult(); } - ListNodeType caseList; - MOZ_TRY_VAR(caseList, handler_.newStatementList(pos())); + ListNodeType caseList = MOZ_TRY(handler_.newStatementList(pos())); bool seenDefault = false; TokenKind tt; @@ -6998,8 +6919,7 @@ GeneralParser<ParseHandler, Unit>::switchStatement( break; case TokenKind::Case: - MOZ_TRY_VAR(caseExpr, - expr(InAllowed, yieldHandling, TripledotProhibited)); + caseExpr = MOZ_TRY(expr(InAllowed, yieldHandling, TripledotProhibited)); break; default: @@ -7011,8 +6931,7 @@ GeneralParser<ParseHandler, Unit>::switchStatement( return errorResult(); } - ListNodeType body; - MOZ_TRY_VAR(body, handler_.newStatementList(pos())); + ListNodeType body = MOZ_TRY(handler_.newStatementList(pos())); bool afterReturn = false; bool warnedAboutStatementsAfterReturn = false; @@ -7031,8 +6950,7 @@ GeneralParser<ParseHandler, Unit>::switchStatement( return errorResult(); } } - Node stmt; - MOZ_TRY_VAR(stmt, statementListItem(yieldHandling)); + Node stmt = MOZ_TRY(statementListItem(yieldHandling)); if (!warnedAboutStatementsAfterReturn) { if (afterReturn) { if (!handler_.isStatementPermittedAfterReturnStatement(stmt)) { @@ -7049,14 +6967,13 @@ GeneralParser<ParseHandler, Unit>::switchStatement( handler_.addStatementToList(body, stmt); } - CaseClauseType caseClause; - MOZ_TRY_VAR(caseClause, - handler_.newCaseOrDefault(caseBegin, caseExpr, body)); + CaseClauseType caseClause = + MOZ_TRY(handler_.newCaseOrDefault(caseBegin, caseExpr, body)); handler_.addCaseStatementToList(caseList, caseClause); } - LexicalScopeNodeType lexicalForCaseList; - MOZ_TRY_VAR(lexicalForCaseList, finishLexicalScope(scope, caseList)); + LexicalScopeNodeType lexicalForCaseList = + MOZ_TRY(finishLexicalScope(scope, caseList)); handler_.setEndPosition(lexicalForCaseList, pos().end); @@ -7138,11 +7055,12 @@ GeneralParser<ParseHandler, Unit>::returnStatement( // Parse an optional operand. // // This is ugly, but we don't want to require a semicolon. - Node exprNode; TokenKind tt = TokenKind::Eof; if (!tokenStream.peekTokenSameLine(&tt, TokenStream::SlashIsRegExp)) { return errorResult(); } + + Node exprNode; switch (tt) { case TokenKind::Eol: case TokenKind::Eof: @@ -7151,8 +7069,7 @@ GeneralParser<ParseHandler, Unit>::returnStatement( exprNode = null(); break; default: { - MOZ_TRY_VAR(exprNode, - expr(InAllowed, yieldHandling, TripledotProhibited)); + exprNode = MOZ_TRY(expr(InAllowed, yieldHandling, TripledotProhibited)); } } @@ -7204,8 +7121,8 @@ GeneralParser<ParseHandler, Unit>::yieldExpression(InHandling inHandling) { tokenStream.consumeKnownToken(TokenKind::Mul, TokenStream::SlashIsRegExp); [[fallthrough]]; default: - MOZ_TRY_VAR(exprNode, - assignExpr(inHandling, YieldIsKeyword, TripledotProhibited)); + exprNode = + MOZ_TRY(assignExpr(inHandling, YieldIsKeyword, TripledotProhibited)); } if (kind == ParseNodeKind::YieldStarExpr) { return handler_.newYieldStarExpression(begin, exprNode); @@ -7229,9 +7146,8 @@ GeneralParser<ParseHandler, Unit>::withStatement(YieldHandling yieldHandling) { return errorResult(); } - Node objectExpr; - MOZ_TRY_VAR(objectExpr, - exprInParens(InAllowed, yieldHandling, TripledotProhibited)); + Node objectExpr = + MOZ_TRY(exprInParens(InAllowed, yieldHandling, TripledotProhibited)); if (!mustMatchToken(TokenKind::RightParen, JSMSG_PAREN_AFTER_WITH)) { return errorResult(); @@ -7240,7 +7156,7 @@ GeneralParser<ParseHandler, Unit>::withStatement(YieldHandling yieldHandling) { Node innerBlock; { ParseContext::Statement stmt(pc_, StatementKind::With); - MOZ_TRY_VAR(innerBlock, statement(yieldHandling)); + innerBlock = MOZ_TRY(statement(yieldHandling)); } pc_->sc()->setBindingsAccessedDynamically(); @@ -7309,8 +7225,7 @@ GeneralParser<ParseHandler, Unit>::labeledStatement( /* Push a label struct and parse the statement. */ ParseContext::LabelStatement stmt(pc_, label); - Node pn; - MOZ_TRY_VAR(pn, labeledItem(yieldHandling)); + Node pn = MOZ_TRY(labeledItem(yieldHandling)); return handler_.newLabeledStatement(label, pn, begin); } @@ -7336,8 +7251,7 @@ GeneralParser<ParseHandler, Unit>::throwStatement(YieldHandling yieldHandling) { return errorResult(); } - Node throwExpr; - MOZ_TRY_VAR(throwExpr, expr(InAllowed, yieldHandling, TripledotProhibited)); + Node throwExpr = MOZ_TRY(expr(InAllowed, yieldHandling, TripledotProhibited)); if (!matchOrInsertSemicolon()) { return errorResult(); @@ -7384,9 +7298,9 @@ GeneralParser<ParseHandler, Unit>::tryStatement(YieldHandling yieldHandling) { return errorResult(); } - MOZ_TRY_VAR(innerBlock, statementList(yieldHandling)); + innerBlock = MOZ_TRY(statementList(yieldHandling)); - MOZ_TRY_VAR(innerBlock, finishLexicalScope(scope, innerBlock)); + innerBlock = MOZ_TRY(finishLexicalScope(scope, innerBlock)); if (!mustMatchToken( TokenKind::RightCurly, [this, openedPos](TokenKind actual) { @@ -7438,9 +7352,8 @@ GeneralParser<ParseHandler, Unit>::tryStatement(YieldHandling yieldHandling) { switch (tt) { case TokenKind::LeftBracket: case TokenKind::LeftCurly: - MOZ_TRY_VAR(catchName, - destructuringDeclaration(DeclarationKind::CatchParameter, - yieldHandling, tt)); + catchName = MOZ_TRY(destructuringDeclaration( + DeclarationKind::CatchParameter, yieldHandling, tt)); break; default: { @@ -7449,9 +7362,8 @@ GeneralParser<ParseHandler, Unit>::tryStatement(YieldHandling yieldHandling) { return errorResult(); } - MOZ_TRY_VAR(catchName, - bindingIdentifier(DeclarationKind::SimpleCatchParameter, - yieldHandling)); + catchName = MOZ_TRY(bindingIdentifier( + DeclarationKind::SimpleCatchParameter, yieldHandling)); break; } } @@ -7465,10 +7377,10 @@ GeneralParser<ParseHandler, Unit>::tryStatement(YieldHandling yieldHandling) { } } - LexicalScopeNodeType catchBody; - MOZ_TRY_VAR(catchBody, catchBlockStatement(yieldHandling, scope)); + LexicalScopeNodeType catchBody = + MOZ_TRY(catchBlockStatement(yieldHandling, scope)); - MOZ_TRY_VAR(catchScope, finishLexicalScope(scope, catchBody)); + catchScope = MOZ_TRY(finishLexicalScope(scope, catchBody)); if (!handler_.setupCatchScope(catchScope, catchName, catchBody)) { return errorResult(); @@ -7495,9 +7407,9 @@ GeneralParser<ParseHandler, Unit>::tryStatement(YieldHandling yieldHandling) { return errorResult(); } - MOZ_TRY_VAR(finallyBlock, statementList(yieldHandling)); + finallyBlock = MOZ_TRY(statementList(yieldHandling)); - MOZ_TRY_VAR(finallyBlock, finishLexicalScope(scope, finallyBlock)); + finallyBlock = MOZ_TRY(finishLexicalScope(scope, finallyBlock)); if (!mustMatchToken( TokenKind::RightCurly, [this, openedPos](TokenKind actual) { @@ -7540,8 +7452,7 @@ GeneralParser<ParseHandler, Unit>::catchBlockStatement( return errorResult(); } - ListNodeType list; - MOZ_TRY_VAR(list, statementList(yieldHandling)); + ListNodeType list = MOZ_TRY(statementList(yieldHandling)); if (!mustMatchToken( TokenKind::RightCurly, [this, openedPos](TokenKind actual) { @@ -7593,9 +7504,8 @@ static AccessorType ToAccessorType(PropertyType propType) { template <class ParseHandler, typename Unit> typename ParseHandler::ListNodeResult GeneralParser<ParseHandler, Unit>::decoratorList(YieldHandling yieldHandling) { - ListNodeType decorators; - MOZ_TRY_VAR(decorators, - handler_.newList(ParseNodeKind::DecoratorList, pos())); + ListNodeType decorators = + MOZ_TRY(handler_.newList(ParseNodeKind::DecoratorList, pos())); // Build a decorator list element. At each entry point to this loop we have // already consumed the |@| token @@ -7605,8 +7515,7 @@ GeneralParser<ParseHandler, Unit>::decoratorList(YieldHandling yieldHandling) { return errorResult(); } - Node decorator; - MOZ_TRY_VAR(decorator, decoratorExpr(yieldHandling, tt)); + Node decorator = MOZ_TRY(decoratorExpr(yieldHandling, tt)); handler_.addList(decorators, decorator); @@ -8119,7 +8028,7 @@ GeneralParser<ParseHandler, Unit>::classDefinition( ListNodeType decorators = null(); FunctionNodeType addInitializerFunction = null(); if (anyChars.isCurrentTokenType(TokenKind::At)) { - MOZ_TRY_VAR(decorators, decoratorList(yieldHandling)); + decorators = MOZ_TRY(decoratorList(yieldHandling)); TokenKind next; if (!tokenStream.getToken(&next)) { return errorResult(); @@ -8207,8 +8116,8 @@ GeneralParser<ParseHandler, Unit>::classDefinition( if (!tokenStream.getToken(&tt)) { return errorResult(); } - MOZ_TRY_VAR(classHeritage, - optionalExpr(yieldHandling, TripledotProhibited, tt)); + classHeritage = + MOZ_TRY(optionalExpr(yieldHandling, TripledotProhibited, tt)); } if (!mustMatchToken(TokenKind::LeftCurly, JSMSG_CURLY_BEFORE_CLASS)) { @@ -8222,8 +8131,8 @@ GeneralParser<ParseHandler, Unit>::classDefinition( return errorResult(); } - ListNodeType classMembers; - MOZ_TRY_VAR(classMembers, handler_.newClassMemberList(pos().begin)); + ListNodeType classMembers = + MOZ_TRY(handler_.newClassMemberList(pos().begin)); ClassInitializedMembers classInitializedMembers{}; for (;;) { @@ -8239,11 +8148,9 @@ GeneralParser<ParseHandler, Unit>::classDefinition( } #ifdef ENABLE_DECORATORS if (classInitializedMembers.hasInstanceDecorators) { - MOZ_TRY_VAR(addInitializerFunction, - synthesizeAddInitializerFunction( - TaggedParserAtomIndex::WellKnown:: - dot_instanceExtraInitializers_(), - yieldHandling)); + addInitializerFunction = MOZ_TRY(synthesizeAddInitializerFunction( + TaggedParserAtomIndex::WellKnown::dot_instanceExtraInitializers_(), + yieldHandling)); } #endif @@ -8292,8 +8199,7 @@ GeneralParser<ParseHandler, Unit>::classDefinition( return errorResult(); } - MOZ_TRY_VAR(classBodyBlock, - finishClassBodyScope(bodyScope, classMembers)); + classBodyBlock = MOZ_TRY(finishClassBodyScope(bodyScope, classMembers)); // Pop the class body scope } @@ -8304,10 +8210,10 @@ GeneralParser<ParseHandler, Unit>::classDefinition( return errorResult(); } - MOZ_TRY_VAR(innerName, newName(className, namePos)); + innerName = MOZ_TRY(newName(className, namePos)); } - MOZ_TRY_VAR(classBlock, finishLexicalScope(innerScope, classBodyBlock)); + classBlock = MOZ_TRY(finishLexicalScope(innerScope, classBodyBlock)); // Pop the inner scope. } @@ -8320,11 +8226,10 @@ GeneralParser<ParseHandler, Unit>::classDefinition( return errorResult(); } - MOZ_TRY_VAR(outerName, newName(className, namePos)); + outerName = MOZ_TRY(newName(className, namePos)); } - MOZ_TRY_VAR(nameNode, - handler_.newClassNames(outerName, innerName, namePos)); + nameNode = MOZ_TRY(handler_.newClassNames(outerName, innerName, namePos)); } MOZ_ALWAYS_TRUE(setLocalStrictMode(savedStrictness)); // We're leaving a class definition that was not itself nested within a class @@ -8370,9 +8275,8 @@ GeneralParser<ParseHandler, Unit>::synthesizeConstructor( FunctionAsyncKind::SyncFunction, isSelfHosting); // Create the top-level field initializer node. - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, - handler_.newFunction(functionSyntaxKind, synthesizedBodyPos)); + FunctionNodeType funNode = + MOZ_TRY(handler_.newFunction(functionSyntaxKind, synthesizedBodyPos)); // If we see any inner function, note it on our current context. The bytecode // emitter may eliminate the function later, but we use a conservative @@ -8565,8 +8469,8 @@ GeneralParser<ParseHandler, Unit>::privateMethodInitializer( FunctionFlags flags = InitialFunctionFlags(syntaxKind, generatorKind, asyncKind, isSelfHosting); - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, propNamePos)); + FunctionNodeType funNode = + MOZ_TRY(handler_.newFunction(syntaxKind, propNamePos)); Directives directives(true); FunctionBox* funbox = @@ -8586,8 +8490,7 @@ GeneralParser<ParseHandler, Unit>::privateMethodInitializer( pc_->functionScope().useAsVarScope(pc_); // Add empty parameter list. - ParamsBodyNodeType argsbody; - MOZ_TRY_VAR(argsbody, handler_.newParamsBody(propNamePos)); + ParamsBodyNodeType argsbody = MOZ_TRY(handler_.newParamsBody(propNamePos)); handler_.setFunctionFormalParametersAndBody(funNode, argsbody); setFunctionStartAtCurrentToken(funbox); funbox->setArgCount(0); @@ -8604,8 +8507,7 @@ GeneralParser<ParseHandler, Unit>::privateMethodInitializer( // a body of synthesized AST nodes. Instead, the body is left empty and the // initializer is synthesized at the bytecode level. // See BytecodeEmitter::emitPrivateMethodInitializer. - ListNodeType stmtList; - MOZ_TRY_VAR(stmtList, handler_.newStatementList(propNamePos)); + ListNodeType stmtList = MOZ_TRY(handler_.newStatementList(propNamePos)); bool canSkipLazyClosedOverBindings = handler_.reuseClosedOverBindings(); if (!pc_->declareFunctionThis(usedNames_, canSkipLazyClosedOverBindings)) { @@ -8615,9 +8517,8 @@ GeneralParser<ParseHandler, Unit>::privateMethodInitializer( return errorResult(); } - LexicalScopeNodeType initializerBody; - MOZ_TRY_VAR(initializerBody, finishLexicalScope(pc_->varScope(), stmtList, - ScopeKind::FunctionLexical)); + LexicalScopeNodeType initializerBody = MOZ_TRY(finishLexicalScope( + pc_->varScope(), stmtList, ScopeKind::FunctionLexical)); handler_.setBeginPosition(initializerBody, stmtList); handler_.setEndPosition(initializerBody, stmtList); handler_.setFunctionBody(funNode, initializerBody); @@ -8658,8 +8559,7 @@ GeneralParser<ParseHandler, Unit>::staticClassBlock( AutoAwaitIsKeyword awaitIsKeyword(this, AwaitHandling::AwaitIsDisallowed); // Create the function node for the static class body. - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, pos())); + FunctionNodeType funNode = MOZ_TRY(handler_.newFunction(syntaxKind, pos())); // Create the FunctionBox and link it to the function object. Directives directives(true); @@ -8697,9 +8597,8 @@ GeneralParser<ParseHandler, Unit>::staticClassBlock( // .staticInitializers is noted as used. classInitializedMembers.staticFields++; - LexicalScopeNodeType body; - MOZ_TRY_VAR(body, - functionBody(InHandling::InAllowed, YieldHandling::YieldIsKeyword, + LexicalScopeNodeType body = + MOZ_TRY(functionBody(InHandling::InAllowed, YieldHandling::YieldIsKeyword, syntaxKind, FunctionBodyType::StatementListBody)); if (anyChars.isEOF()) { @@ -8717,8 +8616,7 @@ GeneralParser<ParseHandler, Unit>::staticClassBlock( // Create a ParamsBodyNode for the parameters + body (there are no // parameters). - ParamsBodyNodeType argsbody; - MOZ_TRY_VAR(argsbody, handler_.newParamsBody(wholeBodyPos)); + ParamsBodyNodeType argsbody = MOZ_TRY(handler_.newParamsBody(wholeBodyPos)); handler_.setFunctionFormalParametersAndBody(funNode, argsbody); funbox->setArgCount(0); @@ -8766,8 +8664,8 @@ GeneralParser<ParseHandler, Unit>::fieldInitializerOpt( InitialFunctionFlags(syntaxKind, generatorKind, asyncKind, isSelfHosting); // Create the top-level field initializer node. - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, propNamePos)); + FunctionNodeType funNode = + MOZ_TRY(handler_.newFunction(syntaxKind, propNamePos)); // Create the FunctionBox and link it to the function object. Directives directives(true); @@ -8799,13 +8697,13 @@ GeneralParser<ParseHandler, Unit>::fieldInitializerOpt( // Parse the expression for the field initializer. { AutoAwaitIsKeyword awaitHandling(this, AwaitIsName); - MOZ_TRY_VAR(initializerExpr, - assignExpr(InAllowed, YieldIsName, TripledotProhibited)); + initializerExpr = + MOZ_TRY(assignExpr(InAllowed, YieldIsName, TripledotProhibited)); } handler_.checkAndSetIsDirectRHSAnonFunction(initializerExpr); } else { - MOZ_TRY_VAR(initializerExpr, handler_.newRawUndefinedLiteral(propNamePos)); + initializerExpr = MOZ_TRY(handler_.newRawUndefinedLiteral(propNamePos)); } TokenPos wholeInitializerPos(propNamePos.begin, pos().end); @@ -8816,18 +8714,16 @@ GeneralParser<ParseHandler, Unit>::fieldInitializerOpt( // Create a ParamsBodyNode for the parameters + body (there are no // parameters). - ParamsBodyNodeType argsbody; - MOZ_TRY_VAR(argsbody, handler_.newParamsBody(wholeInitializerPos)); + ParamsBodyNodeType argsbody = + MOZ_TRY(handler_.newParamsBody(wholeInitializerPos)); handler_.setFunctionFormalParametersAndBody(funNode, argsbody); funbox->setArgCount(0); - NameNodeType thisName; - MOZ_TRY_VAR(thisName, newThisName()); + NameNodeType thisName = MOZ_TRY(newThisName()); // Build `this.field` expression. - ThisLiteralType propAssignThis; - MOZ_TRY_VAR(propAssignThis, - handler_.newThisLiteral(wholeInitializerPos, thisName)); + ThisLiteralType propAssignThis = + MOZ_TRY(handler_.newThisLiteral(wholeInitializerPos, thisName)); Node propAssignFieldAccess; uint32_t indexValue; @@ -8836,14 +8732,11 @@ GeneralParser<ParseHandler, Unit>::fieldInitializerOpt( // .fieldKeys means and its purpose. NameNodeType fieldKeysName; if (isStatic) { - MOZ_TRY_VAR( - fieldKeysName, - newInternalDotName( - TaggedParserAtomIndex::WellKnown::dot_staticFieldKeys_())); + fieldKeysName = MOZ_TRY(newInternalDotName( + TaggedParserAtomIndex::WellKnown::dot_staticFieldKeys_())); } else { - MOZ_TRY_VAR(fieldKeysName, - newInternalDotName( - TaggedParserAtomIndex::WellKnown::dot_fieldKeys_())); + fieldKeysName = MOZ_TRY(newInternalDotName( + TaggedParserAtomIndex::WellKnown::dot_fieldKeys_())); } if (!fieldKeysName) { return errorResult(); @@ -8855,19 +8748,14 @@ GeneralParser<ParseHandler, Unit>::fieldInitializerOpt( } else { fieldKeyIndex = classInitializedMembers.instanceFieldKeys++; } - Node fieldKeyIndexNode; - MOZ_TRY_VAR(fieldKeyIndexNode, - handler_.newNumber(fieldKeyIndex, DecimalPoint::NoDecimal, - wholeInitializerPos)); + Node fieldKeyIndexNode = MOZ_TRY(handler_.newNumber( + fieldKeyIndex, DecimalPoint::NoDecimal, wholeInitializerPos)); - Node fieldKeyValue; - MOZ_TRY_VAR(fieldKeyValue, - handler_.newPropertyByValue(fieldKeysName, fieldKeyIndexNode, - wholeInitializerPos.end)); + Node fieldKeyValue = MOZ_TRY(handler_.newPropertyByValue( + fieldKeysName, fieldKeyIndexNode, wholeInitializerPos.end)); - MOZ_TRY_VAR(propAssignFieldAccess, - handler_.newPropertyByValue(propAssignThis, fieldKeyValue, - wholeInitializerPos.end)); + propAssignFieldAccess = MOZ_TRY(handler_.newPropertyByValue( + propAssignThis, fieldKeyValue, wholeInitializerPos.end)); } else if (handler_.isPrivateName(propName)) { // It would be nice if we could tweak this here such that only if // HasHeritage::Yes we end up emitting CheckPrivateField, but otherwise we @@ -8878,36 +8766,30 @@ GeneralParser<ParseHandler, Unit>::fieldInitializerOpt( // -first- field in a derived class, which would suffice to match the // semantic check. - NameNodeType privateNameNode; - MOZ_TRY_VAR(privateNameNode, privateNameReference(propAtom)); + NameNodeType privateNameNode = MOZ_TRY(privateNameReference(propAtom)); - MOZ_TRY_VAR(propAssignFieldAccess, - handler_.newPrivateMemberAccess(propAssignThis, privateNameNode, - wholeInitializerPos.end)); + propAssignFieldAccess = MOZ_TRY(handler_.newPrivateMemberAccess( + propAssignThis, privateNameNode, wholeInitializerPos.end)); } else if (this->parserAtoms().isIndex(propAtom, &indexValue)) { - MOZ_TRY_VAR(propAssignFieldAccess, - handler_.newPropertyByValue(propAssignThis, propName, - wholeInitializerPos.end)); + propAssignFieldAccess = MOZ_TRY(handler_.newPropertyByValue( + propAssignThis, propName, wholeInitializerPos.end)); } else { - NameNodeType propAssignName; - MOZ_TRY_VAR(propAssignName, - handler_.newPropertyName(propAtom, wholeInitializerPos)); + NameNodeType propAssignName = + MOZ_TRY(handler_.newPropertyName(propAtom, wholeInitializerPos)); - MOZ_TRY_VAR(propAssignFieldAccess, - handler_.newPropertyAccess(propAssignThis, propAssignName)); + propAssignFieldAccess = + MOZ_TRY(handler_.newPropertyAccess(propAssignThis, propAssignName)); } // Synthesize an property init. - BinaryNodeType initializerPropInit; - MOZ_TRY_VAR(initializerPropInit, - handler_.newInitExpr(propAssignFieldAccess, initializerExpr)); + BinaryNodeType initializerPropInit = + MOZ_TRY(handler_.newInitExpr(propAssignFieldAccess, initializerExpr)); - UnaryNodeType exprStatement; - MOZ_TRY_VAR(exprStatement, handler_.newExprStatement( - initializerPropInit, wholeInitializerPos.end)); + UnaryNodeType exprStatement = MOZ_TRY( + handler_.newExprStatement(initializerPropInit, wholeInitializerPos.end)); - ListNodeType statementList; - MOZ_TRY_VAR(statementList, handler_.newStatementList(wholeInitializerPos)); + ListNodeType statementList = + MOZ_TRY(handler_.newStatementList(wholeInitializerPos)); handler_.addStatementToList(statementList, exprStatement); bool canSkipLazyClosedOverBindings = handler_.reuseClosedOverBindings(); @@ -8919,10 +8801,8 @@ GeneralParser<ParseHandler, Unit>::fieldInitializerOpt( } // Set the function's body to the field assignment. - LexicalScopeNodeType initializerBody; - MOZ_TRY_VAR(initializerBody, - finishLexicalScope(pc_->varScope(), statementList, - ScopeKind::FunctionLexical)); + LexicalScopeNodeType initializerBody = MOZ_TRY(finishLexicalScope( + pc_->varScope(), statementList, ScopeKind::FunctionLexical)); handler_.setFunctionBody(funNode, initializerBody); @@ -8998,8 +8878,8 @@ GeneralParser<ParseHandler, Unit>::synthesizeAddInitializerFunction( FunctionFlags flags = InitialFunctionFlags(syntaxKind, generatorKind, asyncKind, isSelfHosting); - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, propNamePos)); + FunctionNodeType funNode = + MOZ_TRY(handler_.newFunction(syntaxKind, propNamePos)); Directives directives(true); FunctionBox* funbox = @@ -9018,8 +8898,7 @@ GeneralParser<ParseHandler, Unit>::synthesizeAddInitializerFunction( pc_->functionScope().useAsVarScope(pc_); // Takes a single parameter, `initializer`. - ParamsBodyNodeType params; - MOZ_TRY_VAR(params, handler_.newParamsBody(propNamePos)); + ParamsBodyNodeType params = MOZ_TRY(handler_.newParamsBody(propNamePos)); handler_.setFunctionFormalParametersAndBody(funNode, params); @@ -9041,8 +8920,7 @@ GeneralParser<ParseHandler, Unit>::synthesizeAddInitializerFunction( // with a body of synthesized AST nodes. Instead, the body is left empty and // the initializer is synthesized at the bytecode level. See // DecoratorEmitter::emitCreateAddInitializerFunction. - ListNodeType stmtList; - MOZ_TRY_VAR(stmtList, handler_.newStatementList(propNamePos)); + ListNodeType stmtList = MOZ_TRY(handler_.newStatementList(propNamePos)); if (!noteUsedName(initializers)) { return null(); @@ -9056,10 +8934,8 @@ GeneralParser<ParseHandler, Unit>::synthesizeAddInitializerFunction( return null(); } - LexicalScopeNodeType addInitializerBody; - MOZ_TRY_VAR(addInitializerBody, - finishLexicalScope(pc_->varScope(), stmtList, - ScopeKind::FunctionLexical)); + LexicalScopeNodeType addInitializerBody = MOZ_TRY(finishLexicalScope( + pc_->varScope(), stmtList, ScopeKind::FunctionLexical)); handler_.setBeginPosition(addInitializerBody, stmtList); handler_.setEndPosition(addInitializerBody, stmtList); handler_.setFunctionBody(funNode, addInitializerBody); @@ -9108,9 +8984,9 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessor( mozilla::Maybe<FunctionNodeType> initializerIfPrivate = Nothing(); if (!isStatic && handler_.isPrivateName(propName)) { classInitializedMembers.privateAccessors++; - FunctionNodeType initializerNode; - MOZ_TRY_VAR(initializerNode, synthesizePrivateMethodInitializer( - propAtom, accessorType, propNamePos)); + FunctionNodeType initializerNode = + MOZ_TRY(synthesizePrivateMethodInitializer(propAtom, accessorType, + propNamePos)); initializerIfPrivate = Some(initializerNode); handler_.setPrivateNameKind(propName, PrivateNameKind::GetterSetter); } @@ -9128,10 +9004,8 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessor( TaggedParserAtomIndex funNameAtom = storedMethodName.finishParserAtom(this->parserAtoms(), fc_); - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, - synthesizeAccessorBody(funNameAtom, propNamePos, - privateStateNameAtom, syntaxKind)); + FunctionNodeType funNode = MOZ_TRY(synthesizeAccessorBody( + funNameAtom, propNamePos, privateStateNameAtom, syntaxKind)); // https://arai-a.github.io/ecma262-compare/?pr=2417&id=sec-makeautoaccessorgetter // 3. Perform MakeMethod(getter, homeObject). @@ -9160,8 +9034,8 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessorBody( InitialFunctionFlags(syntaxKind, generatorKind, asyncKind, isSelfHosting); // Create the top-level function node. - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, propNamePos)); + FunctionNodeType funNode = + MOZ_TRY(handler_.newFunction(syntaxKind, propNamePos)); // Create the FunctionBox and link it to the function object. Directives directives(true); @@ -9189,8 +9063,7 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessorBody( setFunctionEndFromCurrentToken(funbox); // Create a ListNode for the parameters + body - ParamsBodyNodeType paramsbody; - MOZ_TRY_VAR(paramsbody, handler_.newParamsBody(propNamePos)); + ParamsBodyNodeType paramsbody = MOZ_TRY(handler_.newParamsBody(propNamePos)); handler_.setFunctionFormalParametersAndBody(funNode, paramsbody); if (syntaxKind == FunctionSyntaxKind::Getter) { @@ -9201,18 +9074,15 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessorBody( // Build `this` expression to access the privateStateName for use in the // operations to create the getter and setter below. - NameNodeType thisName; - MOZ_TRY_VAR(thisName, newThisName()); + NameNodeType thisName = MOZ_TRY(newThisName()); - ThisLiteralType propThis; - MOZ_TRY_VAR(propThis, handler_.newThisLiteral(propNamePos, thisName)); + ThisLiteralType propThis = + MOZ_TRY(handler_.newThisLiteral(propNamePos, thisName)); - NameNodeType privateNameNode; - MOZ_TRY_VAR(privateNameNode, privateNameReference(propNameAtom)); + NameNodeType privateNameNode = MOZ_TRY(privateNameReference(propNameAtom)); - Node propFieldAccess; - MOZ_TRY_VAR(propFieldAccess, handler_.newPrivateMemberAccess( - propThis, privateNameNode, propNamePos.end)); + Node propFieldAccess = MOZ_TRY(handler_.newPrivateMemberAccess( + propThis, privateNameNode, propNamePos.end)); Node accessorBody; if (syntaxKind == FunctionSyntaxKind::Getter) { @@ -9222,8 +9092,8 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessorBody( // captures privateStateName and performs the following steps when called: // 1.a. Let o be the this value. // 1.b. Return ? PrivateGet(privateStateName, o). - MOZ_TRY_VAR(accessorBody, - handler_.newReturnStatement(propFieldAccess, propNamePos)); + accessorBody = + MOZ_TRY(handler_.newReturnStatement(propFieldAccess, propNamePos)); } else { // Decorators Proposal // https://arai-a.github.io/ecma262-compare/?pr=2417&id=sec-makeautoaccessorsetter @@ -9239,25 +9109,20 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessorBody( /* pos = */ 0, false, /* duplicatedParam = */ nullptr); - Node initializerExpr; - MOZ_TRY_VAR(initializerExpr, - handler_.newName(TaggedParserAtomIndex::WellKnown::value(), - propNamePos)); + Node initializerExpr = MOZ_TRY(handler_.newName( + TaggedParserAtomIndex::WellKnown::value(), propNamePos)); // 1.b. Perform ? PrivateSet(privateStateName, o, value). - Node assignment; - MOZ_TRY_VAR(assignment, - handler_.newAssignment(ParseNodeKind::AssignExpr, - propFieldAccess, initializerExpr)); + Node assignment = MOZ_TRY(handler_.newAssignment( + ParseNodeKind::AssignExpr, propFieldAccess, initializerExpr)); - MOZ_TRY_VAR(accessorBody, - handler_.newExprStatement(assignment, propNamePos.end)); + accessorBody = + MOZ_TRY(handler_.newExprStatement(assignment, propNamePos.end)); // 1.c. Return undefined. } - ListNodeType statementList; - MOZ_TRY_VAR(statementList, handler_.newStatementList(propNamePos)); + ListNodeType statementList = MOZ_TRY(handler_.newStatementList(propNamePos)); handler_.addStatementToList(statementList, accessorBody); bool canSkipLazyClosedOverBindings = handler_.reuseClosedOverBindings(); @@ -9268,10 +9133,8 @@ GeneralParser<ParseHandler, Unit>::synthesizeAccessorBody( return errorResult(); } - LexicalScopeNodeType initializerBody; - MOZ_TRY_VAR(initializerBody, - finishLexicalScope(pc_->varScope(), statementList, - ScopeKind::FunctionLexical)); + LexicalScopeNodeType initializerBody = MOZ_TRY(finishLexicalScope( + pc_->varScope(), statementList, ScopeKind::FunctionLexical)); handler_.setFunctionBody(funNode, initializerBody); @@ -9323,8 +9186,8 @@ template <class ParseHandler, typename Unit> typename ParseHandler::DeclarationListNodeResult GeneralParser<ParseHandler, Unit>::variableStatement( YieldHandling yieldHandling) { - DeclarationListNodeType vars; - MOZ_TRY_VAR(vars, declarationList(yieldHandling, ParseNodeKind::VarStmt)); + DeclarationListNodeType vars = + MOZ_TRY(declarationList(yieldHandling, ParseNodeKind::VarStmt)); if (!matchOrInsertSemicolon()) { return errorResult(); } @@ -9862,9 +9725,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::expr( TripledotHandling tripledotHandling, PossibleError* possibleError /* = nullptr */, InvokedPrediction invoked /* = PredictUninvoked */) { - Node pn; - MOZ_TRY_VAR(pn, assignExpr(inHandling, yieldHandling, tripledotHandling, - possibleError, invoked)); + Node pn = MOZ_TRY(assignExpr(inHandling, yieldHandling, tripledotHandling, + possibleError, invoked)); bool matched; if (!tokenStream.matchToken(&matched, TokenKind::Comma, @@ -9875,8 +9737,7 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::expr( return pn; } - ListNodeType seq; - MOZ_TRY_VAR(seq, handler_.newCommaExpressionList(pn)); + ListNodeType seq = MOZ_TRY(handler_.newCommaExpressionList(pn)); while (true) { // Trailing comma before the closing parenthesis is valid in an arrow // function parameters list: `(a, b, ) => body`. Check if we are @@ -9912,8 +9773,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::expr( // information needed to determine whether or not we're dealing with // a non-recoverable situation. PossibleError possibleErrorInner(*this); - MOZ_TRY_VAR(pn, assignExpr(inHandling, yieldHandling, tripledotHandling, - &possibleErrorInner)); + pn = MOZ_TRY(assignExpr(inHandling, yieldHandling, tripledotHandling, + &possibleErrorInner)); if (!possibleError) { // Report any pending expression error. @@ -10011,9 +9872,8 @@ GeneralParser<ParseHandler, Unit>::orExpr(InHandling inHandling, Node pn; EnforcedParentheses unparenthesizedExpression = EnforcedParentheses::None; for (;;) { - MOZ_TRY_VAR( - pn, unaryExpr(yieldHandling, tripledotHandling, possibleError, invoked, - PrivateNameHandling::PrivateNameAllowed)); + pn = MOZ_TRY(unaryExpr(yieldHandling, tripledotHandling, possibleError, + invoked, PrivateNameHandling::PrivateNameAllowed)); // If a binary operator follows, consume it and compute the // corresponding operator. @@ -10120,8 +9980,8 @@ GeneralParser<ParseHandler, Unit>::orExpr(InHandling inHandling, while (depth > 0 && Precedence(kindStack[depth - 1]) >= Precedence(pnk)) { depth--; ParseNodeKind combiningPnk = kindStack[depth]; - MOZ_TRY_VAR(pn, handler_.appendOrCreateList(combiningPnk, - nodeStack[depth], pn, pc_)); + pn = MOZ_TRY( + handler_.appendOrCreateList(combiningPnk, nodeStack[depth], pn, pc_)); } if (pnk == ParseNodeKind::Limit) { @@ -10151,9 +10011,8 @@ GeneralParser<ParseHandler, Unit>::condExpr(InHandling inHandling, TripledotHandling tripledotHandling, PossibleError* possibleError, InvokedPrediction invoked) { - Node condition; - MOZ_TRY_VAR(condition, orExpr(inHandling, yieldHandling, tripledotHandling, - possibleError, invoked)); + Node condition = MOZ_TRY(orExpr(inHandling, yieldHandling, tripledotHandling, + possibleError, invoked)); bool matched; if (!tokenStream.matchToken(&matched, TokenKind::Hook, @@ -10164,17 +10023,15 @@ GeneralParser<ParseHandler, Unit>::condExpr(InHandling inHandling, return condition; } - Node thenExpr; - MOZ_TRY_VAR(thenExpr, - assignExpr(InAllowed, yieldHandling, TripledotProhibited)); + Node thenExpr = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited)); if (!mustMatchToken(TokenKind::Colon, JSMSG_COLON_IN_COND)) { return errorResult(); } - Node elseExpr; - MOZ_TRY_VAR(elseExpr, - assignExpr(inHandling, yieldHandling, TripledotProhibited)); + Node elseExpr = + MOZ_TRY(assignExpr(inHandling, yieldHandling, TripledotProhibited)); return handler_.newConditional(condition, thenExpr, elseExpr); } @@ -10309,11 +10166,11 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::assignExpr( return errorResult(); } - MOZ_TRY_VAR(lhs, identifierReference(asyncName)); + lhs = MOZ_TRY(identifierReference(asyncName)); } } else { - MOZ_TRY_VAR(lhs, condExpr(inHandling, yieldHandling, tripledotHandling, - &possibleErrorInner, invoked)); + lhs = MOZ_TRY(condExpr(inHandling, yieldHandling, tripledotHandling, + &possibleErrorInner, invoked)); // Use SlashIsRegExp here because the ConditionalExpression parsed above // could be the entirety of this AssignmentExpression, and then ASI @@ -10367,8 +10224,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::assignExpr( } FunctionSyntaxKind syntaxKind = FunctionSyntaxKind::Arrow; - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, startPos)); + FunctionNodeType funNode = + MOZ_TRY(handler_.newFunction(syntaxKind, startPos)); return functionDefinition(funNode, toStringStart, inHandling, yieldHandling, TaggedParserAtomIndex::null(), syntaxKind, @@ -10493,8 +10350,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::assignExpr( return errorResult(); } - Node rhs; - MOZ_TRY_VAR(rhs, assignExpr(inHandling, yieldHandling, TripledotProhibited)); + Node rhs = + MOZ_TRY(assignExpr(inHandling, yieldHandling, TripledotProhibited)); return handler_.newAssignment(kind, lhs, rhs); } @@ -10545,8 +10402,7 @@ typename ParseHandler::UnaryNodeResult GeneralParser<ParseHandler, Unit>::unaryOpExpr(YieldHandling yieldHandling, ParseNodeKind kind, uint32_t begin) { - Node kid; - MOZ_TRY_VAR(kid, unaryExpr(yieldHandling, TripledotProhibited)); + Node kid = MOZ_TRY(unaryExpr(yieldHandling, TripledotProhibited)); return handler_.newUnary(kind, begin, kid); } @@ -10563,9 +10419,8 @@ GeneralParser<ParseHandler, Unit>::optionalExpr( uint32_t begin = pos().begin; - Node lhs; - MOZ_TRY_VAR(lhs, - memberExpr(yieldHandling, tripledotHandling, tt, + Node lhs = + MOZ_TRY(memberExpr(yieldHandling, tripledotHandling, tt, /* allowCallSyntax = */ true, possibleError, invoked)); if (!tokenStream.peekToken(&tt, TokenStream::SlashIsDiv)) { @@ -10592,18 +10447,15 @@ GeneralParser<ParseHandler, Unit>::optionalExpr( return errorResult(); } if (TokenKindIsPossibleIdentifierName(tt)) { - MOZ_TRY_VAR(nextMember, - memberPropertyAccess(lhs, OptionalKind::Optional)); + nextMember = MOZ_TRY(memberPropertyAccess(lhs, OptionalKind::Optional)); } else if (tt == TokenKind::PrivateName) { - MOZ_TRY_VAR(nextMember, - memberPrivateAccess(lhs, OptionalKind::Optional)); + nextMember = MOZ_TRY(memberPrivateAccess(lhs, OptionalKind::Optional)); } else if (tt == TokenKind::LeftBracket) { - MOZ_TRY_VAR(nextMember, memberElemAccess(lhs, yieldHandling, - OptionalKind::Optional)); + nextMember = MOZ_TRY( + memberElemAccess(lhs, yieldHandling, OptionalKind::Optional)); } else if (tt == TokenKind::LeftParen) { - MOZ_TRY_VAR(nextMember, - memberCall(tt, lhs, yieldHandling, possibleError, - OptionalKind::Optional)); + nextMember = MOZ_TRY(memberCall(tt, lhs, yieldHandling, possibleError, + OptionalKind::Optional)); } else { error(JSMSG_NAME_AFTER_DOT); return errorResult(); @@ -10613,18 +10465,17 @@ GeneralParser<ParseHandler, Unit>::optionalExpr( return errorResult(); } if (TokenKindIsPossibleIdentifierName(tt)) { - MOZ_TRY_VAR(nextMember, memberPropertyAccess(lhs)); + nextMember = MOZ_TRY(memberPropertyAccess(lhs)); } else if (tt == TokenKind::PrivateName) { - MOZ_TRY_VAR(nextMember, memberPrivateAccess(lhs)); + nextMember = MOZ_TRY(memberPrivateAccess(lhs)); } else { error(JSMSG_NAME_AFTER_DOT); return errorResult(); } } else if (tt == TokenKind::LeftBracket) { - MOZ_TRY_VAR(nextMember, memberElemAccess(lhs, yieldHandling)); + nextMember = MOZ_TRY(memberElemAccess(lhs, yieldHandling)); } else if (tt == TokenKind::LeftParen) { - MOZ_TRY_VAR(nextMember, - memberCall(tt, lhs, yieldHandling, possibleError)); + nextMember = MOZ_TRY(memberCall(tt, lhs, yieldHandling, possibleError)); } else if (tt == TokenKind::TemplateHead || tt == TokenKind::NoSubsTemplate) { error(JSMSG_BAD_OPTIONAL_TEMPLATE); @@ -10681,8 +10532,7 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::unaryExpr( // // Evaluates expression, triggering a runtime ReferenceError for // // the undefined name. // typeof (1, nonExistentName); - Node kid; - MOZ_TRY_VAR(kid, unaryExpr(yieldHandling, TripledotProhibited)); + Node kid = MOZ_TRY(unaryExpr(yieldHandling, TripledotProhibited)); return handler_.newTypeof(begin, kid); } @@ -10695,9 +10545,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::unaryExpr( } uint32_t operandOffset = pos().begin; - Node operand; - MOZ_TRY_VAR(operand, - optionalExpr(yieldHandling, TripledotProhibited, tt2)); + Node operand = + MOZ_TRY(optionalExpr(yieldHandling, TripledotProhibited, tt2)); if (!checkIncDecOperand(operand, operandOffset)) { return errorResult(); } @@ -10721,8 +10570,7 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::unaryExpr( return errorResult(); } - Node expr; - MOZ_TRY_VAR(expr, unaryExpr(yieldHandling, TripledotProhibited)); + Node expr = MOZ_TRY(unaryExpr(yieldHandling, TripledotProhibited)); // Per spec, deleting most unary expressions is valid -- it simply // returns true -- except for two cases: @@ -10759,9 +10607,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::unaryExpr( error(JSMSG_AWAIT_IN_PARAMETER); return errorResult(); } - Node kid; - MOZ_TRY_VAR(kid, unaryExpr(yieldHandling, tripledotHandling, - possibleError, invoked)); + Node kid = MOZ_TRY(unaryExpr(yieldHandling, tripledotHandling, + possibleError, invoked)); pc_->lastAwaitOffset = begin; return handler_.newAwaitExpression(begin, kid); } @@ -10770,9 +10617,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::unaryExpr( [[fallthrough]]; default: { - Node expr; - MOZ_TRY_VAR(expr, optionalExpr(yieldHandling, tripledotHandling, tt, - possibleError, invoked)); + Node expr = MOZ_TRY(optionalExpr(yieldHandling, tripledotHandling, tt, + possibleError, invoked)); /* Don't look across a newline boundary for a postfix incop. */ if (!tokenStream.peekTokenSameLine(&tt)) { @@ -10803,8 +10649,7 @@ GeneralParser<ParseHandler, Unit>::assignExprWithoutYieldOrAwait( uint32_t startYieldOffset = pc_->lastYieldOffset; uint32_t startAwaitOffset = pc_->lastAwaitOffset; - Node res; - MOZ_TRY_VAR(res, assignExpr(InAllowed, yieldHandling, TripledotProhibited)); + Node res = MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited)); if (pc_->lastYieldOffset != startYieldOffset) { errorAt(pc_->lastYieldOffset, JSMSG_YIELD_IN_PARAMETER); @@ -10822,8 +10667,7 @@ typename ParseHandler::ListNodeResult GeneralParser<ParseHandler, Unit>::argumentList( YieldHandling yieldHandling, bool* isSpread, PossibleError* possibleError /* = nullptr */) { - ListNodeType argsList; - MOZ_TRY_VAR(argsList, handler_.newArguments(pos())); + ListNodeType argsList = MOZ_TRY(handler_.newArguments(pos())); bool matched; if (!tokenStream.matchToken(&matched, TokenKind::RightParen, @@ -10848,11 +10692,10 @@ GeneralParser<ParseHandler, Unit>::argumentList( *isSpread = true; } - Node argNode; - MOZ_TRY_VAR(argNode, assignExpr(InAllowed, yieldHandling, - TripledotProhibited, possibleError)); + Node argNode = MOZ_TRY(assignExpr(InAllowed, yieldHandling, + TripledotProhibited, possibleError)); if (spread) { - MOZ_TRY_VAR(argNode, handler_.newSpread(begin, argNode)); + argNode = MOZ_TRY(handler_.newSpread(begin, argNode)); } handler_.addList(argsList, argNode); @@ -10928,9 +10771,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::memberExpr( } else { // Gotten by tryNewTarget tt = anyChars.currentToken().type; - Node ctorExpr; - MOZ_TRY_VAR(ctorExpr, - memberExpr(yieldHandling, TripledotProhibited, tt, + Node ctorExpr = + MOZ_TRY(memberExpr(yieldHandling, TripledotProhibited, tt, /* allowCallSyntax = */ false, /* possibleError = */ nullptr, PredictInvoked)); @@ -10954,27 +10796,26 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::memberExpr( bool isSpread = false; ListNodeType args; if (matched) { - MOZ_TRY_VAR(args, argumentList(yieldHandling, &isSpread)); + args = MOZ_TRY(argumentList(yieldHandling, &isSpread)); } else { - MOZ_TRY_VAR(args, handler_.newArguments(pos())); + args = MOZ_TRY(handler_.newArguments(pos())); } if (!args) { return errorResult(); } - MOZ_TRY_VAR( - lhs, handler_.newNewExpression(newBegin, ctorExpr, args, isSpread)); + lhs = MOZ_TRY( + handler_.newNewExpression(newBegin, ctorExpr, args, isSpread)); } } else if (tt == TokenKind::Super) { - NameNodeType thisName; - MOZ_TRY_VAR(thisName, newThisName()); - MOZ_TRY_VAR(lhs, handler_.newSuperBase(thisName, pos())); + NameNodeType thisName = MOZ_TRY(newThisName()); + lhs = MOZ_TRY(handler_.newSuperBase(thisName, pos())); } else if (tt == TokenKind::Import) { - MOZ_TRY_VAR(lhs, importExpr(yieldHandling, allowCallSyntax)); + lhs = MOZ_TRY(importExpr(yieldHandling, allowCallSyntax)); } else { - MOZ_TRY_VAR(lhs, primaryExpr(yieldHandling, tripledotHandling, tt, - possibleError, invoked)); + lhs = MOZ_TRY(primaryExpr(yieldHandling, tripledotHandling, tt, + possibleError, invoked)); } MOZ_ASSERT_IF(handler_.isSuperBase(lhs), @@ -10996,15 +10837,15 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::memberExpr( } if (TokenKindIsPossibleIdentifierName(tt)) { - MOZ_TRY_VAR(nextMember, memberPropertyAccess(lhs)); + nextMember = MOZ_TRY(memberPropertyAccess(lhs)); } else if (tt == TokenKind::PrivateName) { - MOZ_TRY_VAR(nextMember, memberPrivateAccess(lhs)); + nextMember = MOZ_TRY(memberPrivateAccess(lhs)); } else { error(JSMSG_NAME_AFTER_DOT); return errorResult(); } } else if (tt == TokenKind::LeftBracket) { - MOZ_TRY_VAR(nextMember, memberElemAccess(lhs, yieldHandling)); + nextMember = MOZ_TRY(memberElemAccess(lhs, yieldHandling)); } else if ((allowCallSyntax && tt == TokenKind::LeftParen) || tt == TokenKind::TemplateHead || tt == TokenKind::NoSubsTemplate) { @@ -11019,7 +10860,7 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::memberExpr( return errorResult(); } - MOZ_TRY_VAR(nextMember, memberSuperCall(lhs, yieldHandling)); + nextMember = MOZ_TRY(memberSuperCall(lhs, yieldHandling)); if (!noteUsedName( TaggedParserAtomIndex::WellKnown::dot_initializers_())) { @@ -11032,8 +10873,7 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::memberExpr( } #endif } else { - MOZ_TRY_VAR(nextMember, - memberCall(tt, lhs, yieldHandling, possibleError)); + nextMember = MOZ_TRY(memberCall(tt, lhs, yieldHandling, possibleError)); } } else { anyChars.ungetToken(); @@ -11067,9 +10907,8 @@ GeneralParser<ParseHandler, Unit>::decoratorExpr(YieldHandling yieldHandling, if (tt == TokenKind::LeftParen) { // DecoratorParenthesizedExpression - Node expr; - MOZ_TRY_VAR(expr, exprInParens(InAllowed, yieldHandling, TripledotAllowed, - /* possibleError*/ nullptr)); + Node expr = MOZ_TRY(exprInParens(InAllowed, yieldHandling, TripledotAllowed, + /* possibleError*/ nullptr)); if (!mustMatchToken(TokenKind::RightParen, JSMSG_PAREN_AFTER_DECORATOR)) { return errorResult(); } @@ -11087,8 +10926,7 @@ GeneralParser<ParseHandler, Unit>::decoratorExpr(YieldHandling yieldHandling, return errorResult(); } - Node lhs; - MOZ_TRY_VAR(lhs, identifierReference(name)); + Node lhs = MOZ_TRY(identifierReference(name)); while (true) { if (!tokenStream.getToken(&tt)) { @@ -11106,16 +10944,16 @@ GeneralParser<ParseHandler, Unit>::decoratorExpr(YieldHandling yieldHandling, } if (TokenKindIsPossibleIdentifierName(tt)) { - MOZ_TRY_VAR(nextMember, memberPropertyAccess(lhs)); + nextMember = MOZ_TRY(memberPropertyAccess(lhs)); } else if (tt == TokenKind::PrivateName) { - MOZ_TRY_VAR(nextMember, memberPrivateAccess(lhs)); + nextMember = MOZ_TRY(memberPrivateAccess(lhs)); } else { error(JSMSG_NAME_AFTER_DOT); return errorResult(); } } else if (tt == TokenKind::LeftParen) { - MOZ_TRY_VAR(nextMember, memberCall(tt, lhs, yieldHandling, - /* possibleError */ nullptr)); + nextMember = MOZ_TRY(memberCall(tt, lhs, yieldHandling, + /* possibleError */ nullptr)); lhs = nextMember; // This is a `DecoratorCallExpression` and it's defined at the top level // of `Decorator`, no other `DecoratorMemberExpression` is allowed to @@ -11166,8 +11004,7 @@ GeneralParser<ParseHandler, Unit>::memberPropertyAccess( return errorResult(); } - NameNodeType name; - MOZ_TRY_VAR(name, handler_.newPropertyName(field, pos())); + NameNodeType name = MOZ_TRY(handler_.newPropertyName(field, pos())); if (optionalKind == OptionalKind::Optional) { MOZ_ASSERT(!handler_.isSuperBase(lhs)); @@ -11202,8 +11039,7 @@ GeneralParser<ParseHandler, Unit>::memberPrivateAccess( return errorResult(); } - NameNodeType privateName; - MOZ_TRY_VAR(privateName, privateNameReference(field)); + NameNodeType privateName = MOZ_TRY(privateNameReference(field)); if (optionalKind == OptionalKind::Optional) { MOZ_ASSERT(!handler_.isSuperBase(lhs)); @@ -11218,8 +11054,7 @@ GeneralParser<ParseHandler, Unit>::memberElemAccess( Node lhs, YieldHandling yieldHandling, OptionalKind optionalKind /* = OptionalKind::NonOptional */) { MOZ_ASSERT(anyChars.currentToken().type == TokenKind::LeftBracket); - Node propExpr; - MOZ_TRY_VAR(propExpr, expr(InAllowed, yieldHandling, TripledotProhibited)); + Node propExpr = MOZ_TRY(expr(InAllowed, yieldHandling, TripledotProhibited)); if (!mustMatchToken(TokenKind::RightBracket, JSMSG_BRACKET_IN_INDEX)) { return errorResult(); @@ -11245,19 +11080,16 @@ GeneralParser<ParseHandler, Unit>::memberSuperCall( // generator, we still inherit the yieldHandling of the // memberExpression, per spec. Curious. bool isSpread = false; - ListNodeType args; - MOZ_TRY_VAR(args, argumentList(yieldHandling, &isSpread)); + ListNodeType args = MOZ_TRY(argumentList(yieldHandling, &isSpread)); - CallNodeType superCall; - MOZ_TRY_VAR(superCall, handler_.newSuperCall(lhs, args, isSpread)); + CallNodeType superCall = MOZ_TRY(handler_.newSuperCall(lhs, args, isSpread)); // |super()| implicitly reads |new.target|. if (!noteUsedName(TaggedParserAtomIndex::WellKnown::dot_newTarget_())) { return errorResult(); } - NameNodeType thisName; - MOZ_TRY_VAR(thisName, newThisName()); + NameNodeType thisName = MOZ_TRY(newThisName()); return handler_.newSetThis(thisName, superCall); } @@ -11314,9 +11146,8 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::memberCall( bool isSpread = false; PossibleError* asyncPossibleError = maybeAsyncArrow ? possibleError : nullptr; - ListNodeType args; - MOZ_TRY_VAR(args, - argumentList(yieldHandling, &isSpread, asyncPossibleError)); + ListNodeType args = + MOZ_TRY(argumentList(yieldHandling, &isSpread, asyncPossibleError)); if (isSpread) { if (op == JSOp::Eval) { op = JSOp::SpreadEval; @@ -11333,8 +11164,7 @@ typename ParseHandler::NodeResult GeneralParser<ParseHandler, Unit>::memberCall( return handler_.newCall(lhs, args, op); } - ListNodeType args; - MOZ_TRY_VAR(args, handler_.newArguments(pos())); + ListNodeType args = MOZ_TRY(handler_.newArguments(pos())); if (!taggedTemplate(yieldHandling, args, tt)) { return errorResult(); @@ -11497,8 +11327,7 @@ template <class ParseHandler> typename ParseHandler::NameNodeResult PerHandlerParser<ParseHandler>::identifierReference( TaggedParserAtomIndex name) { - NameNodeType id; - MOZ_TRY_VAR(id, newName(name)); + NameNodeType id = MOZ_TRY(newName(name)); if (!noteUsedName(name)) { return errorResult(); @@ -11511,8 +11340,7 @@ template <class ParseHandler> typename ParseHandler::NameNodeResult PerHandlerParser<ParseHandler>::privateNameReference( TaggedParserAtomIndex name) { - NameNodeType id; - MOZ_TRY_VAR(id, newPrivateName(name)); + NameNodeType id = MOZ_TRY(newPrivateName(name)); if (!noteUsedName(name, NameVisibility::Private, Some(pos()))) { return errorResult(); @@ -11807,8 +11635,7 @@ GeneralParser<ParseHandler, Unit>::arrayInitializer( MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::LeftBracket)); uint32_t begin = pos().begin; - ListNodeType literal; - MOZ_TRY_VAR(literal, handler_.newArrayLiteral(begin)); + ListNodeType literal = MOZ_TRY(handler_.newArrayLiteral(begin)); TokenKind tt; if (!tokenStream.getToken(&tt, TokenStream::SlashIsRegExp)) { @@ -11858,9 +11685,8 @@ GeneralParser<ParseHandler, Unit>::arrayInitializer( } PossibleError possibleErrorInner(*this); - Node inner; - MOZ_TRY_VAR(inner, - assignExpr(InAllowed, yieldHandling, TripledotProhibited, + Node inner = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited, &possibleErrorInner)); if (!checkDestructuringAssignmentTarget( inner, innerPos, &possibleErrorInner, possibleError)) { @@ -11878,9 +11704,8 @@ GeneralParser<ParseHandler, Unit>::arrayInitializer( } PossibleError possibleErrorInner(*this); - Node element; - MOZ_TRY_VAR(element, - assignExpr(InAllowed, yieldHandling, TripledotProhibited, + Node element = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited, &possibleErrorInner)); if (!checkDestructuringAssignmentElement( element, elementPos, &possibleErrorInner, possibleError)) { @@ -11946,8 +11771,7 @@ GeneralParser<ParseHandler, Unit>::propertyName( } case TokenKind::BigInt: { - Node biNode; - MOZ_TRY_VAR(biNode, newBigInt()); + Node biNode = MOZ_TRY(newBigInt()); return handler_.newSyntheticComputedName(biNode, pos().begin, pos().end); } case TokenKind::String: { @@ -12105,9 +11929,8 @@ GeneralParser<ParseHandler, Unit>::propertyOrMethodName( } #endif - Node propName; - MOZ_TRY_VAR(propName, propertyName(yieldHandling, propertyNameContext, - maybeDecl, propList, propAtomOut)); + Node propName = MOZ_TRY(propertyName(yieldHandling, propertyNameContext, + maybeDecl, propList, propAtomOut)); // Grab the next token following the property/method name. // (If this isn't a colon, we're going to either put it back or throw.) @@ -12213,9 +12036,8 @@ GeneralParser<ParseHandler, Unit>::computedPropertyName( handler_.setListHasNonConstInitializer(literal); } - Node assignNode; - MOZ_TRY_VAR(assignNode, - assignExpr(InAllowed, yieldHandling, TripledotProhibited)); + Node assignNode = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited)); if (!mustMatchToken(TokenKind::RightBracket, JSMSG_COMP_PROP_UNTERM_EXPR)) { return errorResult(); @@ -12231,8 +12053,7 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, uint32_t openedPos = pos().begin; - ListNodeType literal; - MOZ_TRY_VAR(literal, handler_.newObjectLiteral(pos().begin)); + ListNodeType literal = MOZ_TRY(handler_.newObjectLiteral(pos().begin)); bool seenPrototypeMutation = false; bool seenCoverInitializedName = false; @@ -12257,9 +12078,8 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, } PossibleError possibleErrorInner(*this); - Node inner; - MOZ_TRY_VAR(inner, assignExpr(InAllowed, yieldHandling, - TripledotProhibited, &possibleErrorInner)); + Node inner = MOZ_TRY(assignExpr( + InAllowed, yieldHandling, TripledotProhibited, &possibleErrorInner)); if (!checkDestructuringAssignmentTarget( inner, innerPos, &possibleErrorInner, possibleError, TargetBehavior::ForbidAssignmentPattern)) { @@ -12272,10 +12092,9 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, TokenPos namePos = anyChars.nextToken().pos; PropertyType propType; - Node propName; - MOZ_TRY_VAR(propName, propertyOrMethodName( - yieldHandling, PropertyNameInLiteral, declKind, - literal, &propType, &propAtom)); + Node propName = MOZ_TRY( + propertyOrMethodName(yieldHandling, PropertyNameInLiteral, declKind, + literal, &propType, &propAtom)); if (propType == PropertyType::Normal) { TokenPos exprPos; @@ -12284,9 +12103,8 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, } PossibleError possibleErrorInner(*this); - Node propExpr; - MOZ_TRY_VAR(propExpr, - assignExpr(InAllowed, yieldHandling, TripledotProhibited, + Node propExpr = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited, &possibleErrorInner)); if (!checkDestructuringAssignmentElement( @@ -12320,9 +12138,8 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, return errorResult(); } } else { - BinaryNodeType propDef; - MOZ_TRY_VAR(propDef, - handler_.newPropertyDefinition(propName, propExpr)); + BinaryNodeType propDef = + MOZ_TRY(handler_.newPropertyDefinition(propName, propExpr)); handler_.addPropertyDefinition(literal, propDef); } @@ -12337,8 +12154,7 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, return errorResult(); } - NameNodeType nameExpr; - MOZ_TRY_VAR(nameExpr, identifierReference(name)); + NameNodeType nameExpr = MOZ_TRY(identifierReference(name)); if (possibleError) { checkDestructuringAssignmentName(nameExpr, namePos, possibleError); @@ -12358,8 +12174,7 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, return errorResult(); } - Node lhs; - MOZ_TRY_VAR(lhs, identifierReference(name)); + Node lhs = MOZ_TRY(identifierReference(name)); tokenStream.consumeKnownToken(TokenKind::Assign); @@ -12398,13 +12213,11 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, pc_->sc()->setIneligibleForArgumentsLength(); } - Node rhs; - MOZ_TRY_VAR(rhs, - assignExpr(InAllowed, yieldHandling, TripledotProhibited)); + Node rhs = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited)); - BinaryNodeType propExpr; - MOZ_TRY_VAR(propExpr, handler_.newAssignment(ParseNodeKind::AssignExpr, - lhs, rhs)); + BinaryNodeType propExpr = MOZ_TRY( + handler_.newAssignment(ParseNodeKind::AssignExpr, lhs, rhs)); if (!handler_.addPropertyDefinition(literal, propName, propExpr)) { return errorResult(); @@ -12425,9 +12238,8 @@ GeneralParser<ParseHandler, Unit>::objectLiteral(YieldHandling yieldHandling, } } - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, - methodDefinition(namePos.begin, propType, funName)); + FunctionNodeType funNode = + MOZ_TRY(methodDefinition(namePos.begin, propType, funName)); AccessorType atype = ToAccessorType(propType); if (!handler_.addObjectMethodDefinition(literal, propName, funNode, @@ -12514,8 +12326,7 @@ GeneralParser<ParseHandler, Unit>::methodDefinition( YieldHandling yieldHandling = GetYieldHandling(generatorKind); - FunctionNodeType funNode; - MOZ_TRY_VAR(funNode, handler_.newFunction(syntaxKind, pos())); + FunctionNodeType funNode = MOZ_TRY(handler_.newFunction(syntaxKind, pos())); return functionDefinition(funNode, toStringStart, InAllowed, yieldHandling, funName, syntaxKind, generatorKind, asyncKind); @@ -12578,8 +12389,7 @@ GeneralParser<ParseHandler, Unit>::importExpr(YieldHandling yieldHandling, bool allowCallSyntax) { MOZ_ASSERT(anyChars.isCurrentTokenType(TokenKind::Import)); - NullaryNodeType importHolder; - MOZ_TRY_VAR(importHolder, handler_.newPosHolder(pos())); + NullaryNodeType importHolder = MOZ_TRY(handler_.newPosHolder(pos())); TokenKind next; if (!tokenStream.getToken(&next)) { @@ -12600,15 +12410,14 @@ GeneralParser<ParseHandler, Unit>::importExpr(YieldHandling yieldHandling, return errorResult(); } - NullaryNodeType metaHolder; - MOZ_TRY_VAR(metaHolder, handler_.newPosHolder(pos())); + NullaryNodeType metaHolder = MOZ_TRY(handler_.newPosHolder(pos())); return handler_.newImportMeta(importHolder, metaHolder); } if (next == TokenKind::LeftParen && allowCallSyntax) { - Node arg; - MOZ_TRY_VAR(arg, assignExpr(InAllowed, yieldHandling, TripledotProhibited)); + Node arg = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited)); if (!tokenStream.peekToken(&next, TokenStream::SlashIsRegExp)) { return errorResult(); @@ -12624,8 +12433,8 @@ GeneralParser<ParseHandler, Unit>::importExpr(YieldHandling yieldHandling, } if (next != TokenKind::RightParen) { - MOZ_TRY_VAR(optionalArg, - assignExpr(InAllowed, yieldHandling, TripledotProhibited)); + optionalArg = + MOZ_TRY(assignExpr(InAllowed, yieldHandling, TripledotProhibited)); if (!tokenStream.peekToken(&next, TokenStream::SlashIsRegExp)) { return errorResult(); @@ -12636,20 +12445,19 @@ GeneralParser<ParseHandler, Unit>::importExpr(YieldHandling yieldHandling, TokenStream::SlashIsRegExp); } } else { - MOZ_TRY_VAR(optionalArg, - handler_.newPosHolder(TokenPos(pos().end, pos().end))); + optionalArg = + MOZ_TRY(handler_.newPosHolder(TokenPos(pos().end, pos().end))); } } else { - MOZ_TRY_VAR(optionalArg, - handler_.newPosHolder(TokenPos(pos().end, pos().end))); + optionalArg = + MOZ_TRY(handler_.newPosHolder(TokenPos(pos().end, pos().end))); } if (!mustMatchToken(TokenKind::RightParen, JSMSG_PAREN_AFTER_ARGS)) { return errorResult(); } - Node spec; - MOZ_TRY_VAR(spec, handler_.newCallImportSpec(arg, optionalArg)); + Node spec = MOZ_TRY(handler_.newCallImportSpec(arg, optionalArg)); return handler_.newCallImport(importHolder, spec); } @@ -12716,9 +12524,8 @@ GeneralParser<ParseHandler, Unit>::primaryExpr( } // Pass |possibleError| to support destructuring in arrow parameters. - Node expr; - MOZ_TRY_VAR(expr, exprInParens(InAllowed, yieldHandling, TripledotAllowed, - possibleError)); + Node expr = MOZ_TRY(exprInParens(InAllowed, yieldHandling, + TripledotAllowed, possibleError)); if (!mustMatchToken(TokenKind::RightParen, JSMSG_PAREN_IN_PAREN)) { return errorResult(); } @@ -12778,7 +12585,7 @@ GeneralParser<ParseHandler, Unit>::primaryExpr( case TokenKind::This: { NameNodeType thisName = null(); if (pc_->sc()->hasFunctionThisBinding()) { - MOZ_TRY_VAR(thisName, newThisName()); + thisName = MOZ_TRY(newThisName()); } return handler_.newThisLiteral(pos(), thisName); } diff --git a/js/src/jit/WarpOracle.cpp b/js/src/jit/WarpOracle.cpp @@ -160,8 +160,8 @@ AbortReasonOr<WarpSnapshot*> WarpOracle::createSnapshot() { WarpScriptOracle scriptOracle(cx_, this, outerScript_, &mirGen_.outerInfo(), icScript); - WarpScriptSnapshot* scriptSnapshot; - MOZ_TRY_VAR(scriptSnapshot, scriptOracle.createScriptSnapshot()); + WarpScriptSnapshot* scriptSnapshot = + MOZ_TRY(scriptOracle.createScriptSnapshot()); // Insert the outermost scriptSnapshot at the front of the list. scriptSnapshots_.insertFront(scriptSnapshot); @@ -1082,9 +1082,7 @@ AbortReasonOr<Ok> WarpScriptOracle::maybeInlineIC(WarpOpSnapshotList& snapshots, // and their relative frequency. if (ICSupportsPolymorphicTypeData(loc.getOp()) && fallbackStub->enteredCount() == 0) { - bool inlinedPolymorphicTypes = false; - MOZ_TRY_VAR( - inlinedPolymorphicTypes, + bool inlinedPolymorphicTypes = MOZ_TRY( maybeInlinePolymorphicTypes(snapshots, loc, stub, fallbackStub)); if (inlinedPolymorphicTypes) { return Ok(); @@ -1251,9 +1249,8 @@ AbortReasonOr<Ok> WarpScriptOracle::maybeInlineIC(WarpOpSnapshotList& snapshots, if (fallbackStub->trialInliningState() == TrialInliningState::Inlined || fallbackStub->trialInliningState() == TrialInliningState::MonomorphicInlined) { - bool inlinedCall; - MOZ_TRY_VAR(inlinedCall, maybeInlineCall(snapshots, loc, stub, fallbackStub, - stubDataCopy)); + bool inlinedCall = MOZ_TRY( + maybeInlineCall(snapshots, loc, stub, fallbackStub, stubDataCopy)); if (inlinedCall) { return Ok(); } diff --git a/js/src/vm/BigIntType.cpp b/js/src/vm/BigIntType.cpp @@ -3655,8 +3655,7 @@ bool BigInt::equal(const BigInt* lhs, double rhs) { JS::Result<bool> BigInt::equal(JSContext* cx, Handle<BigInt*> lhs, HandleString rhs) { - BigInt* rhsBigInt; - MOZ_TRY_VAR(rhsBigInt, StringToBigInt(cx, rhs)); + BigInt* rhsBigInt = MOZ_TRY(StringToBigInt(cx, rhs)); if (!rhsBigInt) { return false; } diff --git a/js/src/vm/JSContext.h b/js/src/vm/JSContext.h @@ -1238,7 +1238,7 @@ inline BufferHolder<T>::BufferHolder(JSContext* cx, T* buffer) * * ## Checking Results when your return type is not Result * - * This header defines alternatives to MOZ_TRY and MOZ_TRY_VAR for when you + * This header defines alternatives to MOZ_TRY for when you * need to call a `Result` function from a function that uses false or nullptr * to indicate errors: * diff --git a/js/xpconnect/loader/ScriptPreloader.cpp b/js/xpconnect/loader/ScriptPreloader.cpp @@ -426,8 +426,7 @@ Result<Ok, nsresult> ScriptPreloader::OpenCache() { MOZ_TRY(NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(mProfD))); - nsCOMPtr<nsIFile> cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(u".bin"_ns)); + nsCOMPtr<nsIFile> cacheFile = MOZ_TRY(GetCacheFile(u".bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); @@ -706,8 +705,7 @@ Result<Ok, nsresult> ScriptPreloader::WriteCache() { return Ok(); } - nsCOMPtr<nsIFile> cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(u"-new.bin"_ns)); + nsCOMPtr<nsIFile> cacheFile = MOZ_TRY(GetCacheFile(u"-new.bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); diff --git a/js/xpconnect/loader/URLPreloader.cpp b/js/xpconnect/loader/URLPreloader.cpp @@ -176,8 +176,7 @@ Result<nsCOMPtr<nsIFile>, nsresult> URLPreloader::FindCacheFile() { return Err(NS_ERROR_ABORT); } - nsCOMPtr<nsIFile> cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(u".bin"_ns)); + nsCOMPtr<nsIFile> cacheFile = MOZ_TRY(GetCacheFile(u".bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); @@ -212,8 +211,7 @@ Result<Ok, nsresult> URLPreloader::WriteCache() { LOG(Debug, "Writing cache..."); - nsCOMPtr<nsIFile> cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(u"-new.bin"_ns)); + nsCOMPtr<nsIFile> cacheFile = MOZ_TRY(GetCacheFile(u"-new.bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); @@ -267,8 +265,7 @@ Result<Ok, nsresult> URLPreloader::ReadCache( LinkedList<URLEntry>& pendingURLs) { LOG(Debug, "Reading cache..."); - nsCOMPtr<nsIFile> cacheFile; - MOZ_TRY_VAR(cacheFile, FindCacheFile()); + nsCOMPtr<nsIFile> cacheFile = MOZ_TRY(FindCacheFile()); AutoMemMap cache; MOZ_TRY(cache.init(cacheFile)); @@ -500,8 +497,7 @@ Result<nsCString, nsresult> URLPreloader::ReadInternal(const CacheKey& key, Result<nsCString, nsresult> URLPreloader::ReadURIInternal(nsIURI* uri, ReadType readType) { - CacheKey key; - MOZ_TRY_VAR(key, ResolveURI(uri)); + CacheKey key = MOZ_TRY(ResolveURI(uri)); return ReadInternal(key, readType); } @@ -640,10 +636,9 @@ Result<FileLocation, nsresult> URLPreloader::CacheKey::ToFileLocation() { } Result<nsCString, nsresult> URLPreloader::URLEntry::Read() { - FileLocation location; - MOZ_TRY_VAR(location, ToFileLocation()); + FileLocation location = MOZ_TRY(ToFileLocation()); - MOZ_TRY_VAR(mData, ReadLocation(location)); + mData = MOZ_TRY(ReadLocation(location)); return mData; } diff --git a/js/xpconnect/loader/mozJSModuleLoader.cpp b/js/xpconnect/loader/mozJSModuleLoader.cpp @@ -842,8 +842,7 @@ nsresult mozJSModuleLoader::GetScriptForLocation( stencil = CompileModuleScriptToStencil(aCx, options, srcBuf); } } else { - nsCString str; - MOZ_TRY_VAR(str, ReadScript(aInfo)); + nsCString str = MOZ_TRY(ReadScript(aInfo)); JS::SourceText<mozilla::Utf8Unit> srcBuf; if (srcBuf.init(aCx, str.get(), str.Length(), diff --git a/js/xpconnect/src/XPCComponents.cpp b/js/xpconnect/src/XPCComponents.cpp @@ -2348,7 +2348,7 @@ NS_IMETHODIMP nsXPCComponents_Utils::ReadUTF8File(nsIFile* aFile, nsACString& aResult) { NS_ENSURE_TRUE(aFile, NS_ERROR_INVALID_ARG); - MOZ_TRY_VAR(aResult, URLPreloader::ReadFile(aFile)); + aResult = MOZ_TRY(URLPreloader::ReadFile(aFile)); return NS_OK; } @@ -2356,7 +2356,7 @@ NS_IMETHODIMP nsXPCComponents_Utils::ReadUTF8URI(nsIURI* aURI, nsACString& aResult) { NS_ENSURE_TRUE(aURI, NS_ERROR_INVALID_ARG); - MOZ_TRY_VAR(aResult, URLPreloader::ReadURI(aURI)); + aResult = MOZ_TRY(URLPreloader::ReadURI(aURI)); return NS_OK; } diff --git a/layout/generic/nsIFrame.cpp b/layout/generic/nsIFrame.cpp @@ -10425,9 +10425,7 @@ nsIFrame::SelectablePeekReport nsIFrame::GetFrameFromDirection( return result; } - bool atLineEdge; - MOZ_TRY_VAR( - atLineEdge, + bool atLineEdge = MOZ_TRY( needsVisualTraversal ? traversedFrame->IsVisuallyAtLineEdge(it, thisLine, aDirection) : traversedFrame->IsLogicallyAtLineEdge(it, thisLine, aDirection)); diff --git a/layout/style/PreloadedStyleSheet.cpp b/layout/style/PreloadedStyleSheet.cpp @@ -34,9 +34,8 @@ Result<StyleSheet*, nsresult> PreloadedStyleSheet::GetSheet() { if (!mSheet) { auto loader = MakeRefPtr<css::Loader>(); - MOZ_TRY_VAR(mSheet, - loader->LoadSheetSync(mURI, mParsingMode, - css::Loader::UseSystemPrincipal::Yes)); + mSheet = MOZ_TRY(loader->LoadSheetSync( + mURI, mParsingMode, css::Loader::UseSystemPrincipal::Yes)); } return {mSheet.get()}; } diff --git a/layout/xul/tree/nsTreeBodyFrame.cpp b/layout/xul/tree/nsTreeBodyFrame.cpp @@ -1569,9 +1569,8 @@ nsresult nsTreeBodyFrame::CreateTimer(const LookAndFeel::IntID aID, // Create a new timer only if the delay is greater than zero. // Zero value means that this feature is completely disabled. if (delay > 0) { - MOZ_TRY_VAR(timer, - NS_NewTimerWithFuncCallback(aFunc, this, delay, aType, aName, - GetMainThreadSerialEventTarget())); + timer = MOZ_TRY(NS_NewTimerWithFuncCallback( + aFunc, this, delay, aType, aName, GetMainThreadSerialEventTarget())); } timer.forget(aTimer); diff --git a/mfbt/Try.h b/mfbt/Try.h @@ -34,14 +34,5 @@ } \ mozTryVarTempResult.unwrap(); \ }) -/** - * MOZ_TRY_VAR(target, expr) is the C++ equivalent of Rust's `target = - * try!(expr);`. First, it evaluates expr, which must produce a Result value. On - * success, the result's success value is assigned to target. On error, - * immediately returns the error result. |target| must be an lvalue. - * - * This macro is obsolete and its usages should be replaced with `MOZ_TRY`. - */ -#define MOZ_TRY_VAR(target, expr) (target) = MOZ_TRY(expr); #endif // mozilla_Try_h diff --git a/mfbt/tests/TestResult.cpp b/mfbt/tests/TestResult.cpp @@ -146,13 +146,6 @@ static constexpr Result<int, TestUnusedZeroEnum> Task2UnusedZeroEnumErr( } static Result<int, Failed> Task3(bool pass1, bool pass2, int value) { - int x, y; - MOZ_TRY_VAR(x, Task2(pass1, value)); - MOZ_TRY_VAR(y, Task2(pass2, value)); - return x + y; -} - -static Result<int, Failed> Task4(bool pass1, bool pass2, int value) { auto x = MOZ_TRY(Task2(pass1, value)); auto y = MOZ_TRY(Task2(pass2, value)); return x + y; @@ -187,13 +180,6 @@ static void BasicTests() { MOZ_RELEASE_ASSERT(Task2UnusedZeroEnumErr(false, 3).isErr()); MOZ_RELEASE_ASSERT(Task2UnusedZeroEnumErr(false, 3).unwrapOr(6) == 6); - MOZ_RELEASE_ASSERT(Task4(true, true, 3).isOk()); - MOZ_RELEASE_ASSERT(Task4(true, true, 3).unwrap() == 6); - MOZ_RELEASE_ASSERT(Task4(true, false, 3).isErr()); - MOZ_RELEASE_ASSERT(Task4(false, true, 3).isErr()); - MOZ_RELEASE_ASSERT(Task4(false, true, 3).unwrapOr(6) == 6); - - // MOZ_TRY_VAR works. MOZ_RELEASE_ASSERT(Task3(true, true, 3).isOk()); MOZ_RELEASE_ASSERT(Task3(true, true, 3).unwrap() == 6); MOZ_RELEASE_ASSERT(Task3(true, false, 3).isErr()); diff --git a/modules/libpref/Preferences.cpp b/modules/libpref/Preferences.cpp @@ -1274,16 +1274,14 @@ class MOZ_STACK_CLASS PrefWrapper : public PrefWrapperBase { } nsresult GetValue(PrefValueKind aKind, bool* aResult) const { - PrefValueKind kind; - MOZ_TRY_VAR(kind, WantValueKind(PrefType::Bool, aKind)); + PrefValueKind kind = MOZ_TRY(WantValueKind(PrefType::Bool, aKind)); *aResult = GetBoolValue(kind); return NS_OK; } nsresult GetValue(PrefValueKind aKind, int32_t* aResult) const { - PrefValueKind kind; - MOZ_TRY_VAR(kind, WantValueKind(PrefType::Int, aKind)); + PrefValueKind kind = MOZ_TRY(WantValueKind(PrefType::Int, aKind)); *aResult = GetIntValue(kind); return NS_OK; @@ -1305,8 +1303,7 @@ class MOZ_STACK_CLASS PrefWrapper : public PrefWrapperBase { } nsresult GetValue(PrefValueKind aKind, nsACString& aResult) const { - PrefValueKind kind; - MOZ_TRY_VAR(kind, WantValueKind(PrefType::String, aKind)); + PrefValueKind kind = MOZ_TRY(WantValueKind(PrefType::String, aKind)); aResult = GetStringValue(kind); return NS_OK; @@ -4750,8 +4747,7 @@ nsresult Preferences::WritePrefFile( static nsresult openPrefFile(nsIFile* aFile, PrefValueKind aKind) { MOZ_ASSERT(XRE_IsParentProcess()); - nsCString data; - MOZ_TRY_VAR(data, URLPreloader::ReadFile(aFile)); + nsCString data = MOZ_TRY(URLPreloader::ReadFile(aFile)); nsAutoString filenameUtf16; aFile->GetLeafName(filenameUtf16); @@ -4851,9 +4847,8 @@ static nsresult pref_LoadPrefsInDir(nsIFile* aDir) { static nsresult pref_ReadPrefFromJar(nsZipArchive* aJarReader, const char* aName) { - nsCString manifest; - MOZ_TRY_VAR(manifest, - URLPreloader::ReadZip(aJarReader, nsDependentCString(aName))); + nsCString manifest = + MOZ_TRY(URLPreloader::ReadZip(aJarReader, nsDependentCString(aName))); Parser parser; if (!parser.Parse(PrefValueKind::Default, aName, manifest)) { @@ -5431,11 +5426,8 @@ nsresult Preferences::Lock(const char* aPrefName) { ENSURE_PARENT_PROCESS("Lock", aPrefName); NS_ENSURE_TRUE(InitStaticMembers(), NS_ERROR_NOT_AVAILABLE); - Pref* pref; - MOZ_TRY_VAR(pref, - pref_LookupForModify(aPrefName, [](const PrefWrapper& aPref) { - return !aPref.IsLocked(); - })); + Pref* pref = MOZ_TRY(pref_LookupForModify( + aPrefName, [](const PrefWrapper& aPref) { return !aPref.IsLocked(); })); if (pref) { pref->SetIsLocked(true); @@ -5450,11 +5442,8 @@ nsresult Preferences::Unlock(const char* aPrefName) { ENSURE_PARENT_PROCESS("Unlock", aPrefName); NS_ENSURE_TRUE(InitStaticMembers(), NS_ERROR_NOT_AVAILABLE); - Pref* pref; - MOZ_TRY_VAR(pref, - pref_LookupForModify(aPrefName, [](const PrefWrapper& aPref) { - return aPref.IsLocked(); - })); + Pref* pref = MOZ_TRY(pref_LookupForModify( + aPrefName, [](const PrefWrapper& aPref) { return aPref.IsLocked(); })); if (pref) { pref->SetIsLocked(false); diff --git a/mozglue/android/APKOpen.cpp b/mozglue/android/APKOpen.cpp @@ -190,8 +190,7 @@ static LoadGeckoLibsResult loadGeckoLibs() { getrusage(RUSAGE_SELF, &usage1); static const char* libxul = getenv("MOZ_ANDROID_LIBDIR_OVERRIDE"); - MOZ_TRY_VAR( - gBootstrap, + gBootstrap = MOZ_TRY( GetBootstrap(libxul ? libxul : getUnpackedLibraryName("libxul.so").get(), LibLoadingStrategy::ReadAhead)); diff --git a/mozglue/misc/PreXULSkeletonUI.cpp b/mozglue/misc/PreXULSkeletonUI.cpp @@ -274,8 +274,7 @@ static Result<Ok, PreXULSkeletonUIError> GetSkeletonUILock() { // get quite the same robustness that `GetInstallHash` might provide, but // we already don't have that with how we key our registry values, so it // probably makes sense to just match those. - UniquePtr<wchar_t[]> binPath; - MOZ_TRY_VAR(binPath, GetBinaryPath()); + UniquePtr<wchar_t[]> binPath = MOZ_TRY(GetBinaryPath()); // Lowercase the binpath to match how we look for remote instances. MutateStringToLowercase(binPath.get()); @@ -1716,8 +1715,7 @@ static Result<uint32_t, PreXULSkeletonUIError> ReadRegUint( static Result<bool, PreXULSkeletonUIError> ReadRegBool( HKEY regKey, const std::wstring& valueName) { - uint32_t value; - MOZ_TRY_VAR(value, ReadRegUint(regKey, valueName)); + uint32_t value = MOZ_TRY(ReadRegUint(regKey, valueName)); return !!value; } @@ -1800,12 +1798,10 @@ static Result<Ok, PreXULSkeletonUIError> CreateAndStorePreXULSkeletonUIImpl( const TimeStamp skeletonStart = TimeStamp::Now(); - HKEY regKey; - MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey()); + HKEY regKey = MOZ_TRY(OpenPreXULSkeletonUIRegKey()); AutoCloseRegKey closeKey(regKey); - UniquePtr<wchar_t[]> binPath; - MOZ_TRY_VAR(binPath, GetBinaryPath()); + UniquePtr<wchar_t[]> binPath = MOZ_TRY(GetBinaryPath()); std::wstring regProgressName = GetRegValueName(binPath.get(), sProgressSuffix); @@ -1868,48 +1864,32 @@ static Result<Ok, PreXULSkeletonUIError> CreateAndStorePreXULSkeletonUIImpl( return Err(PreXULSkeletonUIError::FailedRegisteringWindowClass); } - uint32_t screenX; - MOZ_TRY_VAR(screenX, ReadRegUint(regKey, GetRegValueName(binPath.get(), - sScreenXRegSuffix))); - uint32_t screenY; - MOZ_TRY_VAR(screenY, ReadRegUint(regKey, GetRegValueName(binPath.get(), - sScreenYRegSuffix))); - uint32_t windowWidth; - MOZ_TRY_VAR( - windowWidth, + uint32_t screenX = MOZ_TRY( + ReadRegUint(regKey, GetRegValueName(binPath.get(), sScreenXRegSuffix))); + uint32_t screenY = MOZ_TRY( + ReadRegUint(regKey, GetRegValueName(binPath.get(), sScreenYRegSuffix))); + uint32_t windowWidth = MOZ_TRY( ReadRegUint(regKey, GetRegValueName(binPath.get(), sWidthRegSuffix))); - uint32_t windowHeight; - MOZ_TRY_VAR( - windowHeight, + uint32_t windowHeight = MOZ_TRY( ReadRegUint(regKey, GetRegValueName(binPath.get(), sHeightRegSuffix))); - MOZ_TRY_VAR( - sMaximized, + sMaximized = MOZ_TRY( ReadRegBool(regKey, GetRegValueName(binPath.get(), sMaximizedRegSuffix))); - MOZ_TRY_VAR( - sCSSToDevPixelScaling, - ReadRegDouble(regKey, GetRegValueName(binPath.get(), - sCssToDevPixelScalingRegSuffix))); - Vector<CSSPixelSpan> urlbar; - MOZ_TRY_VAR(urlbar, - ReadRegCSSPixelSpans( - regKey, GetRegValueName(binPath.get(), sUrlbarCSSRegSuffix))); - Vector<CSSPixelSpan> searchbar; - MOZ_TRY_VAR(searchbar, - ReadRegCSSPixelSpans( - regKey, GetRegValueName(binPath.get(), sSearchbarRegSuffix))); - Vector<CSSPixelSpan> springs; - MOZ_TRY_VAR(springs, ReadRegCSSPixelSpans( - regKey, GetRegValueName(binPath.get(), - sSpringsCSSRegSuffix))); + sCSSToDevPixelScaling = MOZ_TRY(ReadRegDouble( + regKey, GetRegValueName(binPath.get(), sCssToDevPixelScalingRegSuffix))); + Vector<CSSPixelSpan> urlbar = MOZ_TRY(ReadRegCSSPixelSpans( + regKey, GetRegValueName(binPath.get(), sUrlbarCSSRegSuffix))); + Vector<CSSPixelSpan> searchbar = MOZ_TRY(ReadRegCSSPixelSpans( + regKey, GetRegValueName(binPath.get(), sSearchbarRegSuffix))); + Vector<CSSPixelSpan> springs = MOZ_TRY(ReadRegCSSPixelSpans( + regKey, GetRegValueName(binPath.get(), sSpringsCSSRegSuffix))); if (urlbar.empty() || searchbar.empty()) { return Err(PreXULSkeletonUIError::CorruptData); } EnumSet<SkeletonUIFlag, uint32_t> flags; - uint32_t flagsUint; - MOZ_TRY_VAR(flagsUint, ReadRegUint(regKey, GetRegValueName(binPath.get(), - sFlagsRegSuffix))); + uint32_t flagsUint = MOZ_TRY( + ReadRegUint(regKey, GetRegValueName(binPath.get(), sFlagsRegSuffix))); flags.deserialize(flagsUint); if (flags.contains(SkeletonUIFlag::TouchDensity) || @@ -1917,9 +1897,8 @@ static Result<Ok, PreXULSkeletonUIError> CreateAndStorePreXULSkeletonUIImpl( return Err(PreXULSkeletonUIError::BadUIDensity); } - uint32_t theme; - MOZ_TRY_VAR(theme, ReadRegUint(regKey, GetRegValueName(binPath.get(), - sThemeRegSuffix))); + uint32_t theme = MOZ_TRY( + ReadRegUint(regKey, GetRegValueName(binPath.get(), sThemeRegSuffix))); ThemeMode themeMode = static_cast<ThemeMode>(theme); if (themeMode == ThemeMode::Default) { if (IsSystemDarkThemeEnabled()) { @@ -2096,12 +2075,10 @@ Result<Ok, PreXULSkeletonUIError> PersistPreXULSkeletonUIValues( return Err(PreXULSkeletonUIError::Disabled); } - HKEY regKey; - MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey()); + HKEY regKey = MOZ_TRY(OpenPreXULSkeletonUIRegKey()); AutoCloseRegKey closeKey(regKey); - UniquePtr<wchar_t[]> binPath; - MOZ_TRY_VAR(binPath, GetBinaryPath()); + UniquePtr<wchar_t[]> binPath = MOZ_TRY(GetBinaryPath()); MOZ_TRY(WriteRegUint(regKey, GetRegValueName(binPath.get(), sScreenXRegSuffix), @@ -2176,12 +2153,10 @@ MFBT_API Result<Ok, PreXULSkeletonUIError> SetPreXULSkeletonUIEnabledIfAllowed( return Err(PreXULSkeletonUIError::Disabled); } - HKEY regKey; - MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey()); + HKEY regKey = MOZ_TRY(OpenPreXULSkeletonUIRegKey()); AutoCloseRegKey closeKey(regKey); - UniquePtr<wchar_t[]> binPath; - MOZ_TRY_VAR(binPath, GetBinaryPath()); + UniquePtr<wchar_t[]> binPath = MOZ_TRY(GetBinaryPath()); MOZ_TRY(WriteRegBool( regKey, GetRegValueName(binPath.get(), sEnabledRegSuffix), value)); @@ -2208,12 +2183,10 @@ MFBT_API Result<Ok, PreXULSkeletonUIError> SetPreXULSkeletonUIThemeId( // If we fail below, invalidate sTheme auto invalidateTheme = MakeScopeExit([] { sTheme = ThemeMode::Invalid; }); - HKEY regKey; - MOZ_TRY_VAR(regKey, OpenPreXULSkeletonUIRegKey()); + HKEY regKey = MOZ_TRY(OpenPreXULSkeletonUIRegKey()); AutoCloseRegKey closeKey(regKey); - UniquePtr<wchar_t[]> binPath; - MOZ_TRY_VAR(binPath, GetBinaryPath()); + UniquePtr<wchar_t[]> binPath = MOZ_TRY(GetBinaryPath()); MOZ_TRY(WriteRegUint(regKey, GetRegValueName(binPath.get(), sThemeRegSuffix), static_cast<uint32_t>(theme))); diff --git a/netwerk/base/SimpleChannel.cpp b/netwerk/base/SimpleChannel.cpp @@ -33,8 +33,8 @@ nsresult SimpleChannel::OpenContentStream(bool async, nsIChannel** channel) { NS_ENSURE_TRUE(mCallbacks, NS_ERROR_UNEXPECTED); - nsCOMPtr<nsIInputStream> stream; - MOZ_TRY_VAR(stream, mCallbacks->OpenContentStream(async, this)); + nsCOMPtr<nsIInputStream> stream = + MOZ_TRY(mCallbacks->OpenContentStream(async, this)); MOZ_ASSERT(stream); mCallbacks = nullptr; diff --git a/netwerk/protocol/res/ExtensionProtocolHandler.cpp b/netwerk/protocol/res/ExtensionProtocolHandler.cpp @@ -603,8 +603,7 @@ Result<bool, nsresult> ExtensionProtocolHandler::AllowExternalResource( // allow loading. Before we allow an unpacked extension to load a // resource outside of the extension dir, we make sure the extension // dir is within the app directory. - bool result; - MOZ_TRY_VAR(result, AppDirContains(aExtensionDir)); + bool result = MOZ_TRY(AppDirContains(aExtensionDir)); if (!result) { return false; } @@ -784,18 +783,16 @@ Result<nsCOMPtr<nsIInputStream>, nsresult> ExtensionProtocolHandler::NewStream( bool isResourceFromExtensionDir = false; MOZ_TRY(extensionDir->Contains(requestedFile, &isResourceFromExtensionDir)); if (!isResourceFromExtensionDir) { - bool isAllowed; - MOZ_TRY_VAR(isAllowed, AllowExternalResource(extensionDir, requestedFile)); + bool isAllowed = + MOZ_TRY(AllowExternalResource(extensionDir, requestedFile)); if (!isAllowed) { LogExternalResourceError(extensionDir, requestedFile); return Err(NS_ERROR_FILE_ACCESS_DENIED); } } - nsCOMPtr<nsIInputStream> inputStream; - MOZ_TRY_VAR(inputStream, - NS_NewLocalFileInputStream(requestedFile, PR_RDONLY, -1, - nsIFileInputStream::DEFER_OPEN)); + nsCOMPtr<nsIInputStream> inputStream = MOZ_TRY(NS_NewLocalFileInputStream( + requestedFile, PR_RDONLY, -1, nsIFileInputStream::DEFER_OPEN)); return inputStream; } diff --git a/security/manager/ssl/nsNSSCertificateDB.cpp b/security/manager/ssl/nsNSSCertificateDB.cpp @@ -1255,8 +1255,7 @@ nsresult VerifyCertAtTime(nsIX509Cert* aCert, nsIX509CertDB::VerifyUsage aUsage, OriginAttributes(), &evStatus); } else { const nsCString& flatHostname = PromiseFlatCString(aHostname); - VerifyUsage vu; - MOZ_TRY_VAR(vu, MapX509UsageToVerifierUsage(aUsage)); + VerifyUsage vu = MOZ_TRY(MapX509UsageToVerifierUsage(aUsage)); result = certVerifier->VerifyCert( certBytes, vu, aTime, nullptr, // Assume no context diff --git a/startupcache/StartupCache.cpp b/startupcache/StartupCache.cpp @@ -574,22 +574,21 @@ Result<Ok, nsresult> StartupCache::WriteToDisk() { for (auto& e : entries) { auto value = e.second; value->mOffset = offset; - Span<const char> result; - MOZ_TRY_VAR(result, - ctx.BeginCompressing(writeSpan).mapErr(MapLZ4ErrorToNsresult)); + Span<const char> result = + MOZ_TRY(ctx.BeginCompressing(writeSpan).mapErr(MapLZ4ErrorToNsresult)); MOZ_TRY(Write(fd, result.Elements(), result.Length())); offset += result.Length(); for (size_t i = 0; i < value->mUncompressedSize; i += chunkSize) { size_t size = std::min(chunkSize, value->mUncompressedSize - i); char* uncompressed = value->mData.get() + i; - MOZ_TRY_VAR(result, ctx.ContinueCompressing(Span(uncompressed, size)) - .mapErr(MapLZ4ErrorToNsresult)); + result = MOZ_TRY(ctx.ContinueCompressing(Span(uncompressed, size)) + .mapErr(MapLZ4ErrorToNsresult)); MOZ_TRY(Write(fd, result.Elements(), result.Length())); offset += result.Length(); } - MOZ_TRY_VAR(result, ctx.EndCompressing().mapErr(MapLZ4ErrorToNsresult)); + result = MOZ_TRY(ctx.EndCompressing().mapErr(MapLZ4ErrorToNsresult)); MOZ_TRY(Write(fd, result.Elements(), result.Length())); offset += result.Length(); value->mCompressedSize = offset - value->mOffset; diff --git a/toolkit/components/backgroundhangmonitor/HangDetails.cpp b/toolkit/components/backgroundhangmonitor/HangDetails.cpp @@ -457,8 +457,7 @@ Result<Ok, nsresult> WriteTString(PRFileDesc* aFile, template <typename CharT> Result<nsTString<CharT>, nsresult> ReadTString(PRFileDesc* aFile) { - uint32_t length; - MOZ_TRY_VAR(length, ReadUint(aFile)); + uint32_t length = MOZ_TRY(ReadUint(aFile)); nsTString<CharT> result; CharT buffer[512]; size_t bufferLength = sizeof(buffer) / sizeof(CharT); @@ -528,22 +527,18 @@ Result<Ok, nsresult> WriteEntry(PRFileDesc* aFile, const HangStack& aStack, } Result<Ok, nsresult> ReadEntry(PRFileDesc* aFile, HangStack& aStack) { - uint32_t type; - MOZ_TRY_VAR(type, ReadUint(aFile)); + uint32_t type = MOZ_TRY(ReadUint(aFile)); HangEntry::Type entryType = HangEntry::Type(type); switch (entryType) { case HangEntry::TnsCString: case HangEntry::THangEntryBufOffset: { - nsCString str; - MOZ_TRY_VAR(str, ReadTString<char>(aFile)); + nsCString str = MOZ_TRY(ReadTString<char>(aFile)); aStack.stack().AppendElement(std::move(str)); break; } case HangEntry::THangEntryModOffset: { - uint32_t module; - MOZ_TRY_VAR(module, ReadUint(aFile)); - uint32_t offset; - MOZ_TRY_VAR(offset, ReadUint(aFile)); + uint32_t module = MOZ_TRY(ReadUint(aFile)); + uint32_t offset = MOZ_TRY(ReadUint(aFile)); aStack.stack().AppendElement(HangEntryModOffset(module, offset)); break; } @@ -594,16 +589,14 @@ Result<HangDetails, nsresult> ReadHangDetailsFromFile(nsIFile* aFile) { } HangDetails result; - uint32_t duration; - MOZ_TRY_VAR(duration, ReadUint(fd)); + uint32_t duration = MOZ_TRY(ReadUint(fd)); result.duration() = TimeDuration::FromMilliseconds(double(duration)); - MOZ_TRY_VAR(result.threadName(), ReadTString<char>(fd)); - MOZ_TRY_VAR(result.runnableName(), ReadTString<char>(fd)); - MOZ_TRY_VAR(result.process(), ReadTString<char>(fd)); - MOZ_TRY_VAR(result.remoteType(), ReadTString<char>(fd)); + result.threadName() = MOZ_TRY(ReadTString<char>(fd)); + result.runnableName() = MOZ_TRY(ReadTString<char>(fd)); + result.process() = MOZ_TRY(ReadTString<char>(fd)); + result.remoteType() = MOZ_TRY(ReadTString<char>(fd)); - uint32_t numAnnotations; - MOZ_TRY_VAR(numAnnotations, ReadUint(fd)); + uint32_t numAnnotations = MOZ_TRY(ReadUint(fd)); auto& annotations = result.annotations(); // Add a "Unrecovered" annotation so we can know when processing this that @@ -615,14 +608,13 @@ Result<HangDetails, nsresult> ReadHangDetailsFromFile(nsIFile* aFile) { for (size_t i = 0; i < numAnnotations; ++i) { HangAnnotation annot; - MOZ_TRY_VAR(annot.name(), ReadTString<char16_t>(fd)); - MOZ_TRY_VAR(annot.value(), ReadTString<char16_t>(fd)); + annot.name() = MOZ_TRY(ReadTString<char16_t>(fd)); + annot.value() = MOZ_TRY(ReadTString<char16_t>(fd)); annotations.AppendElement(std::move(annot)); } auto& stack = result.stack(); - uint32_t numFrames; - MOZ_TRY_VAR(numFrames, ReadUint(fd)); + uint32_t numFrames = MOZ_TRY(ReadUint(fd)); if (!stack.stack().SetCapacity(numFrames, mozilla::fallible)) { return Err(NS_ERROR_FAILURE); } @@ -631,8 +623,7 @@ Result<HangDetails, nsresult> ReadHangDetailsFromFile(nsIFile* aFile) { MOZ_TRY(ReadEntry(fd, stack)); } - uint32_t numModules; - MOZ_TRY_VAR(numModules, ReadUint(fd)); + uint32_t numModules = MOZ_TRY(ReadUint(fd)); auto& modules = stack.modules(); if (!annotations.SetCapacity(numModules, mozilla::fallible)) { return Err(NS_ERROR_FAILURE); @@ -640,8 +631,8 @@ Result<HangDetails, nsresult> ReadHangDetailsFromFile(nsIFile* aFile) { for (size_t i = 0; i < numModules; ++i) { HangModule module; - MOZ_TRY_VAR(module.name(), ReadTString<char16_t>(fd)); - MOZ_TRY_VAR(module.breakpadId(), ReadTString<char>(fd)); + module.name() = MOZ_TRY(ReadTString<char16_t>(fd)); + module.breakpadId() = MOZ_TRY(ReadTString<char>(fd)); modules.AppendElement(std::move(module)); } diff --git a/toolkit/components/extensions/ExtensionPolicyService.cpp b/toolkit/components/extensions/ExtensionPolicyService.cpp @@ -257,8 +257,7 @@ ExtensionPolicyService::CollectReports(nsIHandleReportCallback* aHandleReport, name.ReplaceSubstring("\"", ""); name.ReplaceSubstring("\\", ""); - nsString url; - MOZ_TRY_VAR(url, ext->GetURL(u""_ns)); + nsString url = MOZ_TRY(ext->GetURL(u""_ns)); nsPrintfCString desc("Extension(id=%s, name=\"%s\", baseURL=%s)", id.get(), name.get(), NS_ConvertUTF16toUTF8(url).get()); diff --git a/toolkit/components/glean/bindings/private/Ping.cpp b/toolkit/components/glean/bindings/private/Ping.cpp @@ -169,49 +169,48 @@ GleanPing::TestSubmission(nsIGleanPingTestCallback* aTestCallback, RefPtr<dom::Promise> submitPromise; MOZ_TRY(aSubmitCallback->Call(getter_AddRefs(submitPromise))); - RefPtr<dom::Promise> thenPromise; - MOZ_TRY_VAR(thenPromise, - submitPromise->ThenWithCycleCollectedArgs( - [aSubmitTimeoutMs](JSContext*, JS::Handle<JS::Value>, - ErrorResult& aRv, - RefPtr<dom::Promise> aSubmittedPromise) - -> already_AddRefed<dom::Promise> { - // The submit callback has finished successfully now - // (whether or not it was async). - if (aSubmitTimeoutMs) { - // We have a submit timeout, which means that - // `aSubmitCallback` has triggered the submission through - // some async means that does not complete before it - // returns (e.g., idle dispatch from c++). Reject - // `submittedPromise` after the given timeout to make sure - // we don't hang forever waiting for a submission that - // might not happen. - nsresult rv = NS_DelayedDispatchToCurrentThread( - NS_NewRunnableFunction( - __func__, - [submittedPromise = RefPtr(aSubmittedPromise)]() { - submittedPromise->MaybeRejectWithTimeoutError( - "Ping was not submitted after timeout"); - }), - aSubmitTimeoutMs); - - if (NS_FAILED(rv)) { - aSubmittedPromise->MaybeReject(rv); - } - } else { - // If there is no timeout then the ping should have been - // submitted already. We attempt to reject the promise, - // which will have no affect if the promise is already - // settled. - aSubmittedPromise->MaybeRejectWithOperationError( - "Ping did not submit immediately"); - } - - // Chain into `submittedPromise` so that we will - // resolve/reject appropriately. - return aSubmittedPromise.forget(); - }, - std::move(submittedPromise))); + RefPtr<dom::Promise> thenPromise = + MOZ_TRY(submitPromise->ThenWithCycleCollectedArgs( + [aSubmitTimeoutMs](JSContext*, JS::Handle<JS::Value>, + ErrorResult& aRv, + RefPtr<dom::Promise> aSubmittedPromise) + -> already_AddRefed<dom::Promise> { + // The submit callback has finished successfully now + // (whether or not it was async). + if (aSubmitTimeoutMs) { + // We have a submit timeout, which means that + // `aSubmitCallback` has triggered the submission through + // some async means that does not complete before it + // returns (e.g., idle dispatch from c++). Reject + // `submittedPromise` after the given timeout to make sure + // we don't hang forever waiting for a submission that + // might not happen. + nsresult rv = NS_DelayedDispatchToCurrentThread( + NS_NewRunnableFunction( + __func__, + [submittedPromise = RefPtr(aSubmittedPromise)]() { + submittedPromise->MaybeRejectWithTimeoutError( + "Ping was not submitted after timeout"); + }), + aSubmitTimeoutMs); + + if (NS_FAILED(rv)) { + aSubmittedPromise->MaybeReject(rv); + } + } else { + // If there is no timeout then the ping should have been + // submitted already. We attempt to reject the promise, + // which will have no affect if the promise is already + // settled. + aSubmittedPromise->MaybeRejectWithOperationError( + "Ping did not submit immediately"); + } + + // Chain into `submittedPromise` so that we will + // resolve/reject appropriately. + return aSubmittedPromise.forget(); + }, + std::move(submittedPromise))); thenPromise.forget(aOutPromise); return NS_OK; diff --git a/toolkit/components/startup/nsAppStartup.cpp b/toolkit/components/startup/nsAppStartup.cpp @@ -549,8 +549,7 @@ Result<ShutdownPhase, nsresult> IDLShutdownPhaseToNative( NS_IMETHODIMP nsAppStartup::AdvanceShutdownPhase(IDLShutdownPhase aPhase) { - ShutdownPhase nativePhase; - MOZ_TRY_VAR(nativePhase, IDLShutdownPhaseToNative(aPhase)); + ShutdownPhase nativePhase = MOZ_TRY(IDLShutdownPhaseToNative(aPhase)); AppShutdown::AdvanceShutdownPhase(nativePhase); return NS_OK; } @@ -558,8 +557,7 @@ nsAppStartup::AdvanceShutdownPhase(IDLShutdownPhase aPhase) { NS_IMETHODIMP nsAppStartup::IsInOrBeyondShutdownPhase(IDLShutdownPhase aPhase, bool* aIsInOrBeyond) { - ShutdownPhase nativePhase; - MOZ_TRY_VAR(nativePhase, IDLShutdownPhaseToNative(aPhase)); + ShutdownPhase nativePhase = MOZ_TRY(IDLShutdownPhaseToNative(aPhase)); *aIsInOrBeyond = AppShutdown::IsInOrBeyond(nativePhase); return NS_OK; } diff --git a/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp b/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp @@ -217,15 +217,13 @@ nsresult nsUrlClassifierStreamUpdater::FetchUpdate( "timeout. Disabling these update timeouts."); return NS_OK; } - MOZ_TRY_VAR(mResponseTimeoutTimer, - NS_NewTimerWithCallback( - this, StaticPrefs::urlclassifier_update_response_timeout_ms(), - nsITimer::TYPE_ONE_SHOT)); + mResponseTimeoutTimer = MOZ_TRY(NS_NewTimerWithCallback( + this, StaticPrefs::urlclassifier_update_response_timeout_ms(), + nsITimer::TYPE_ONE_SHOT)); - MOZ_TRY_VAR(mTimeoutTimer, - NS_NewTimerWithCallback( - this, StaticPrefs::urlclassifier_update_timeout_ms(), - nsITimer::TYPE_ONE_SHOT)); + mTimeoutTimer = MOZ_TRY(NS_NewTimerWithCallback( + this, StaticPrefs::urlclassifier_update_timeout_ms(), + nsITimer::TYPE_ONE_SHOT)); if (StaticPrefs::urlclassifier_update_timeout_ms() < MIN_TIMEOUT_MS) { LOG(("Download update timeout %d ms (< %d ms) would be too small", @@ -327,9 +325,8 @@ nsUrlClassifierStreamUpdater::DownloadUpdates( // We cannot guarantee that we will be notified when DBService is done // processing the current update, so we fire a retry timer on our own. - MOZ_TRY_VAR(mFetchNextRequestTimer, - NS_NewTimerWithCallback(this, FETCH_NEXT_REQUEST_RETRY_DELAY_MS, - nsITimer::TYPE_ONE_SHOT)); + mFetchNextRequestTimer = MOZ_TRY(NS_NewTimerWithCallback( + this, FETCH_NEXT_REQUEST_RETRY_DELAY_MS, nsITimer::TYPE_ONE_SHOT)); return NS_OK; } diff --git a/toolkit/components/viaduct/ViaductRequest.cpp b/toolkit/components/viaduct/ViaductRequest.cpp @@ -152,13 +152,10 @@ nsresult ViaductRequest::LaunchRequest( false /* aStreamHasHeaders */); } - MOZ_TRY_VAR( - mConnectTimeoutTimer, - NS_NewTimerWithCallback(this, request.connect_timeout_secs() * 1000, - nsITimer::TYPE_ONE_SHOT)); - MOZ_TRY_VAR(mReadTimeoutTimer, - NS_NewTimerWithCallback(this, request.read_timeout_secs() * 1000, - nsITimer::TYPE_ONE_SHOT)); + mConnectTimeoutTimer = MOZ_TRY(NS_NewTimerWithCallback( + this, request.connect_timeout_secs() * 1000, nsITimer::TYPE_ONE_SHOT)); + mReadTimeoutTimer = MOZ_TRY(NS_NewTimerWithCallback( + this, request.read_timeout_secs() * 1000, nsITimer::TYPE_ONE_SHOT)); rv = httpChannel->AsyncOpen(this); NS_ENSURE_SUCCESS(rv, rv); diff --git a/toolkit/mozapps/defaultagent/DefaultPDF.cpp b/toolkit/mozapps/defaultagent/DefaultPDF.cpp @@ -141,10 +141,7 @@ static PdfResult GetDefaultPdf() { } DefaultPdfResult GetDefaultPdfInfo() { - DefaultPdfInfo pdfInfo; - MOZ_TRY_VAR(pdfInfo.currentDefaultPdf, GetDefaultPdf()); - - return pdfInfo; + return DefaultPdfInfo{MOZ_TRY(GetDefaultPdf())}; } } // namespace mozilla::default_agent diff --git a/toolkit/mozapps/defaultagent/Registry.cpp b/toolkit/mozapps/defaultagent/Registry.cpp @@ -92,8 +92,7 @@ MaybeStringResult RegistryGetValueString( } // Convert to narrow string and return. - std::string narrowData; - MOZ_TRY_VAR(narrowData, Utf16ToUtf8(wideData.Elements())); + std::string narrowData = MOZ_TRY(Utf16ToUtf8(wideData.Elements())); return mozilla::Some(narrowData); } @@ -113,8 +112,7 @@ VoidResult RegistrySetValueString(IsPrefixed isPrefixed, std::wstring keyName = MakeKeyName(subKey); // Convert the value from a narrow string to a wide string - std::wstring wideValue; - MOZ_TRY_VAR(wideValue, Utf8ToUtf16(newValue)); + std::wstring wideValue = MOZ_TRY(Utf8ToUtf16(newValue)); // Store the value LSTATUS ls = RegSetKeyValueW(HKEY_CURRENT_USER, keyName.c_str(), diff --git a/toolkit/mozapps/extensions/AddonManagerStartup.cpp b/toolkit/mozapps/extensions/AddonManagerStartup.cpp @@ -211,8 +211,7 @@ static_assert(sizeof STRUCTURED_CLONE_MAGIC % 8 == 0, static Result<nsCString, nsresult> ReadFileLZ4(nsIFile* file) { static const char MAGIC_NUMBER[] = "mozLz40"; - nsCString lz4; - MOZ_TRY_VAR(lz4, URLPreloader::ReadFile(file)); + nsCString lz4 = MOZ_TRY(URLPreloader::ReadFile(file)); if (lz4.IsEmpty()) { return lz4; @@ -256,7 +255,7 @@ static Result<FileLocation, nsresult> GetFileLocation(nsIURI* uri) { nsCString entry; MOZ_TRY(ParseJARURI(uri, getter_AddRefs(fileURI), entry)); - MOZ_TRY_VAR(file, GetFile(fileURI)); + file = MOZ_TRY(GetFile(fileURI)); location.Init(file, entry); } @@ -440,8 +439,7 @@ Result<nsCOMPtr<nsIFile>, nsresult> Addon::FullPath() { } Result<bool, nsresult> Addon::UpdateLastModifiedTime() { - nsCOMPtr<nsIFile> file; - MOZ_TRY_VAR(file, FullPath()); + nsCOMPtr<nsIFile> file = MOZ_TRY(FullPath()); JS::Rooted<JSObject*> obj(mCx, mObject); @@ -525,8 +523,7 @@ nsresult AddonManagerStartup::ReadStartupData( if (addon.Enabled() && (shouldCheck || addon.ShouldCheckStartupModifications())) { - bool changed; - MOZ_TRY_VAR(changed, addon.UpdateLastModifiedTime()); + bool changed = MOZ_TRY(addon.UpdateLastModifiedTime()); if (changed) { loc.SetChanged(true); } @@ -557,8 +554,7 @@ nsresult AddonManagerStartup::EncodeBlob(JS::Handle<JS::Value> value, }); NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY); - nsCString lz4; - MOZ_TRY_VAR(lz4, EncodeLZ4(scData, STRUCTURED_CLONE_MAGIC)); + nsCString lz4 = MOZ_TRY(EncodeLZ4(scData, STRUCTURED_CLONE_MAGIC)); JS::Rooted<JSObject*> obj(cx, dom::ArrayBuffer::Create(cx, lz4, rv)); RETURN_NSRESULT_ON_FAILURE(rv); @@ -590,7 +586,7 @@ nsresult AddonManagerStartup::DecodeBlob(JS::Handle<JS::Value> value, reinterpret_cast<char*>(JS::GetArrayBufferData(obj, &isShared, nogc)), uint32_t(len)); - MOZ_TRY_VAR(data, DecodeLZ4(lz4, STRUCTURED_CLONE_MAGIC)); + data = MOZ_TRY(DecodeLZ4(lz4, STRUCTURED_CLONE_MAGIC)); } bool ok = holder.CopyExternalData(data.get(), data.Length()); @@ -620,8 +616,7 @@ static nsresult EnumerateZip(nsIZipReader* zip, const nsACString& pattern, nsresult AddonManagerStartup::EnumerateJAR(nsIURI* uri, const nsACString& pattern, nsTArray<nsString>& results) { - nsCOMPtr<nsIZipReaderCache> zipCache; - MOZ_TRY_VAR(zipCache, GetJarCache()); + nsCOMPtr<nsIZipReaderCache> zipCache = MOZ_TRY(GetJarCache()); nsCOMPtr<nsIZipReader> zip; nsCOMPtr<nsIFile> file; @@ -630,11 +625,11 @@ nsresult AddonManagerStartup::EnumerateJAR(nsIURI* uri, nsCString entry; MOZ_TRY(ParseJARURI(jarURI, getter_AddRefs(fileURI), entry)); - MOZ_TRY_VAR(file, GetFile(fileURI)); + file = MOZ_TRY(GetFile(fileURI)); MOZ_TRY( zipCache->GetInnerZip(file, Substring(entry, 1), getter_AddRefs(zip))); } else { - MOZ_TRY_VAR(file, GetFile(uri)); + file = MOZ_TRY(GetFile(uri)); MOZ_TRY(zipCache->GetZip(file, getter_AddRefs(zip))); } MOZ_ASSERT(zip); @@ -790,8 +785,7 @@ AddonManagerStartup::RegisterChrome(nsIURI* manifestURI, NS_ENSURE_ARG_POINTER(manifestURI); NS_ENSURE_TRUE(IsArray(locations), NS_ERROR_INVALID_ARG); - FileLocation location; - MOZ_TRY_VAR(location, GetFileLocation(manifestURI)); + FileLocation location = MOZ_TRY(GetFileLocation(manifestURI)); nsTArray<RegistryEntries::Locale> locales; nsTArray<ContentEntry> content; diff --git a/toolkit/xre/nsAppRunner.cpp b/toolkit/xre/nsAppRunner.cpp @@ -1809,8 +1809,7 @@ nsXULAppInfo::GetExtraFileForID(const nsAString& aId, nsIFile** aExtraFile) { NS_IMETHODIMP nsXULAppInfo::AnnotateCrashReport(const nsACString& key, JS::Handle<JS::Value> data, JSContext* cx) { - CrashReporter::Annotation annotation; - MOZ_TRY_VAR(annotation, GetCrashAnnotation(key)); + CrashReporter::Annotation annotation = MOZ_TRY(GetCrashAnnotation(key)); switch (data.type()) { case JS::ValueType::Int32: CrashReporter::RecordAnnotationU32(annotation, data.toInt32()); @@ -1844,8 +1843,7 @@ nsXULAppInfo::AnnotateCrashReport(const nsACString& key, NS_IMETHODIMP nsXULAppInfo::RemoveCrashReportAnnotation(const nsACString& key) { - CrashReporter::Annotation annotation; - MOZ_TRY_VAR(annotation, GetCrashAnnotation(key)); + CrashReporter::Annotation annotation = MOZ_TRY(GetCrashAnnotation(key)); CrashReporter::UnrecordAnnotation(annotation); return NS_OK; } @@ -1860,8 +1858,7 @@ nsXULAppInfo::IsAnnotationValid(const nsACString& aValue, bool* aIsValid) { NS_IMETHODIMP nsXULAppInfo::IsAnnotationAllowedForPing(const nsACString& aValue, bool* aIsAllowed) { - CrashReporter::Annotation annotation; - MOZ_TRY_VAR(annotation, GetCrashAnnotation(aValue)); + CrashReporter::Annotation annotation = MOZ_TRY(GetCrashAnnotation(aValue)); *aIsAllowed = CrashReporter::IsAnnotationAllowedForPing(annotation); return NS_OK; } @@ -1869,8 +1866,7 @@ nsXULAppInfo::IsAnnotationAllowedForPing(const nsACString& aValue, NS_IMETHODIMP nsXULAppInfo::IsAnnotationAllowedForReport(const nsACString& aValue, bool* aIsAllowed) { - CrashReporter::Annotation annotation; - MOZ_TRY_VAR(annotation, GetCrashAnnotation(aValue)); + CrashReporter::Annotation annotation = MOZ_TRY(GetCrashAnnotation(aValue)); *aIsAllowed = CrashReporter::IsAnnotationAllowedForReport(annotation); return NS_OK; } @@ -6142,8 +6138,7 @@ int XREMain::XRE_main(int argc, char* argv[], const BootstrapConfig& aConfig) { // If we exit gracefully, remove the startup crash canary file. auto cleanup = MakeScopeExit([&]() -> nsresult { if (mProfLD) { - nsCOMPtr<nsIFile> crashFile; - MOZ_TRY_VAR(crashFile, GetIncompleteStartupFile(mProfLD)); + nsCOMPtr<nsIFile> crashFile = MOZ_TRY(GetIncompleteStartupFile(mProfLD)); crashFile->Remove(false); } return NS_OK; diff --git a/tools/fuzzing/common/FuzzingBufferReader.h b/tools/fuzzing/common/FuzzingBufferReader.h @@ -34,17 +34,16 @@ class [[nodiscard]] GenericErrorResult<TestFuncRetValue> { MOZ_IMPLICIT operator int() const { return mErrorValue; } }; -// This allows using MOZ_TRY_VAR to unpack data from the libFuzzer test buffer. +// This allows using MOZ_TRY to unpack data from the libFuzzer test buffer. // // static int testCallback(const uint8_t* buf, size_t size) { // FuzzingBufferReader fuzzBuf(buf, size); // -// int32_t data; -// MOZ_TRY_VAR(data, fuzzBuf.Read<int32_t>()); +// int32_t data = MOZ_TRY(fuzzBuf.Read<int32_t>()); // ... // } // -// If the remaining buffer data is less than requested, MOZ_TRY_VAR returns 0 to +// If the remaining buffer data is less than requested, MOZ_TRY returns 0 to // end the iteration. class FuzzingBufferReader { public: diff --git a/tools/profiler/core/platform.cpp b/tools/profiler/core/platform.cpp @@ -3999,10 +3999,8 @@ do_profiler_stream_json_for_this_process( return Err(ProfilerError::IsInactive); } - ProfileGenerationAdditionalInformation additionalInfo; - MOZ_TRY_VAR( - additionalInfo, - locked_profiler_stream_json_for_this_process( + ProfileGenerationAdditionalInformation additionalInfo = + MOZ_TRY(locked_profiler_stream_json_for_this_process( lock, aWriter, aSinceTime, preRecordedMetaInformation, aIsShuttingDown, aService, aProgressLogger.CreateSubLoggerFromTo( @@ -4025,10 +4023,10 @@ profiler_stream_json_for_this_process(SpliceableJSONWriter& aWriter, "In the parent process, profiles should only be generated from the main " "thread, otherwise they will be incomplete."); - ProfileGenerationAdditionalInformation additionalInfo; - MOZ_TRY_VAR(additionalInfo, do_profiler_stream_json_for_this_process( - aWriter, aSinceTime, aIsShuttingDown, - aService, std::move(aProgressLogger))); + ProfileGenerationAdditionalInformation additionalInfo = + MOZ_TRY(do_profiler_stream_json_for_this_process( + aWriter, aSinceTime, aIsShuttingDown, aService, + std::move(aProgressLogger))); return additionalInfo; } diff --git a/widget/RemoteLookAndFeel.cpp b/widget/RemoteLookAndFeel.cpp @@ -91,10 +91,8 @@ void AddToMap(nsTArray<Item>& aItems, nsTArray<UInt>& aMap, Id aId, nsresult RemoteLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor& aResult) { - const nscolor* result; const bool dark = aScheme == ColorScheme::Dark; - MOZ_TRY_VAR( - result, + const nscolor* result = MOZ_TRY( MapLookup(dark ? mTables.darkColors() : mTables.lightColors(), dark ? mTables.darkColorMap() : mTables.lightColorMap(), aID)); aResult = *result; @@ -102,15 +100,15 @@ nsresult RemoteLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, } nsresult RemoteLookAndFeel::NativeGetInt(IntID aID, int32_t& aResult) { - const int32_t* result; - MOZ_TRY_VAR(result, MapLookup(mTables.ints(), mTables.intMap(), aID)); + const int32_t* result = + MOZ_TRY(MapLookup(mTables.ints(), mTables.intMap(), aID)); aResult = *result; return NS_OK; } nsresult RemoteLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) { - const float* result; - MOZ_TRY_VAR(result, MapLookup(mTables.floats(), mTables.floatMap(), aID)); + const float* result = + MOZ_TRY(MapLookup(mTables.floats(), mTables.floatMap(), aID)); aResult = *result; return NS_OK; } diff --git a/widget/windows/filedialog/WinFileDialogCommands.cpp b/widget/windows/filedialog/WinFileDialogCommands.cpp @@ -467,8 +467,7 @@ auto SpawnPickerT(HWND parent, FileDialogType type, ExtractorF&& extractor, // with our context set temporarily to system-dpi-aware. WinUtils::AutoSystemDpiAware dpiAwareness; - RefPtr<IFileDialog> dialog; - MOZ_TRY_VAR(dialog, MakeFileDialog(type)); + RefPtr<IFileDialog> dialog = MOZ_TRY(MakeFileDialog(type)); MOZ_TRY(ApplyCommands(dialog, commands)); @@ -479,8 +478,7 @@ auto SpawnPickerT(HWND parent, FileDialogType type, ExtractorF&& extractor, return mozilla::Err(MOZ_FD_LOCAL_ERROR("IFileDialog::Show", rv)); } - RetT res; - MOZ_TRY_VAR(res, extractor(dialog.get())); + RetT res = MOZ_TRY(extractor(dialog.get())); return Some(res); }); diff --git a/widget/windows/nsWindow.cpp b/widget/windows/nsWindow.cpp @@ -8551,7 +8551,7 @@ nsresult nsWindow::SynthesizeNativeTouchPoint( // If we already know about this pointer id get it's record return mActivePointers.WithEntryHandle(aPointerId, [&](auto&& entry) { POINTER_FLAGS flags; - // Can't use MOZ_TRY_VAR because it confuses WithEntryHandle + // Can't use MOZ_TRY because it confuses WithEntryHandle auto result = PointerStateToFlag(aPointerState, !!entry); if (result.isOk()) { flags = result.unwrap(); @@ -8639,7 +8639,7 @@ nsresult nsWindow::SynthesizeNativePenInput( // If we already know about this pointer id get it's record return mActivePointers.WithEntryHandle(aPointerId, [&](auto&& entry) { POINTER_FLAGS flags; - // Can't use MOZ_TRY_VAR because it confuses WithEntryHandle + // Can't use MOZ_TRY because it confuses WithEntryHandle auto result = PointerStateToFlag(aPointerState, !!entry); if (result.isOk()) { flags = result.unwrap(); diff --git a/xpcom/base/MemoryTelemetry.cpp b/xpcom/base/MemoryTelemetry.cpp @@ -507,8 +507,7 @@ nsresult MemoryTelemetry::FinishGatheringTotalMemory( } if (aChildSizes.Length() > 1) { - int32_t tabsCount; - MOZ_TRY_VAR(tabsCount, GetOpenTabsCount()); + int32_t tabsCount = MOZ_TRY(GetOpenTabsCount()); nsCString key; if (tabsCount <= 10) { diff --git a/xpcom/base/nsINIParser.cpp b/xpcom/base/nsINIParser.cpp @@ -16,8 +16,7 @@ using namespace mozilla; nsresult nsINIParser::Init(nsIFile* aFile) { - nsCString result; - MOZ_TRY_VAR(result, URLPreloader::ReadFile(aFile)); + nsCString result = MOZ_TRY(URLPreloader::ReadFile(aFile)); return InitFromString(result); } diff --git a/xpcom/glue/standalone/nsXPCOMGlue.cpp b/xpcom/glue/standalone/nsXPCOMGlue.cpp @@ -144,8 +144,7 @@ static ReadDependentCBResult ReadDependentCB( ReadAheadLib(aDependentLib); } #endif - LibHandleType libHandle; - MOZ_TRY_VAR(libHandle, GetLibHandle(aDependentLib)); + LibHandleType libHandle = MOZ_TRY(GetLibHandle(aDependentLib)); AppendDependentLib(libHandle); return Ok(); diff --git a/xpcom/io/nsAnonymousTemporaryFile.cpp b/xpcom/io/nsAnonymousTemporaryFile.cpp @@ -164,8 +164,8 @@ class nsAnonTempFileRemover final : public nsIObserver, public nsINamed { // idle observer too early, it will be registered before the fake idle // service is installed when running in xpcshell, and this interferes with // the fake idle service, causing xpcshell-test failures. - MOZ_TRY_VAR(mTimer, NS_NewTimerWithObserver(this, SCHEDULE_TIMEOUT_MS, - nsITimer::TYPE_ONE_SHOT)); + mTimer = MOZ_TRY(NS_NewTimerWithObserver(this, SCHEDULE_TIMEOUT_MS, + nsITimer::TYPE_ONE_SHOT)); // Register shutdown observer so we can cancel the timer if we shutdown // before the timer runs. diff --git a/xpcom/string/nsTSubstring.h b/xpcom/string/nsTSubstring.h @@ -178,8 +178,8 @@ class BulkWriteHandle final { mozilla::Result<mozilla::Ok, nsresult> RestartBulkWrite( size_type aCapacity, size_type aPrefixToPreserve, bool aAllowShrinking) { MOZ_ASSERT(mString); - MOZ_TRY_VAR(mCapacity, mString->StartBulkWriteImpl( - aCapacity, aPrefixToPreserve, aAllowShrinking)); + mCapacity = MOZ_TRY(mString->StartBulkWriteImpl( + aCapacity, aPrefixToPreserve, aAllowShrinking)); return mozilla::Ok(); } diff --git a/xpcom/threads/CPUUsageWatcher.cpp b/xpcom/threads/CPUUsageWatcher.cpp @@ -163,13 +163,11 @@ Result<Ok, CPUUsageWatcherError> CPUUsageWatcher::Init() { mExternalUsageThreshold = std::max(1.0f - 1.0f / (float)mNumCPUs, kTolerableExternalCPUUsageFloor); - CPUStats processTimes; - MOZ_TRY_VAR(processTimes, GetProcessCPUStats(mNumCPUs)); + CPUStats processTimes = MOZ_TRY(GetProcessCPUStats(mNumCPUs)); mProcessUpdateTime = processTimes.updateTime; mProcessUsageTime = processTimes.usageTime; - CPUStats globalTimes; - MOZ_TRY_VAR(globalTimes, GetGlobalCPUStats()); + CPUStats globalTimes = MOZ_TRY(GetGlobalCPUStats()); mGlobalUpdateTime = globalTimes.updateTime; mGlobalUsageTime = globalTimes.usageTime; @@ -197,10 +195,8 @@ Result<Ok, CPUUsageWatcherError> CPUUsageWatcher::CollectCPUUsage() { mExternalUsageRatio = 0.0f; - CPUStats processTimes; - MOZ_TRY_VAR(processTimes, GetProcessCPUStats(mNumCPUs)); - CPUStats globalTimes; - MOZ_TRY_VAR(globalTimes, GetGlobalCPUStats()); + CPUStats processTimes = MOZ_TRY(GetProcessCPUStats(mNumCPUs)); + CPUStats globalTimes = MOZ_TRY(GetGlobalCPUStats()); uint64_t processUsageDelta = processTimes.usageTime - mProcessUsageTime; uint64_t processUpdateDelta = processTimes.updateTime - mProcessUpdateTime;