From 5a20a1c17ebc24e9441bc846dc196e7a31ac2ac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 13:56:20 +0900 Subject: [PATCH 01/24] Add a cargo feature --- crates/swc_allocator/Cargo.toml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/swc_allocator/Cargo.toml b/crates/swc_allocator/Cargo.toml index 08c80426d9bf..e9681bc79bec 100644 --- a/crates/swc_allocator/Cargo.toml +++ b/crates/swc_allocator/Cargo.toml @@ -9,8 +9,9 @@ repository = { workspace = true } version = "0.1.3" [features] -rkyv = ["dep:rkyv"] -serde = ["dep:serde", "dep:serde_derive"] +rkyv = ["dep:rkyv"] +scoped = [] +serde = ["dep:serde", "dep:serde_derive"] [dependencies] allocator-api2 = { workspace = true, features = ["serde"] } From 93ebbc6fa4162ea522a42ef4a10dbbbacb76e34f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 13:56:53 +0900 Subject: [PATCH 02/24] DEp --- crates/swc_core/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/swc_core/Cargo.toml b/crates/swc_core/Cargo.toml index 76afdfbc7df8..c9941da72650 100644 --- a/crates/swc_core/Cargo.toml +++ b/crates/swc_core/Cargo.toml @@ -381,6 +381,7 @@ swc_transform_common = { optional = true, version = "0.1.0", path = swc_typescript = { optional = true, version = "0.2.0", path = "../swc_typescript" } testing = { optional = true, version = "0.37.0", path = "../testing" } # TODO: eventually swc_plugin_runner needs to remove default features +swc_allocator = { version = "0.1.2", path = "../swc_allocator" } swc_plugin_runner = { optional = true, version = "0.110.0", path = "../swc_plugin_runner", default-features = false } [build-dependencies] From 061c490787af6cbd5e8e503268bab8c271405a18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 13:56:56 +0900 Subject: [PATCH 03/24] cargo lockifle --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 2cbd3fe4c68a..eec7451af539 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3897,6 +3897,7 @@ dependencies = [ "binding_macros", "once_cell", "swc", + "swc_allocator", "swc_atoms", "swc_bundler", "swc_cached", From 2dbbb9a69669d004e1839a18de91ffb3f9cf179c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 13:57:24 +0900 Subject: [PATCH 04/24] reexport --- crates/swc_core/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/swc_core/src/lib.rs b/crates/swc_core/src/lib.rs index 41b281198345..8d035af9db7c 100644 --- a/crates/swc_core/src/lib.rs +++ b/crates/swc_core/src/lib.rs @@ -1,5 +1,7 @@ #![cfg_attr(docsrs, feature(doc_cfg))] +pub extern crate swc_allocator as alloc; + #[cfg(feature = "swc_atoms")] #[cfg_attr(docsrs, doc(cfg(feature = "swc_atoms")))] pub use swc_atoms as atoms; From f20c03279bec3676c95b26db7492d304b4bf784f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 13:57:48 +0900 Subject: [PATCH 05/24] Add a feature to swc_core --- crates/swc_core/Cargo.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/swc_core/Cargo.toml b/crates/swc_core/Cargo.toml index c9941da72650..81ac790e38ad 100644 --- a/crates/swc_core/Cargo.toml +++ b/crates/swc_core/Cargo.toml @@ -38,6 +38,8 @@ doctest = false ## but changes internal logics to perform differently. These flag should be turned on in combination with ## actual features. Refer build.rs for more details. +scoped-alloc = ["swc_allocator/scoped"] + # swc_common/ahash common_ahash = ["swc_common/ahash"] From f9b707d6f48756711561ae8b702df29c8feed558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:31:35 +0900 Subject: [PATCH 06/24] docs.rs --- crates/swc_allocator/Cargo.toml | 11 +- crates/swc_atoms/words.txt | 2454 ------------------------------- 2 files changed, 8 insertions(+), 2457 deletions(-) delete mode 100644 crates/swc_atoms/words.txt diff --git a/crates/swc_allocator/Cargo.toml b/crates/swc_allocator/Cargo.toml index e9681bc79bec..d9df7f6c8249 100644 --- a/crates/swc_allocator/Cargo.toml +++ b/crates/swc_allocator/Cargo.toml @@ -8,6 +8,11 @@ name = "swc_allocator" repository = { workspace = true } version = "0.1.3" + [package.metadata.docs.rs] + all-features = true + rustdoc-args = ["--cfg", "docsrs"] + + [features] rkyv = ["dep:rkyv"] scoped = [] @@ -16,9 +21,9 @@ serde = ["dep:serde", "dep:serde_derive"] [dependencies] allocator-api2 = { workspace = true, features = ["serde"] } bumpalo = { workspace = true, features = [ - "allocator-api2", - "boxed", - "collections", + "allocator-api2", + "boxed", + "collections", ] } ptr_meta = { workspace = true } rkyv = { workspace = true, optional = true } diff --git a/crates/swc_atoms/words.txt b/crates/swc_atoms/words.txt deleted file mode 100644 index 9a28a185e154..000000000000 --- a/crates/swc_atoms/words.txt +++ /dev/null @@ -1,2454 +0,0 @@ -* --infinity --moz-activehyperlinktext --moz-animation --moz-animation-delay --moz-animation-direction --moz-animation-duration --moz-animation-fill-mode --moz-animation-iteration-count --moz-animation-name --moz-animation-play-state --moz-animation-timing-function --moz-any --moz-appearance --moz-backface-visibility --moz-background-origin --moz-background-size --moz-border-end --moz-border-image --moz-border-radius --moz-border-radius-bottomleft --moz-border-radius-bottomright --moz-border-radius-topleft --moz-border-radius-topright --moz-border-start --moz-box-align --moz-box-direction --moz-box-flex --moz-box-ordinal-group --moz-box-orient --moz-box-pack --moz-box-shadow --moz-box-sizing --moz-buttondefault --moz-buttonhoverface --moz-buttonhovertext --moz-calc --moz-cellhighlight --moz-cellhighlighttext --moz-column-count --moz-column-fill --moz-column-gap --moz-column-rule --moz-column-rule-color --moz-column-rule-style --moz-column-rule-width --moz-column-span --moz-column-width --moz-columns --moz-combobox --moz-comboboxtext --moz-default-background-color --moz-default-color --moz-dialog --moz-dialogtext --moz-document --moz-dragtargetzone --moz-element --moz-eventreerow --moz-font-feature-settings --moz-font-language-override --moz-font-variant-ligatures --moz-html-cellhighlight --moz-html-cellhighlighttext --moz-hyperlinktext --moz-hyphens --moz-keyframes --moz-mac-accentdarkestshadow --moz-mac-accentdarkshadow --moz-mac-accentface --moz-mac-accentlightesthighlight --moz-mac-accentlightshadow --moz-mac-accentregularhighlight --moz-mac-accentregularshadow --moz-mac-chrome-active --moz-mac-chrome-inactive --moz-mac-focusring --moz-mac-menuselect --moz-mac-menushadow --moz-mac-menutextselect --moz-margin-end --moz-margin-start --moz-menubarhovertext --moz-menubartext --moz-menuhover --moz-menuhovertext --moz-nativehyperlinktext --moz-oddtreerow --moz-padding-end --moz-padding-start --moz-perspective --moz-perspective-origin --moz-tab-size --moz-text-align-last --moz-text-decoration --moz-text-decoration-color --moz-text-decoration-line --moz-text-decoration-style --moz-text-size-adjust --moz-transform --moz-transform-origin --moz-transform-style --moz-transition --moz-transition-delay --moz-transition-duration --moz-transition-timing-function --moz-user-select --moz-visitedhyperlinktext --moz-win-accentcolor --moz-win-accentcolortext --moz-win-communicationstext --moz-win-mediatext --ms-appearance --ms-flex --ms-flex-align --ms-flex-direction --ms-flex-flow --ms-flex-item-align --ms-flex-line-pack --ms-flex-negative --ms-flex-order --ms-flex-pack --ms-flex-positive --ms-flex-preferred-size --ms-flex-wrap --ms-flow-from --ms-flow-into --ms-high-contrast-adjust --ms-hyphens --ms-interpolation-mode --ms-keyframes --ms-region-fragment --ms-scroll-chaining --ms-scroll-snap-coordinate --ms-scroll-snap-destination --ms-scroll-snap-points-x --ms-scroll-snap-points-y --ms-scroll-snap-type --ms-text-size-adjust --ms-text-spacing --ms-touch-action --ms-transform --ms-transform-origin --ms-user-select --ms-viewport --ms-writing-mode --o-animation --o-animation-delay --o-animation-direction --o-animation-duration --o-animation-fill-mode --o-animation-iteration-count --o-animation-name --o-animation-play-state --o-animation-timing-function --o-background-origin --o-background-size --o-border-image --o-keyframes --o-object-fit --o-object-position --o-tab-size --o-text-overflow --o-transform --o-transform-origin --o-transition --o-transition-delay --o-transition-duration --o-transition-timing-function --o-viewport --webkit-align-content --webkit-align-items --webkit-align-self --webkit-animation --webkit-animation-delay --webkit-animation-direction --webkit-animation-duration --webkit-animation-fill-mode --webkit-animation-iteration-count --webkit-animation-name --webkit-animation-play-state --webkit-animation-timing-function --webkit-any --webkit-appearance --webkit-backdrop-filter --webkit-backface-visibility --webkit-background-clip --webkit-background-origin --webkit-background-size --webkit-border-after --webkit-border-before --webkit-border-bottom-left-radius --webkit-border-bottom-right-radius --webkit-border-end --webkit-border-image --webkit-border-radius --webkit-border-start --webkit-border-top-left-radius --webkit-border-top-right-radius --webkit-box-align --webkit-box-decoration-break --webkit-box-direction --webkit-box-flex --webkit-box-ordinal-group --webkit-box-orient --webkit-box-pack --webkit-box-shadow --webkit-box-sizing --webkit-calc --webkit-clip-path --webkit-column-break-after --webkit-column-break-before --webkit-column-break-inside --webkit-column-count --webkit-column-fill --webkit-column-gap --webkit-column-rule --webkit-column-rule-color --webkit-column-rule-style --webkit-column-rule-width --webkit-column-span --webkit-column-width --webkit-columns --webkit-filter --webkit-flex --webkit-flex-basis --webkit-flex-direction --webkit-flex-flow --webkit-flex-grow --webkit-flex-shrink --webkit-flex-wrap --webkit-flow-from --webkit-flow-into --webkit-font-feature-settings --webkit-font-kerning --webkit-font-language-override --webkit-font-variant-ligatures --webkit-hyphens --webkit-justify-content --webkit-keyframes --webkit-line-clamp --webkit-margin-after --webkit-margin-before --webkit-margin-end --webkit-margin-start --webkit-mask --webkit-mask-border-repeat --webkit-mask-border-source --webkit-mask-box-image --webkit-mask-box-image-outset --webkit-mask-box-image-repeat --webkit-mask-box-image-slice --webkit-mask-box-image-width --webkit-mask-clip --webkit-mask-composite --webkit-mask-image --webkit-mask-origin --webkit-mask-position --webkit-mask-repeat --webkit-mask-size --webkit-order --webkit-padding-after --webkit-padding-before --webkit-padding-end --webkit-padding-start --webkit-perspective --webkit-perspective-origin --webkit-print-color-adjust --webkit-region-fragment --webkit-scroll-snap-coordinate --webkit-scroll-snap-destination --webkit-scroll-snap-points-x --webkit-scroll-snap-points-y --webkit-scroll-snap-type --webkit-shape-image-threshold --webkit-shape-margin --webkit-shape-outside --webkit-text-decoration --webkit-text-decoration-color --webkit-text-decoration-line --webkit-text-decoration-skip --webkit-text-decoration-skip-ink --webkit-text-decoration-style --webkit-text-emphasis --webkit-text-emphasis-color --webkit-text-emphasis-position --webkit-text-emphasis-style --webkit-text-orientation --webkit-text-size-adjust --webkit-transform --webkit-transform-origin --webkit-transform-style --webkit-transition --webkit-transition-delay --webkit-transition-duration --webkit-transition-property --webkit-transition-timing-function --webkit-user-select --webkit-writing-mode -AbortController -AbortSignal -AnalyserNode -Animation -AnimationEffectReadOnly -AnimationEffectTiming -AnimationEffectTimingReadOnly -AnimationEvent -AnimationPlaybackEvent -AnimationTimeline -ApplicationCache -ApplicationCacheErrorEvent -Array -ArrayBuffer -Atomics -Attr -Audio -AudioBuffer -AudioBufferSourceNode -AudioContext -AudioDestinationNode -AudioListener -AudioNode -AudioParam -AudioProcessingEvent -AudioScheduledSourceNode -AudioWorkletGlobalScope -AudioWorkletNode -AudioWorkletProcessor -BarProp -BaseAudioContext -BatteryManager -BeforeUnloadEvent -BigInt -BigInt64Array -BigUint64Array -BiquadFilterNode -Blob -BlobEvent -Boolean -Bottom line -BroadcastChannel -BudgetService -ByteLengthQueuingStrategy -CSS -CSSConditionRule -CSSFontFaceRule -CSSGroupingRule -CSSImportRule -CSSKeyframeRule -CSSKeyframesRule -CSSMediaRule -CSSNamespaceRule -CSSPageRule -CSSRule -CSSRuleList -CSSStyleDeclaration -CSSStyleRule -CSSStyleSheet -CSSSupportsRule -Cache -CacheStorage -CanvasCaptureMediaStreamTrack -CanvasGradient -CanvasPattern -CanvasRenderingContext2D -ChannelMergerNode -ChannelSplitterNode -CharacterData -ClipboardEvent -CloseEvent -Comment -CompositionEvent -ConstantSourceNode -ConvolverNode -CountQueuingStrategy -Credential -CredentialsContainer -Crypto -CryptoKey -CustomElementRegistry -CustomEvent -DOMError -DOMException -DOMImplementation -DOMMatrix -DOMMatrixReadOnly -DOMParser -DOMPoint -DOMPointReadOnly -DOMQuad -DOMRect -DOMRectReadOnly -DOMStringList -DOMStringMap -DOMTokenList -DataTransfer -DataTransferItem -DataTransferItemList -DataView -Date -DelayNode -DeviceMotionEvent -DeviceOrientationEvent -Document -DocumentFragment -DocumentType -DragEvent -DynamicsCompressorNode -Element -Error -ErrorEvent -EvalError -Event -EventSource -EventTarget -Exclude -Extract -File -FileList -FileReader -Float32Array -Float64Array -FocusEvent -FontFace -FontFaceSetLoadEvent -FormData -Function -GainNode -Gamepad -GamepadButton -GamepadEvent -HTMLAllCollection -HTMLAnchorElement -HTMLAreaElement -HTMLAudioElement -HTMLBRElement -HTMLBaseElement -HTMLBodyElement -HTMLButtonElement -HTMLCanvasElement -HTMLCollection -HTMLContentElement -HTMLDListElement -HTMLDataElement -HTMLDataListElement -HTMLDetailsElement -HTMLDialogElement -HTMLDirectoryElement -HTMLDivElement -HTMLDocument -HTMLElement -HTMLEmbedElement -HTMLFieldSetElement -HTMLFontElement -HTMLFormControlsCollection -HTMLFormElement -HTMLFrameElement -HTMLFrameSetElement -HTMLHRElement -HTMLHeadElement -HTMLHeadingElement -HTMLHtmlElement -HTMLIFrameElement -HTMLImageElement -HTMLInputElement -HTMLLIElement -HTMLLabelElement -HTMLLegendElement -HTMLLinkElement -HTMLMapElement -HTMLMarqueeElement -HTMLMediaElement -HTMLMenuElement -HTMLMetaElement -HTMLMeterElement -HTMLModElement -HTMLOListElement -HTMLObjectElement -HTMLOptGroupElement -HTMLOptionElement -HTMLOptionsCollection -HTMLOutputElement -HTMLParagraphElement -HTMLParamElement -HTMLPictureElement -HTMLPreElement -HTMLProgressElement -HTMLQuoteElement -HTMLScriptElement -HTMLSelectElement -HTMLShadowElement -HTMLSlotElement -HTMLSourceElement -HTMLSpanElement -HTMLStyleElement -HTMLTableCaptionElement -HTMLTableCellElement -HTMLTableColElement -HTMLTableElement -HTMLTableRowElement -HTMLTableSectionElement -HTMLTemplateElement -HTMLTextAreaElement -HTMLTimeElement -HTMLTitleElement -HTMLTrackElement -HTMLUListElement -HTMLUnknownElement -HTMLVideoElement -HashChangeEvent -Headers -History -Hz -IDBCursor -IDBCursorWithValue -IDBDatabase -IDBFactory -IDBIndex -IDBKeyRange -IDBObjectStore -IDBOpenDBRequest -IDBRequest -IDBTransaction -IDBVersionChangeEvent -IIRFilterNode -IdleDeadline -Image -ImageBitmap -ImageBitmapRenderingContext -ImageCapture -ImageData -Infinity -InputEvent -Int16Array -Int32Array -Int8Array -IntersectionObserver -IntersectionObserverEntry -Intl -JSON -KeyboardEvent -KeyframeEffect -KeyframeEffectReadOnly -Location -MIDIAccess -MIDIConnectionEvent -MIDIInput -MIDIInputMap -MIDIMessageEvent -MIDIOutput -MIDIOutputMap -MIDIPort -Map -Math -MediaDeviceInfo -MediaDevices -MediaElementAudioSourceNode -MediaEncryptedEvent -MediaError -MediaKeyMessageEvent -MediaKeySession -MediaKeyStatusMap -MediaKeySystemAccess -MediaList -MediaQueryList -MediaQueryListEvent -MediaRecorder -MediaSettingsRange -MediaSource -MediaStream -MediaStreamAudioDestinationNode -MediaStreamAudioSourceNode -MediaStreamEvent -MediaStreamTrack -MediaStreamTrackEvent -MessageChannel -MessageEvent -MessagePort -MimeType -MimeTypeArray -MouseEvent -MutationEvent -MutationObserver -MutationRecord -NODE_ENV -NaN -NamedNodeMap -NavigationPreloadManager -Navigator -NetworkInformation -Node -NodeFilter -NodeIterator -NodeList -NonNullable -Notification -Number -Object -OfflineAudioCompletionEvent -OfflineAudioContext -OffscreenCanvas -Option -OscillatorNode -PageTransitionEvent -PannerNode -Partial -Path2D -PaymentAddress -PaymentRequest -PaymentRequestUpdateEvent -PaymentResponse -Performance -PerformanceEntry -PerformanceLongTaskTiming -PerformanceMark -PerformanceMeasure -PerformanceNavigation -PerformanceNavigationTiming -PerformanceObserver -PerformanceObserverEntryList -PerformancePaintTiming -PerformanceResourceTiming -PerformanceTiming -PeriodicWave -PermissionStatus -Permissions -PhotoCapabilities -Pick -Plugin -PluginArray -PointerEvent -PopStateEvent -Presentation -PresentationAvailability -PresentationConnection -PresentationConnectionAvailableEvent -PresentationConnectionCloseEvent -PresentationConnectionList -PresentationReceiver -PresentationRequest -ProcessingInstruction -ProgressEvent -Promise -PromiseRejectionEvent -Proxy -PushManager -PushSubscription -PushSubscriptionOptions -RTCCertificate -RTCDataChannel -RTCDataChannelEvent -RTCDtlsTransport -RTCIceCandidate -RTCIceGatherer -RTCIceTransport -RTCPeerConnection -RTCPeerConnectionIceEvent -RTCRtpContributingSource -RTCRtpReceiver -RTCRtpSender -RTCSctpTransport -RTCSessionDescription -RTCStatsReport -RTCTrackEvent -RadioNodeList -Range -RangeError -React -ReadableStream -Readonly -ReadonlyArray -Record -ReferenceError -Reflect -RegExp -RemotePlayback -Request -Required -ResizeObserver -ResizeObserverEntry -Response -ReturnType -SVGAElement -SVGAngle -SVGAnimateElement -SVGAnimateMotionElement -SVGAnimateTransformElement -SVGAnimatedAngle -SVGAnimatedBoolean -SVGAnimatedEnumeration -SVGAnimatedInteger -SVGAnimatedLength -SVGAnimatedLengthList -SVGAnimatedNumber -SVGAnimatedNumberList -SVGAnimatedPreserveAspectRatio -SVGAnimatedRect -SVGAnimatedString -SVGAnimatedTransformList -SVGAnimationElement -SVGCircleElement -SVGClipPathElement -SVGComponentTransferFunctionElement -SVGDefsElement -SVGDescElement -SVGDiscardElement -SVGElement -SVGEllipseElement -SVGFEBlendElement -SVGFEColorMatrixElement -SVGFEComponentTransferElement -SVGFECompositeElement -SVGFEConvolveMatrixElement -SVGFEDiffuseLightingElement -SVGFEDisplacementMapElement -SVGFEDistantLightElement -SVGFEDropShadowElement -SVGFEFloodElement -SVGFEFuncAElement -SVGFEFuncBElement -SVGFEFuncGElement -SVGFEFuncRElement -SVGFEGaussianBlurElement -SVGFEImageElement -SVGFEMergeElement -SVGFEMergeNodeElement -SVGFEMorphologyElement -SVGFEOffsetElement -SVGFEPointLightElement -SVGFESpecularLightingElement -SVGFESpotLightElement -SVGFETileElement -SVGFETurbulenceElement -SVGFilterElement -SVGForeignObjectElement -SVGGElement -SVGGeometryElement -SVGGradientElement -SVGGraphicsElement -SVGImageElement -SVGLength -SVGLengthList -SVGLineElement -SVGLinearGradientElement -SVGMPathElement -SVGMarkerElement -SVGMaskElement -SVGMatrix -SVGMetadataElement -SVGNumber -SVGNumberList -SVGPathElement -SVGPatternElement -SVGPoint -SVGPointList -SVGPolygonElement -SVGPolylineElement -SVGPreserveAspectRatio -SVGRadialGradientElement -SVGRect -SVGRectElement -SVGSVGElement -SVGScriptElement -SVGSetElement -SVGStopElement -SVGStringList -SVGStyleElement -SVGSwitchElement -SVGSymbolElement -SVGTSpanElement -SVGTextContentElement -SVGTextElement -SVGTextPathElement -SVGTextPositioningElement -SVGTitleElement -SVGTransform -SVGTransformList -SVGUnitTypes -SVGUseElement -SVGViewElement -Screen -ScreenOrientation -ScriptProcessorNode -SecurityPolicyViolationEvent -Selection -ServiceWorker -ServiceWorkerContainer -ServiceWorkerRegistration -Set -ShadowRoot -SharedArrayBuffer -SharedWorker -SourceBuffer -SourceBufferList -SpeechSynthesisEvent -SpeechSynthesisUtterance -StaticRange -StereoPannerNode -Storage -StorageEvent -StorageManager -String -StyleSheet -StyleSheetList -SubtleCrypto -Symbol -SyntaxError -TaskAttributionTiming -Text -TextDecoder -TextEncoder -TextEvent -TextMetrics -TextTrack -TextTrackCue -TextTrackCueList -TextTrackList -TimeRanges -Touch -TouchEvent -TouchList -TrackEvent -TransitionEvent -TreeWalker -TypeError -UIEvent -URIError -URL -URLSearchParams -Uint16Array -Uint32Array -Uint8Array -Uint8ClampedArray -VTTCue -ValidityState -VisualViewport -WaveShaperNode -WeakMap -WeakSet -WebAssembly -WebGL2RenderingContext -WebGLActiveInfo -WebGLBuffer -WebGLContextEvent -WebGLFramebuffer -WebGLProgram -WebGLQuery -WebGLRenderbuffer -WebGLRenderingContext -WebGLSampler -WebGLShader -WebGLShaderPrecisionFormat -WebGLSync -WebGLTexture -WebGLTransformFeedback -WebGLUniformLocation -WebGLVertexArrayObject -WebSocket -WheelEvent -Window -Worker -WritableStream -XMLDocument -XMLHttpRequest -XMLHttpRequestEventTarget -XMLHttpRequestUpload -XMLSerializer -XPathEvaluator -XPathExpression -XPathResult -XSLTProcessor -__proto__ -_defineProperty -_define_property -_extends -_toConsumableArray -a -abbr -abs -abstract -accent-color -accept -accesskey -accessor -acos -acronym -action -activeborder -activecaption -activetext -actuate -add -address -after -aliceblue -align-content -align-items -align-self -align-tracks -all -alpha -altGlyph -altGlyphDef -altGlyphItem -alternate -alternate-reverse -altglyph -altglyphdef -altglyphitem -and -animate -animateColor -animateMotion -animateTransform -animatecolor -animatemotion -animatetransform -animation -animation-delay -animation-direction -animation-duration -animation-fill-mode -animation-iteration-count -animation-name -animation-play-state -animation-timeline -animation-timing-function -annotation -annotation-xml -anonymous -antiquewhite -any -appWorkspace -appearance -apple-touch-icon -apple-touch-icon-precomposed -applet -application/ecmascript -application/javascript -application/json -application/ld+json -application/x-javascript -application/xhtml+xml -apply -aqua -aquamarine -arcrole -area -arguments -aria-describedby -aria-labelledby -aria-owns -article -as -aside -asin -aspect-ratio -assert -asserts -async -atan -atan2 -attributeName -attributeType -attributename -attributetype -audio -auto -autocomplete -avoid -await -azimuth -azure -b -backdrop-filter -backface-visibility -background -background-attachment -background-blend-mode -background-clip -background-color -background-image -background-origin -background-position -background-position-x -background-position-y -background-repeat -background-size -backwards -base -baseFrequency -baseProfile -basefont -basefrequency -baseline -baseprofile -bdi -bdo -before -begin -beige -bgsound -big -bigint -bisque -black -blanchedalmond -blank -blink -block -block-overflow -block-size -blocking -blockquote -blue -blueviolet -body -bold -boolean -border-block-color -border-block-end -border-block-end-color -border-block-end-style -border-block-end-width -border-block-start -border-block-start-color -border-block-start-style -border-block-start-width -border-block-style -border-block-width -border-bottom-color -border-bottom-left-radius -border-bottom-right-radius -border-bottom-style -border-bottom-width -border-box -border-collapse -border-end-end-radius -border-end-start-radius -border-image -border-image-outset -border-image-repeat -border-image-slice -border-image-source -border-image-width -border-inline-color -border-inline-end -border-inline-end-color -border-inline-end-style -border-inline-end-width -border-inline-start -border-inline-start-color -border-inline-start-style -border-inline-start-width -border-inline-style -border-inline-width -border-left-color -border-left-style -border-left-width -border-radius -border-right-color -border-right-style -border-right-width -border-spacing -border-start-end-radius -border-start-start-radius -border-style -border-top-color -border-top-left-radius -border-top-right-radius -border-top-style -border-top-width -border-width -both -bottom -bottom-center -bottom-left -bottom-left-corner -bottom-right -bottom-right-corner -box-decoration-break -box-shadow -box-sizing -br -break -break-after -break-before -break-inside -brown -burlywood -button -buttonborder -buttonface -buttonhighlight -buttonshadow -buttontext -cadetblue -calc -calcMode -calcmode -call -canvas -canvastext -cap -caption -caption-side -captiontext -caret-color -caret-shape -case -catch -center -ch -character-variant -charset -chartreuse -chocolate -circle -cite -clamp -class -classid -clear -clip -clip-path -clipPath -clipPathUnits -clippath -clippathunits -cm -code -codebase -col -colgroup -collection -color -color-adjust -color-contrast -color-index -color-mix -color-profile -color-scheme -cols -colspan -column -column-count -column-fill -column-gap -column-reverse -column-rule -column-rule-color -column-rule-style -column-rule-width -column-span -column-width -columns -command -concat -const -constant -constructor -contain -contain-intrinsic-block-size -contain-intrinsic-height -contain-intrinsic-inline-size -contain-intrinsic-width -container -content -content-box -content-security-policy -contenteditable -continue -coral -cornflowerblue -cornsilk -cos -counter-increment -counter-reset -counter-set -counter-style -cqb -cqh -cqi -cqmax -cqmin -cqw -createClass -createReactClass -crimson -crossorigin -cubic-bezier -cue -cue-region -current -currentColor -currentcolor -cursor -custom-media -cyan -d -darkblue -darkcyan -darkgoldenrod -darkgray -darkgreen -darkgrey -darkkhaki -darkmagenta -darkolivegreen -darkorange -darkorchid -darkred -darksalmon -darkseagreen -darkslateblue -darkslategray -darkslategrey -darkturquoise -darkviolet -data -datalist -dd -debugger -declare -deeppink -deepskyblue -default -definitionURL -definitionurl -defs -deg -del -delete -desc -details -device-aspect-ratio -device-cmyk -device-height -device-width -dfn -dialog -diffuseConstant -diffuseconstant -dimgray -dimgrey -dir -direction -discard -disk -display -displayName -div -dl -do -document -dodgerblue -dpcm -dpi -dppx -dt -dvb -dvh -dvi -dvmax -dvmin -dvw -e -ease -ease-in -ease-in-out -ease-out -edgeMode -edgemode -element -ellipse -else -em -embed -embedded-opentype -empty-cells -encoding -end -enum -env -eval -even -ex -exp -export -exportparts -extends -face -false -feBlend -feColorMatrix -feComponentTransfer -feComposite -feConvolveMatrix -feDiffuseLighting -feDisplacementMap -feDistantLight -feDropShadow -feFlood -feFuncA -feFuncB -feFuncG -feFuncR -feGaussianBlur -feImage -feMerge -feMergeNode -feMorphology -feOffset -fePointLight -feSpecularLighting -feSpotLight -feTile -feTurbulence -feblend -fecolormatrix -fecomponenttransfer -fecomposite -feconvolvematrix -fediffuselighting -fedisplacementmap -fedistantlight -fedropshadow -feflood -fefunca -fefuncb -fefuncg -fefuncr -fegaussianblur -feimage -femerge -femergenode -femorphology -feoffset -fepointlight -fespecularlighting -fespotlight -fetile -feturbulence -field -fieldset -fieldtext -figcaption -figure -file -fill -fill-box -fill-opacity -filter -filterUnits -filterunits -finally -firebrick -first -first-child -first-letter -first-line -first-of-type -flat -flex -flex-basis -flex-direction -flex-flow -flex-grow -flex-shrink -flex-wrap -float -floralwhite -flow -flow-from -flow-into -flow-root -font -font-face -font-face-format -font-face-name -font-face-src -font-face-uri -font-feature-settings -font-feature-values -font-kerning -font-language-override -font-optical-sizing -font-palette-values -font-size -font-size-adjust -font-stretch -font-style -font-synthesis -font-variant -font-variant-alternates -font-variant-caps -font-variant-east-asian -font-variant-ligatures -font-variant-numeric -font-variant-position -font-variation-settings -font-weight -footer -for -forced-color-adjust -foreignObject -foreignobject -forestgreen -form -formaction -format -forwards -fr -frame -frameset -from -from-image -fuchsia -function -future -g -gainsboro -get -ghostwhite -global -glyph -glyphRef -glyphref -gold -goldenrod -grad -gradientTransform -gradientUnits -gradienttransform -gradientunits -gray -graytext -green -greenyellow -grey -grid -grid-auto-columns -grid-auto-flow -grid-auto-rows -grid-column-end -grid-column-gap -grid-column-start -grid-row-end -grid-row-gap -grid-row-start -grid-template -grid-template-areas -grid-template-columns -grid-template-rows -h1 -h2 -h3 -h4 -h5 -h6 -hanging-punctuation -has -head -header -headers -height -hgroup -highlight -highlighttext -historical-forms -hkern -honeydew -horizontal-tb -host -host-context -hotpink -hr -href -hsl -hsla -html -http-equiv -hwb -hyphenate-character -hyphens -hypot -hz -i -ic -icon -id -if -iframe -image -image-orientation -image-rendering -image-resolution -imagesizes -imagesrcset -ime-mode -img -implements -import -important -importmap -in -inactiveborder -inactivecaption -inactivecaptiontext -indianred -indigo -infer -infinite -infinity -infobackground -infotext -inherit -initial -initial-letter -initial-letter-align -inline -inline-block -inline-size -input -input-security -ins -inset -inset-block -inset-block-end -inset-block-start -inset-inline -inset-inline-end -inset-inline-start -instanceof -interface -intrinsic -is -isindex -isolation -itemid -itemprop -itemref -itemtype -iterator -ivory -jump-end -jump-start -justify-content -justify-items -justify-self -justify-tracks -kHz -kbd -kernelMatrix -kernelUnitLength -kernelmatrix -kernelunitlength -key -keyPoints -keySplines -keyTimes -keyframes -keygen -keyof -keypoints -keysplines -keytimes -keywords -khaki -khz -lab -label -lang -language -last-child -last-of-type -lavender -lavenderblush -lawngreen -layer -lch -left -left-bottom -left-middle -left-top -legacy -legend -lemonchiffon -length -lengthAdjust -lengthadjust -let -letter-spacing -lh -li -lightblue -lightcoral -lightcyan -lightgoldenrodyellow -lightgray -lightgreen -lightgrey -lightpink -lightsalmon -lightseagreen -lightskyblue -lightslategray -lightslategrey -lightsteelblue -lightyellow -lime -limegreen -limitingConeAngle -limitingconeangle -line -line-break -line-clamp -line-height -line-height-step -line-through -linear -linearGradient -lineargradient -linen -link -linktext -list-item -list-style-image -list-style-type -listing -local -log -longdesc -lr -lr-tb -ltr -luminance -lvb -lvh -lvi -lvmax -lvmin -lvw -magenta -main -malignmark -manual -map -margin -margin-block -margin-block-end -margin-block-start -margin-bottom -margin-inline -margin-inline-end -margin-inline-start -margin-left -margin-right -margin-top -margin-trim -mark -marker -markerHeight -markerUnits -markerWidth -markerheight -markerunits -markerwidth -marktext -maroon -marquee -mask -mask-border -mask-border-mode -mask-border-outset -mask-border-repeat -mask-border-slice -mask-border-source -mask-border-width -mask-clip -mask-composite -mask-image -mask-mode -mask-origin -mask-position -mask-repeat -mask-size -mask-type -maskContentUnits -maskUnits -maskcontentunits -maskunits -masonry-auto-flow -match-source -matches -math -math-depth -math-shift -math-style -matrix -matrix3d -max -max-aspect-ratio -max-block-size -max-color -max-color-index -max-device-aspect-ratio -max-device-height -max-device-width -max-height -max-inline-size -max-lines -max-monochrome -max-resolution -max-width -maxlength -media -medium -mediumaquamarine -mediumblue -mediumorchid -mediumpurple -mediumseagreen -mediumslateblue -mediumspringgreen -mediumturquoise -mediumvioletred -menu -menutext -meta -metadata -meter -mglyph -mi -midnightblue -min -min-aspect-ratio -min-block-size -min-color -min-color-index -min-device-aspect-ratio -min-device-height -min-device-width -min-height -min-inline-size -min-monochrome -min-resolution -min-width -mintcream -missing-glyph -mistyrose -mix-blend-mode -mixed -mm -mn -mo -moccasin -mod -module -monochrome -mozmm -mpath -ms -mtext -name -namespace -nan -nav -navajowhite -navy -nest -never -new -no-repeat -nobr -noembed -noframes -none -normal -noscript -not -nowrap -nth-child -nth-col -nth-last-child -nth-last-col -nth-last-of-type -nth-of-type -null -numOctaves -number -numoctaves -object -object-fit -object-position -odd -of -offset-anchor -offset-distance -offset-path -offset-position -offset-rotate -oklab -oklch -ol -oldlace -olive -olivedrab -onabort -onafterprint -onautocomplete -onautocompleteerror -onauxclick -onbeforematch -onbeforeprint -onbeforeunload -onbegin -onblur -oncancel -oncanplay -oncanplaythrough -onchange -onclick -onclose -oncontextlost -oncontextmenu -oncontextrestored -oncopy -oncuechange -oncut -ondblclick -ondrag -ondragend -ondragenter -ondragexit -ondragleave -ondragover -ondragstart -ondrop -ondurationchange -onemptied -onend -onended -onerror -onfocus -onformdata -onhashchange -oninput -oninvalid -onkeydown -onkeypress -onkeyup -onlanguagechange -onload -onloadeddata -onloadedmetadata -onloadstart -only -onmessage -onmessageerror -onmousedown -onmouseenter -onmouseleave -onmousemove -onmouseout -onmouseover -onmouseup -onmousewheel -onoffline -ononline -onpagehide -onpageshow -onpaste -onpause -onplay -onplaying -onpopstate -onprogress -onratechange -onreadystatechange -onrejectionhandled -onrepeat -onreset -onresize -onscroll -onsecuritypolicyviolation -onseeked -onseeking -onselect -onshow -onslotchange -onsort -onstalled -onstorage -onsubmit -onsuspend -ontimeupdate -ontoggle -onunhandledrejection -onunload -onvisibilitychange -onvolumechange -onwaiting -onwebkitanimationend -onwebkitanimationiteration -onwebkitanimationstart -onwebkittransitionend -onwheel -opacity -opentype -optgroup -option -or -orange -orangered -orchid -order -ornaments -orphans -out -outline-offset -outline-style -outline-width -output -over -overflow -overflow-anchor -overflow-block -overflow-clip-margin -overflow-inline -overflow-wrap -overflow-x -overflow-y -overline -override -overscroll-behavior -overscroll-behavior-block -overscroll-behavior-inline -overscroll-behavior-x -overscroll-behavior-y -p -pack -package -padding -padding-block -padding-block-end -padding-block-start -padding-bottom -padding-box -padding-inline -padding-inline-end -padding-inline-start -padding-left -padding-right -padding-top -page -page-break-after -page-break-before -page-break-inside -paint-order -palegoldenrod -palegreen -paleturquoise -palevioletred -panose-1 -papayawhip -param -part -past -path -pathLength -pathlength -pattern -patternContentUnits -patternTransform -patternUnits -patterncontentunits -patterntransform -patternunits -paused -pc -peachpuff -perspective -perspective-origin -peru -pi -picture -ping -pink -place-content -place-items -place-self -placeholder -plaintext -plum -pointer-events -points -pointsAtX -pointsAtY -pointsAtZ -pointsatx -pointsaty -pointsatz -polygon -polyline -position -poster -pow -powderblue -pre -preload -preserveAlpha -preserveAspectRatio -preservealpha -preserveaspectratio -primitiveUnits -primitiveunits -print-color-adjust -private -process -profile -progress -property -protected -pt -public -purple -px -q -rad -radialGradient -radialgradient -rb -rbc -rcap -rch -readonly -rebeccapurple -rect -red -refX -refY -refx -refy -region-fragment -rel -rem -repeat -repeat-x -repeat-y -repeatCount -repeatDur -repeatcount -repeatdur -require -requiredExtensions -requiredFeatures -requiredextensions -requiredfeatures -resize -resolution -return -reverse -revert -revert-layer -rex -rgb -rgba -ric -right -right-bottom -right-middle -right-top -rl -rlh -role -rosybrown -rotate -rotate3d -rotateX -rotateY -rotateZ -rotatex -rotatey -rotatez -round -row -row-gap -row-reverse -rows -rowspan -royalblue -rp -rt -rtc -rtl -ruby -ruby-align -ruby-base -ruby-merge -ruby-position -ruby-text -run-in -running -s -saddlebrown -salmon -samp -sandbox -sandybrown -satisfies -scale -scale3d -scaleX -scaleY -scaleZ -scalex -scaley -scalez -scope -script -scroll -scroll-behavior -scroll-margin -scroll-margin-block -scroll-margin-block-end -scroll-margin-block-start -scroll-margin-bottom -scroll-margin-inline -scroll-margin-inline-end -scroll-margin-inline-start -scroll-margin-left -scroll-margin-right -scroll-margin-top -scroll-padding -scroll-padding-block -scroll-padding-block-end -scroll-padding-block-start -scroll-padding-bottom -scroll-padding-inline -scroll-padding-inline-end -scroll-padding-inline-start -scroll-padding-left -scroll-padding-right -scroll-padding-top -scroll-snap-align -scroll-snap-coordinate -scroll-snap-destination -scroll-snap-points-x -scroll-snap-points-y -scroll-snap-stop -scroll-snap-type -scroll-snap-type-x -scroll-snap-type-y -scroll-timeline-axis -scroll-timeline-name -scrollbar -scrollbar-color -scrollbar-gutter -scrollbar-width -seagreen -seashell -section -select -selecteditem -selecteditemtext -selector -separate -set -shadow -shape-image-threshold -shape-margin -shape-outside -show -sideways-lr -sideways-rl -sienna -sign -silver -sin -size -sizes -skew -skewX -skewY -skewx -skewy -skyblue -slateblue -slategray -slategrey -slice -slot -slotted -small -snow -solid -solidColor -source -space -space-around -spacer -span -specularConstant -specularExponent -specularconstant -specularexponent -speculationrules -spreadMethod -spreadmethod -springgreen -sqrt -src -srcdoc -srcset -start -starting-style -startOffset -startoffset -static -stdDeviation -stddeviation -steelblue -step-end -step-start -steps -stitchTiles -stitchtiles -stop -strike -string -stroke-box -stroke-dasharray -stroke-opacity -strong -style -styleset -stylistic -sub -summary -sup -super -supports -surfaceScale -surfacescale -svb -svg -svh -svi -svmax -svmin -svw -swash -switch -symbol -systemLanguage -systemlanguage -tab-size -tabindex -table -table-caption -table-cell -table-layout -tableValues -tablevalues -tan -target -targetX -targetY -targetx -targety -tb -tb-lr -tb-rl -tbody -td -teal -template -text -text-align-last -text-combine-upright -text-decoration -text-decoration-color -text-decoration-line -text-decoration-skip -text-decoration-skip-ink -text-decoration-style -text-decoration-thickness -text-emphasis -text-emphasis-color -text-emphasis-position -text-emphasis-style -text-indent -text-justify -text-orientation -text-overflow -text-rendering -text-shadow -text-size-adjust -text-spacing -text-transform -text-underline-offset -text-underline-position -text/css -text/ecmascript -text/html -text/javascript -text/jscript -textLength -textPath -textarea -textlength -textpath -tfoot -th -thead -this -thistle -threeddarkshadow -threedface -threedhighlight -threedlightshadow -threedshadow -throw -time -title -to -toString -tomato -top -top-center -top-left -top-left-corner -top-right -top-right-corner -touch-action -tr -track -transform -transform-box -transform-origin -transform-style -transition -transition-delay -transition-duration -transition-property -transition-timing-function -translate -translate3d -translateX -translateY -translateZ -translatey -translatez -transparent -tref -true -truetype -try -tspan -tt -turn -turquoise -type -typeof -u -ul -undefined -under -underline -unicode-bidi -unique -unknown -unset -url -use -usemap -user-select -using -values -var -vb -vertical-align -vertical-lr -vertical-rl -vh -vi -video -view -view-box -viewBox -viewTarget -viewbox -viewport -viewtarget -violet -visitedtext -vkern -vmax -vmin -void -vw -wbr -weight -wheat -where -while -white -white-space -whitesmoke -widows -width -will-change -window -windowframe -windowtext -with -woff -woff2 -word-break -word-spacing -word-wrap -wrap -wrap-reverse -writing-mode -x -xChannelSelector -xchannelselector -xlink -xlink:actuate -xlink:arcrole -xlink:href -xlink:role -xlink:show -xlink:title -xlink:type -xml -xml:lang -xml:space -xmlns -xmlns:xlink -xmp -xyz -xyz-d50 -xyz-d65 -yChannelSelector -ychannelselector -yellow -yellowgreen -yield -z-index -zoom -zoomAndPan -zoomandpan From 388c6bd41514f0e54d592057f7e8642aecfd0b8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:33:17 +0900 Subject: [PATCH 07/24] docs --- crates/swc_allocator/src/alloc.rs | 6 ++++-- crates/swc_allocator/src/lib.rs | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/swc_allocator/src/alloc.rs b/crates/swc_allocator/src/alloc.rs index 6f0fafe811de..745e6a89f969 100644 --- a/crates/swc_allocator/src/alloc.rs +++ b/crates/swc_allocator/src/alloc.rs @@ -1,4 +1,4 @@ -use std::{alloc::Layout, cell::Cell, mem::transmute, ptr::NonNull}; +use std::{alloc::Layout, cell::Cell, ptr::NonNull}; use allocator_api2::alloc::Global; @@ -12,6 +12,8 @@ thread_local! { pub struct SwcAllocator(MemorySpace); impl SwcAllocator { + #[cfg(any(docsrs, feature = "scoped"))] + #[cfg_attr(docsrs, doc(cfg(feature = "scoped")))] /// Invokes `f` in a scope where the allocations are done in this allocator. #[inline(always)] pub fn scope<'a, F, R>(&'a self, f: F) -> R @@ -20,7 +22,7 @@ impl SwcAllocator { { let s = unsafe { // Safery: We are using a scoped API - transmute::<&'a SwcAllocator, &'static SwcAllocator>(self) + std::mem::transmute::<&'a SwcAllocator, &'static SwcAllocator>(self) }; ALLOC.set(Some(s)); diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index 3066fdd088f7..0da64c137b2a 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -3,6 +3,7 @@ //! API designed after [`oxc_allocator`](https://github.com/oxc-project/oxc/tree/725571aad193ec6ba779c820baeb4a7774533ed7/crates/oxc_allocator/src). #![allow(clippy::needless_doctest_main)] +#![cfg_attr(docsrs, feature(doc_cfg))] use std::ops::{Deref, DerefMut}; From 98625bddcad80548b754f1b8ec122a29e61ab085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:34:01 +0900 Subject: [PATCH 08/24] fix doc --- crates/swc_allocator/src/vec/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/swc_allocator/src/vec/mod.rs b/crates/swc_allocator/src/vec/mod.rs index d6297df85b08..6d2bb212b07e 100644 --- a/crates/swc_allocator/src/vec/mod.rs +++ b/crates/swc_allocator/src/vec/mod.rs @@ -105,7 +105,7 @@ impl Vec { /// * `capacity` needs to be the capacity that the pointer was allocated /// with. /// * The allocated size in bytes must be no larger than `isize::MAX`. See - /// the safety documentation of [`pointer::offset`]. + /// the safety documentation of [`std::pointer::offset`]. /// /// These requirements are always upheld by any `ptr` that has been /// allocated via `Vec`. Other allocation sources are allowed if the From 9c11cd2e03d8f89c3df4ee295314332ba26b29db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:36:26 +0900 Subject: [PATCH 09/24] Remove `MemorySpace` --- crates/swc_allocator/src/alloc.rs | 39 +++++++++++++++++++++++++++---- crates/swc_allocator/src/lib.rs | 29 ----------------------- 2 files changed, 35 insertions(+), 33 deletions(-) diff --git a/crates/swc_allocator/src/alloc.rs b/crates/swc_allocator/src/alloc.rs index 745e6a89f969..0f2d57e4bb97 100644 --- a/crates/swc_allocator/src/alloc.rs +++ b/crates/swc_allocator/src/alloc.rs @@ -1,15 +1,23 @@ -use std::{alloc::Layout, cell::Cell, ptr::NonNull}; +use std::{ + alloc::Layout, + cell::Cell, + ops::{Deref, DerefMut}, + ptr::NonNull, +}; use allocator_api2::alloc::Global; +use bumpalo::Bump; -use crate::{FastAlloc, MemorySpace}; +use crate::FastAlloc; thread_local! { static ALLOC: Cell> = const { Cell::new(None) }; } #[derive(Default)] -pub struct SwcAllocator(MemorySpace); +pub struct SwcAllocator { + alloc: Bump, +} impl SwcAllocator { #[cfg(any(docsrs, feature = "scoped"))] @@ -51,7 +59,10 @@ impl FastAlloc { f: impl FnOnce(&dyn allocator_api2::alloc::Allocator, bool) -> T, ) -> T { if let Some(arena) = &self.alloc { - f((&&*arena.0) as &dyn allocator_api2::alloc::Allocator, true) + f( + (&&arena.alloc) as &dyn allocator_api2::alloc::Allocator, + true, + ) } else { f(&allocator_api2::alloc::Global, false) } @@ -161,3 +172,23 @@ unsafe impl allocator_api2::alloc::Allocator for FastAlloc { self } } + +impl From for SwcAllocator { + fn from(alloc: Bump) -> Self { + Self { alloc } + } +} + +impl Deref for SwcAllocator { + type Target = Bump; + + fn deref(&self) -> &Bump { + &self.alloc + } +} + +impl DerefMut for SwcAllocator { + fn deref_mut(&mut self) -> &mut Bump { + &mut self.alloc + } +} diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index 0da64c137b2a..173e9ab89bfb 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -5,10 +5,6 @@ #![allow(clippy::needless_doctest_main)] #![cfg_attr(docsrs, feature(doc_cfg))] -use std::ops::{Deref, DerefMut}; - -use bumpalo::Bump; - pub use crate::alloc::SwcAllocator; mod alloc; @@ -19,28 +15,3 @@ pub mod vec; pub struct FastAlloc { alloc: Option<&'static SwcAllocator>, } - -#[derive(Default)] -struct MemorySpace { - alloc: Bump, -} - -impl From for MemorySpace { - fn from(alloc: Bump) -> Self { - Self { alloc } - } -} - -impl Deref for MemorySpace { - type Target = Bump; - - fn deref(&self) -> &Bump { - &self.alloc - } -} - -impl DerefMut for MemorySpace { - fn deref_mut(&mut self) -> &mut Bump { - &mut self.alloc - } -} From f3c20c1b91705248565aec79e5dfef8698844889 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:37:13 +0900 Subject: [PATCH 10/24] features --- crates/swc_allocator/Cargo.toml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/swc_allocator/Cargo.toml b/crates/swc_allocator/Cargo.toml index d9df7f6c8249..5a7bb60e6f5a 100644 --- a/crates/swc_allocator/Cargo.toml +++ b/crates/swc_allocator/Cargo.toml @@ -40,5 +40,6 @@ swc_malloc = { version = "0.5.10", path = "../swc_malloc" } [[bench]] -harness = false -name = "bench" +features = ["scoped"] +harness = false +name = "bench" From 7c86279a8041bec043e413e23600d634397fc544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:37:56 +0900 Subject: [PATCH 11/24] Copy --- crates/swc_allocator/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index 173e9ab89bfb..e9e87f1bba51 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -11,7 +11,7 @@ mod alloc; pub mod boxed; pub mod vec; -#[derive(Clone)] +#[derive(Clone, Copy)] pub struct FastAlloc { alloc: Option<&'static SwcAllocator>, } From ec0d1d1cb44340745bf64cf3988c4770e5559622 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:38:20 +0900 Subject: [PATCH 12/24] Rename --- crates/swc_allocator/benches/bench.rs | 6 +++--- crates/swc_allocator/src/alloc.rs | 14 +++++++------- crates/swc_allocator/src/lib.rs | 4 ++-- crates/swc_allocator/tests/apis.rs | 4 ++-- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/swc_allocator/benches/bench.rs b/crates/swc_allocator/benches/bench.rs index 55deaef17ab0..644b63cd3a40 100644 --- a/crates/swc_allocator/benches/bench.rs +++ b/crates/swc_allocator/benches/bench.rs @@ -1,7 +1,7 @@ extern crate swc_malloc; use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion}; -use swc_allocator::{FastAlloc, SwcAllocator}; +use swc_allocator::{Allocator, FastAlloc}; fn bench_alloc(c: &mut Criterion) { fn direct_alloc_std(b: &mut Bencher, times: usize) { @@ -40,7 +40,7 @@ fn bench_alloc(c: &mut Criterion) { fn direct_alloc_scoped(b: &mut Bencher, times: usize) { b.iter(|| { - let allocator = SwcAllocator::default(); + let allocator = Allocator::default(); allocator.scope(|| { let mut vec = swc_allocator::vec::Vec::new(); @@ -56,7 +56,7 @@ fn bench_alloc(c: &mut Criterion) { fn fast_alloc_scoped(b: &mut Bencher, times: usize) { b.iter(|| { - SwcAllocator::default().scope(|| { + Allocator::default().scope(|| { let allocator = FastAlloc::default(); let mut vec = allocator.vec(); diff --git a/crates/swc_allocator/src/alloc.rs b/crates/swc_allocator/src/alloc.rs index 0f2d57e4bb97..a32e516e3de9 100644 --- a/crates/swc_allocator/src/alloc.rs +++ b/crates/swc_allocator/src/alloc.rs @@ -11,15 +11,15 @@ use bumpalo::Bump; use crate::FastAlloc; thread_local! { - static ALLOC: Cell> = const { Cell::new(None) }; + static ALLOC: Cell> = const { Cell::new(None) }; } #[derive(Default)] -pub struct SwcAllocator { +pub struct Allocator { alloc: Bump, } -impl SwcAllocator { +impl Allocator { #[cfg(any(docsrs, feature = "scoped"))] #[cfg_attr(docsrs, doc(cfg(feature = "scoped")))] /// Invokes `f` in a scope where the allocations are done in this allocator. @@ -30,7 +30,7 @@ impl SwcAllocator { { let s = unsafe { // Safery: We are using a scoped API - std::mem::transmute::<&'a SwcAllocator, &'static SwcAllocator>(self) + std::mem::transmute::<&'a Allocator, &'static Allocator>(self) }; ALLOC.set(Some(s)); @@ -173,13 +173,13 @@ unsafe impl allocator_api2::alloc::Allocator for FastAlloc { } } -impl From for SwcAllocator { +impl From for Allocator { fn from(alloc: Bump) -> Self { Self { alloc } } } -impl Deref for SwcAllocator { +impl Deref for Allocator { type Target = Bump; fn deref(&self) -> &Bump { @@ -187,7 +187,7 @@ impl Deref for SwcAllocator { } } -impl DerefMut for SwcAllocator { +impl DerefMut for Allocator { fn deref_mut(&mut self) -> &mut Bump { &mut self.alloc } diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index e9e87f1bba51..5e49946a70c1 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -5,7 +5,7 @@ #![allow(clippy::needless_doctest_main)] #![cfg_attr(docsrs, feature(doc_cfg))] -pub use crate::alloc::SwcAllocator; +pub use crate::alloc::Allocator; mod alloc; pub mod boxed; @@ -13,5 +13,5 @@ pub mod vec; #[derive(Clone, Copy)] pub struct FastAlloc { - alloc: Option<&'static SwcAllocator>, + alloc: Option<&'static Allocator>, } diff --git a/crates/swc_allocator/tests/apis.rs b/crates/swc_allocator/tests/apis.rs index a613046b0fbe..377251cd50f2 100644 --- a/crates/swc_allocator/tests/apis.rs +++ b/crates/swc_allocator/tests/apis.rs @@ -1,5 +1,5 @@ use criterion::black_box; -use swc_allocator::SwcAllocator; +use swc_allocator::Allocator; #[test] fn direct_alloc_std() { @@ -22,7 +22,7 @@ fn direct_alloc_no_scope() { #[test] fn direct_alloc_in_scope() { - let allocator = SwcAllocator::default(); + let allocator = Allocator::default(); allocator.scope(|| { let mut vec = swc_allocator::vec::Vec::new(); From c6ea41b873d5b9a38e6802e29a44bd5139ab1cbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:41:23 +0900 Subject: [PATCH 13/24] doc --- crates/swc_allocator/src/lib.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index 5e49946a70c1..ba6a9e992f48 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -11,6 +11,16 @@ mod alloc; pub mod boxed; pub mod vec; +/// Fast allocator. +/// +/// +/// # Misc +/// +/// It implements [`allocator_api2::alloc::Allocator`]. So it can be used as the +/// second argument for [`allocator_api2::boxed::Box`] and +/// [`allocator_api2::vec::Vec`]. But you should prefer using +/// [`crate::boxed::Box`] and [`crate::vec::Vec`], which is a wrapper around the +/// original types. #[derive(Clone, Copy)] pub struct FastAlloc { alloc: Option<&'static Allocator>, From 2687051814c5b19797103bf4118b563917daf5d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:44:47 +0900 Subject: [PATCH 14/24] Change FastAlloc API --- crates/swc_allocator/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index ba6a9e992f48..5c714c017450 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -11,7 +11,8 @@ mod alloc; pub mod boxed; pub mod vec; -/// Fast allocator. +/// Fast allocator, effectively working as a cache. +/// /// /// /// # Misc From d8f2d0fb3a66073dde282261ce302c5c43994e26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:48:26 +0900 Subject: [PATCH 15/24] More work --- crates/swc_allocator/benches/bench.rs | 26 +++++++++++-------------- crates/swc_allocator/src/alloc.rs | 5 ++--- crates/swc_allocator/src/boxed/mod.rs | 19 ++++++------------ crates/swc_allocator/src/vec/mod.rs | 28 ++++++++++----------------- 4 files changed, 29 insertions(+), 49 deletions(-) diff --git a/crates/swc_allocator/benches/bench.rs b/crates/swc_allocator/benches/bench.rs index 644b63cd3a40..355e6f939240 100644 --- a/crates/swc_allocator/benches/bench.rs +++ b/crates/swc_allocator/benches/bench.rs @@ -1,7 +1,7 @@ extern crate swc_malloc; use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion}; -use swc_allocator::{Allocator, FastAlloc}; +use swc_allocator::{boxed::Box as SwcBox, vec::Vec as SwcVec, Allocator, FastAlloc}; fn bench_alloc(c: &mut Criterion) { fn direct_alloc_std(b: &mut Bencher, times: usize) { @@ -16,10 +16,9 @@ fn bench_alloc(c: &mut Criterion) { fn direct_alloc_no_scope(b: &mut Bencher, times: usize) { b.iter(|| { - let mut vec = swc_allocator::vec::Vec::new(); + let mut vec = SwcVec::new(); for i in 0..times { - let item: swc_allocator::boxed::Box = - black_box(swc_allocator::boxed::Box::new(black_box(i))); + let item: SwcBox = black_box(SwcBox::new(black_box(i))); vec.push(item); } }) @@ -27,12 +26,11 @@ fn bench_alloc(c: &mut Criterion) { fn fast_alloc_no_scope(b: &mut Bencher, times: usize) { b.iter(|| { - let allocator = FastAlloc::default(); + let alloc = FastAlloc::default(); - let mut vec = allocator.vec(); + let mut vec = SwcVec::new_in(alloc); for i in 0..times { - let item: swc_allocator::boxed::Box = - black_box(allocator.alloc(black_box(i))); + let item: SwcBox = black_box(SwcBox::new_in(black_box(i), alloc)); vec.push(item); } }) @@ -43,11 +41,10 @@ fn bench_alloc(c: &mut Criterion) { let allocator = Allocator::default(); allocator.scope(|| { - let mut vec = swc_allocator::vec::Vec::new(); + let mut vec = SwcVec::new(); for i in 0..times { - let item: swc_allocator::boxed::Box = - black_box(swc_allocator::boxed::Box::new(black_box(i))); + let item: SwcBox = black_box(SwcBox::new(black_box(i))); vec.push(item); } }); @@ -57,13 +54,12 @@ fn bench_alloc(c: &mut Criterion) { fn fast_alloc_scoped(b: &mut Bencher, times: usize) { b.iter(|| { Allocator::default().scope(|| { - let allocator = FastAlloc::default(); + let alloc = FastAlloc::default(); - let mut vec = allocator.vec(); + let mut vec = SwcVec::new_in(alloc); for i in 0..times { - let item: swc_allocator::boxed::Box = - black_box(allocator.alloc(black_box(i))); + let item: SwcBox = black_box(SwcBox::new_in(black_box(i), alloc)); vec.push(item); } }); diff --git a/crates/swc_allocator/src/alloc.rs b/crates/swc_allocator/src/alloc.rs index a32e516e3de9..045bfab99170 100644 --- a/crates/swc_allocator/src/alloc.rs +++ b/crates/swc_allocator/src/alloc.rs @@ -1,6 +1,7 @@ use std::{ alloc::Layout, cell::Cell, + mem::transmute, ops::{Deref, DerefMut}, ptr::NonNull, }; @@ -20,8 +21,6 @@ pub struct Allocator { } impl Allocator { - #[cfg(any(docsrs, feature = "scoped"))] - #[cfg_attr(docsrs, doc(cfg(feature = "scoped")))] /// Invokes `f` in a scope where the allocations are done in this allocator. #[inline(always)] pub fn scope<'a, F, R>(&'a self, f: F) -> R @@ -30,7 +29,7 @@ impl Allocator { { let s = unsafe { // Safery: We are using a scoped API - std::mem::transmute::<&'a Allocator, &'static Allocator>(self) + transmute::<&'a Allocator, &'static Allocator>(self) }; ALLOC.set(Some(s)); diff --git a/crates/swc_allocator/src/boxed/mod.rs b/crates/swc_allocator/src/boxed/mod.rs index 8ea7fd38c2de..65f0ceb54e60 100644 --- a/crates/swc_allocator/src/boxed/mod.rs +++ b/crates/swc_allocator/src/boxed/mod.rs @@ -49,15 +49,14 @@ where } impl Box { - /// Allocates a new box with `value`. - /// - /// See [`std::boxed::Box::new`]. #[inline(always)] pub fn new(value: T) -> Self { - Self(allocator_api2::boxed::Box::new_in( - value, - FastAlloc::default(), - )) + Self::new_in(value, Default::default()) + } + + #[inline(always)] + pub fn new_in(value: T, alloc: FastAlloc) -> Self { + Self(allocator_api2::boxed::Box::new_in(value, alloc)) } /// Moves the value out of the box. @@ -627,9 +626,3 @@ where self.0.len() } } - -impl FastAlloc { - pub fn alloc(&self, t: T) -> Box { - Box(allocator_api2::boxed::Box::new_in(t, self.clone())) - } -} diff --git a/crates/swc_allocator/src/vec/mod.rs b/crates/swc_allocator/src/vec/mod.rs index 6d2bb212b07e..f7b1224b1484 100644 --- a/crates/swc_allocator/src/vec/mod.rs +++ b/crates/swc_allocator/src/vec/mod.rs @@ -15,14 +15,19 @@ pub struct Vec(allocator_api2::vec::Vec); impl Vec { pub fn new() -> Self { - Default::default() + Self::new_in(Default::default()) + } + + pub fn new_in(alloc: FastAlloc) -> Self { + Self(allocator_api2::vec::Vec::new_in(alloc)) } pub fn with_capacity(capacity: usize) -> Self { - Self(allocator_api2::vec::Vec::with_capacity_in( - capacity, - FastAlloc::default(), - )) + Self::with_capacity_in(capacity, Default::default()) + } + + pub fn with_capacity_in(capacity: usize, alloc: FastAlloc) -> Self { + Self(allocator_api2::vec::Vec::with_capacity_in(capacity, alloc)) } /// Converts the vector into [`Box<[T]>`][owned slice]. @@ -243,16 +248,3 @@ impl Extend for Vec { self.0.extend(iter) } } - -impl FastAlloc { - pub fn vec(&self) -> Vec { - Vec(allocator_api2::vec::Vec::new_in(self.clone())) - } - - pub fn vec_with_capacity(&self, capacity: usize) -> Vec { - Vec(allocator_api2::vec::Vec::with_capacity_in( - capacity, - self.clone(), - )) - } -} From ff0dc6083faad2a3871bce37e69b9c8d5de200da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:51:57 +0900 Subject: [PATCH 16/24] Doc --- crates/swc_allocator/src/lib.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index 5c714c017450..4f144571264c 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -4,6 +4,7 @@ #![allow(clippy::needless_doctest_main)] #![cfg_attr(docsrs, feature(doc_cfg))] +#![deny(missing_docs)] pub use crate::alloc::Allocator; @@ -13,6 +14,15 @@ pub mod vec; /// Fast allocator, effectively working as a cache. /// +/// This type implements [Default] and [Copy]. This type is intended to stored +/// in a variable or a field in a struct before allocating code, and used as the +/// seocnd argument in [crate::boxed::Box::new_in] and +/// [crate::vec::Vec::new_in]. +/// +/// [crate::boxed::Box::new] and [crate::vec::Vec::new] are slower than using +/// this field because they use [FastAlloc::default] internally, which is slower +/// than store [FastAlloc] in a variable. +/// /// /// /// # Misc From f918c4f76945921ce7e120b9aeb94466604f8262 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:52:02 +0900 Subject: [PATCH 17/24] dco --- crates/swc_allocator/src/boxed/mod.rs | 2 ++ crates/swc_allocator/src/vec/mod.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/crates/swc_allocator/src/boxed/mod.rs b/crates/swc_allocator/src/boxed/mod.rs index 65f0ceb54e60..6beba6c03bc9 100644 --- a/crates/swc_allocator/src/boxed/mod.rs +++ b/crates/swc_allocator/src/boxed/mod.rs @@ -1,3 +1,5 @@ +//! Faster box type. + use std::{ borrow::{Borrow, BorrowMut}, fmt::{self, Debug, Display, Formatter}, diff --git a/crates/swc_allocator/src/vec/mod.rs b/crates/swc_allocator/src/vec/mod.rs index f7b1224b1484..d170269bb4c3 100644 --- a/crates/swc_allocator/src/vec/mod.rs +++ b/crates/swc_allocator/src/vec/mod.rs @@ -1,3 +1,5 @@ +//! Faster vec type. + use std::ops::{Deref, DerefMut}; #[cfg(feature = "rkyv")] From f0510d441e230b689701e4343ffb915679acaaeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:53:23 +0900 Subject: [PATCH 18/24] doc --- crates/swc_allocator/src/boxed/mod.rs | 29 ++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/crates/swc_allocator/src/boxed/mod.rs b/crates/swc_allocator/src/boxed/mod.rs index 6beba6c03bc9..7d14a47b41f2 100644 --- a/crates/swc_allocator/src/boxed/mod.rs +++ b/crates/swc_allocator/src/boxed/mod.rs @@ -16,13 +16,6 @@ mod rkyv; #[cfg(feature = "serde")] mod serde; -/// A special `Box` which has size of [`std::boxed::Box`] but **may** be -/// allocated with a custom allocator. -/// -/// -/// # Representation -/// -/// The last bit is 1 if the box is allocated with a custom allocator. #[repr(transparent)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Box(pub(crate) allocator_api2::boxed::Box); @@ -51,11 +44,33 @@ where } impl Box { + /// Allocates memory on the heap and then places `x` into it. + /// + /// This doesn't actually allocate if `T` is zero-sized. + /// + /// # Examples + /// + /// ``` + /// let five = Box::new(5); + /// ``` #[inline(always)] pub fn new(value: T) -> Self { Self::new_in(value, Default::default()) } + /// Allocates memory in the given allocator then places `x` into it. + /// + /// This doesn't actually allocate if `T` is zero-sized. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_api)] + /// + /// use std::alloc::System; + /// + /// let five = Box::new_in(5, System); + /// ``` #[inline(always)] pub fn new_in(value: T, alloc: FastAlloc) -> Self { Self(allocator_api2::boxed::Box::new_in(value, alloc)) From 06d52e09d1d4902113910069430bc6c605044142 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:54:18 +0900 Subject: [PATCH 19/24] doc --- crates/swc_allocator/src/boxed/mod.rs | 1 + crates/swc_allocator/src/vec/mod.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/crates/swc_allocator/src/boxed/mod.rs b/crates/swc_allocator/src/boxed/mod.rs index 7d14a47b41f2..b2774bc6f805 100644 --- a/crates/swc_allocator/src/boxed/mod.rs +++ b/crates/swc_allocator/src/boxed/mod.rs @@ -16,6 +16,7 @@ mod rkyv; #[cfg(feature = "serde")] mod serde; +/// Faster alterantive for [`std::boxed::Box`]. #[repr(transparent)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Box(pub(crate) allocator_api2::boxed::Box); diff --git a/crates/swc_allocator/src/vec/mod.rs b/crates/swc_allocator/src/vec/mod.rs index d170269bb4c3..8c4d5a1754fe 100644 --- a/crates/swc_allocator/src/vec/mod.rs +++ b/crates/swc_allocator/src/vec/mod.rs @@ -7,6 +7,7 @@ mod rkyv; use crate::{boxed::Box, FastAlloc}; +/// Faster version of [`std::vec::Vec`]. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] #[cfg_attr( From 219fe6e22cd91f44e7b61c6d60b3baf2ed5ddb83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:56:23 +0900 Subject: [PATCH 20/24] doc --- crates/swc_allocator/src/boxed/mod.rs | 2 + crates/swc_allocator/src/vec/mod.rs | 130 ++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) diff --git a/crates/swc_allocator/src/boxed/mod.rs b/crates/swc_allocator/src/boxed/mod.rs index b2774bc6f805..7e327f0af657 100644 --- a/crates/swc_allocator/src/boxed/mod.rs +++ b/crates/swc_allocator/src/boxed/mod.rs @@ -54,6 +54,8 @@ impl Box { /// ``` /// let five = Box::new(5); /// ``` + /// + /// Note: This is slower than using [Self::new_in] with cached [FastAlloc]. #[inline(always)] pub fn new(value: T) -> Self { Self::new_in(value, Default::default()) diff --git a/crates/swc_allocator/src/vec/mod.rs b/crates/swc_allocator/src/vec/mod.rs index 8c4d5a1754fe..9c2eb54f5d59 100644 --- a/crates/swc_allocator/src/vec/mod.rs +++ b/crates/swc_allocator/src/vec/mod.rs @@ -17,18 +17,148 @@ use crate::{boxed::Box, FastAlloc}; pub struct Vec(allocator_api2::vec::Vec); impl Vec { + /// Constructs a new, empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + /// + /// # Examples + /// + /// ``` + /// # #![allow(unused_mut)] + /// let mut vec: Vec = Vec::new(); + /// ``` + /// + /// Note: This is slower than using [Self::new_in] with cached [FastAlloc]. pub fn new() -> Self { Self::new_in(Default::default()) } + /// Constructs a new, empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// # #[allow(unused_mut)] + /// let mut vec: Vec = Vec::new_in(System); + /// ``` pub fn new_in(alloc: FastAlloc) -> Self { Self(allocator_api2::vec::Vec::new_in(alloc)) } + /// Constructs a new, empty `Vec` with at least the specified capacity. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is 0, the vector will not allocate. + /// + /// It is important to note that although the returned vector has the + /// minimum *capacity* specified, the vector will have a zero *length*. For + /// an explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// If it is important to know the exact allocated capacity of a `Vec`, + /// always use the [`capacity`] method after construction. + /// + /// For `Vec` where `T` is a zero-sized type, there will be no allocation + /// and the capacity will always be `usize::MAX`. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// [`capacity`]: Vec::capacity + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` bytes. + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert!(vec.capacity() >= 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert!(vec.capacity() >= 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// // A vector of a zero-sized type will always over-allocate, since no + /// // allocation is necessary + /// let vec_units = Vec::<()>::with_capacity(10); + /// assert_eq!(vec_units.capacity(), usize::MAX); + /// ``` + /// + /// Note: This is slower than using [Self::with_capacity_in] with cached + /// [FastAlloc]. pub fn with_capacity(capacity: usize) -> Self { Self::with_capacity_in(capacity, Default::default()) } + /// Constructs a new, empty `Vec` with at least the specified capacity + /// with the provided allocator. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is 0, the vector will not allocate. + /// + /// It is important to note that although the returned vector has the + /// minimum *capacity* specified, the vector will have a zero *length*. For + /// an explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// If it is important to know the exact allocated capacity of a `Vec`, + /// always use the [`capacity`] method after construction. + /// + /// For `Vec` where `T` is a zero-sized type, there will be no + /// allocation and the capacity will always be `usize::MAX`. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// [`capacity`]: Vec::capacity + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` bytes. + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut vec = Vec::with_capacity_in(10, System); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert_eq!(vec.capacity(), 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert_eq!(vec.capacity(), 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// // A vector of a zero-sized type will always over-allocate, since no + /// // allocation is necessary + /// let vec_units = Vec::<(), System>::with_capacity_in(10, System); + /// assert_eq!(vec_units.capacity(), usize::MAX); + /// ``` pub fn with_capacity_in(capacity: usize, alloc: FastAlloc) -> Self { Self(allocator_api2::vec::Vec::with_capacity_in(capacity, alloc)) } From c51efc4608115684b94fb3a492988149701f0b4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 14:57:08 +0900 Subject: [PATCH 21/24] doc --- crates/swc_allocator/src/alloc.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/swc_allocator/src/alloc.rs b/crates/swc_allocator/src/alloc.rs index 045bfab99170..70a5f578a017 100644 --- a/crates/swc_allocator/src/alloc.rs +++ b/crates/swc_allocator/src/alloc.rs @@ -15,6 +15,7 @@ thread_local! { static ALLOC: Cell> = const { Cell::new(None) }; } +/// The actual storage for [FastAlloc]. #[derive(Default)] pub struct Allocator { alloc: Bump, From 94208ebfb995b17aa8e419ad045c4546893810c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 15:03:33 +0900 Subject: [PATCH 22/24] fix typescript wasm --- bindings/Cargo.lock | 7 +++++-- bindings/binding_typescript_wasm/Cargo.toml | 2 +- bindings/binding_typescript_wasm/src/lib.rs | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/bindings/Cargo.lock b/bindings/Cargo.lock index d330a9e67619..d128834ffd2e 100644 --- a/bindings/Cargo.lock +++ b/bindings/Cargo.lock @@ -3828,15 +3828,18 @@ dependencies = [ [[package]] name = "swc_fast_ts_strip" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fa68aa0e8b9a36759139523f2980d17e86b5afeef1441b0c4db0cf220dd8ec1" +checksum = "9fc53e8aa24cc7ec9491807672a56d4b3dd4ae8f1df072c9971025ecd4b07ab1" dependencies = [ "anyhow", "serde", "swc_common", "swc_ecma_ast", + "swc_ecma_codegen", "swc_ecma_parser", + "swc_ecma_transforms_base", + "swc_ecma_transforms_typescript", "swc_ecma_visit", ] diff --git a/bindings/binding_typescript_wasm/Cargo.toml b/bindings/binding_typescript_wasm/Cargo.toml index 00afbfcc66e7..7a2daa52db2d 100644 --- a/bindings/binding_typescript_wasm/Cargo.toml +++ b/bindings/binding_typescript_wasm/Cargo.toml @@ -22,7 +22,7 @@ serde-wasm-bindgen = "0.4.5" serde_json = "1.0.120" swc_common = "0.35.0" swc_error_reporters = "0.19.0" -swc_fast_ts_strip = "0.2.0" +swc_fast_ts_strip = "0.2.1" tracing = { version = "0.1.37", features = ["max_level_off"] } wasm-bindgen = { version = "0.2.82", features = ["enable-interning"] } wasm-bindgen-futures = { version = "0.4.41" } diff --git a/bindings/binding_typescript_wasm/src/lib.rs b/bindings/binding_typescript_wasm/src/lib.rs index 7b4fc94d5b8c..32a779213143 100644 --- a/bindings/binding_typescript_wasm/src/lib.rs +++ b/bindings/binding_typescript_wasm/src/lib.rs @@ -1,7 +1,7 @@ use anyhow::Error; use swc_common::{errors::ColorConfig, sync::Lrc, SourceMap, GLOBALS}; use swc_error_reporters::handler::{try_with_handler, HandlerOpts}; -use swc_fast_ts_strip::Options; +use swc_fast_ts_strip::{Options, TransformOutput}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::{ future_to_promise, @@ -34,7 +34,7 @@ pub fn transform_sync(input: JsString, options: JsValue) -> Result Result { +fn operate(input: String, options: Options) -> Result { let cm = Lrc::new(SourceMap::default()); try_with_handler( From 7c1f62baea0ada85334c2b688548d55367d2805d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 15:15:12 +0900 Subject: [PATCH 23/24] doc --- crates/swc_allocator/src/vec/mod.rs | 38 ++--------------------------- 1 file changed, 2 insertions(+), 36 deletions(-) diff --git a/crates/swc_allocator/src/vec/mod.rs b/crates/swc_allocator/src/vec/mod.rs index 9c2eb54f5d59..a25dd2409387 100644 --- a/crates/swc_allocator/src/vec/mod.rs +++ b/crates/swc_allocator/src/vec/mod.rs @@ -37,14 +37,7 @@ impl Vec { /// /// The vector will not allocate until elements are pushed onto it. /// - /// # Examples - /// - /// ``` - /// use std::alloc::System; - /// - /// # #[allow(unused_mut)] - /// let mut vec: Vec = Vec::new_in(System); - /// ``` + /// See [std::vec::Vec::new_in] for more information. pub fn new_in(alloc: FastAlloc) -> Self { Self(allocator_api2::vec::Vec::new_in(alloc)) } @@ -131,34 +124,7 @@ impl Vec { /// /// Panics if the new capacity exceeds `isize::MAX` bytes. /// - /// # Examples - /// - /// ``` - /// use std::alloc::System; - /// - /// let mut vec = Vec::with_capacity_in(10, System); - /// - /// // The vector contains no items, even though it has capacity for more - /// assert_eq!(vec.len(), 0); - /// assert_eq!(vec.capacity(), 10); - /// - /// // These are all done without reallocating... - /// for i in 0..10 { - /// vec.push(i); - /// } - /// assert_eq!(vec.len(), 10); - /// assert_eq!(vec.capacity(), 10); - /// - /// // ...but this may make the vector reallocate - /// vec.push(11); - /// assert_eq!(vec.len(), 11); - /// assert!(vec.capacity() >= 11); - /// - /// // A vector of a zero-sized type will always over-allocate, since no - /// // allocation is necessary - /// let vec_units = Vec::<(), System>::with_capacity_in(10, System); - /// assert_eq!(vec_units.capacity(), usize::MAX); - /// ``` + /// See [std::vec::Vec::with_capacity_in] for more information. pub fn with_capacity_in(capacity: usize, alloc: FastAlloc) -> Self { Self(allocator_api2::vec::Vec::with_capacity_in(capacity, alloc)) } From c16042a56ad6a0bf32904433bea78e5080b858d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EB=8F=99=EC=9C=A4=20=28Donny=29?= Date: Mon, 15 Jul 2024 15:15:21 +0900 Subject: [PATCH 24/24] Update jest snapshot --- .../__tests__/__snapshots__/transform.js.snap | 70 ++++++++++++++----- 1 file changed, 51 insertions(+), 19 deletions(-) diff --git a/bindings/binding_typescript_wasm/__tests__/__snapshots__/transform.js.snap b/bindings/binding_typescript_wasm/__tests__/__snapshots__/transform.js.snap index a0c9bd4e77c8..7b5b95a0cc17 100644 --- a/bindings/binding_typescript_wasm/__tests__/__snapshots__/transform.js.snap +++ b/bindings/binding_typescript_wasm/__tests__/__snapshots__/transform.js.snap @@ -1,53 +1,82 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`transform in strip-only mode should remove declare enum 1`] = `" "`; +exports[`transform in strip-only mode should remove declare enum 1`] = ` +{ + "code": " ", + "map": undefined, +} +`; exports[`transform in strip-only mode should remove declare enum 2`] = ` -" +{ + "code": " - " + ", + "map": undefined, +} `; exports[`transform in strip-only mode should remove declare enum 3`] = ` -" +{ + "code": " - " + ", + "map": undefined, +} `; exports[`transform in strip-only mode should strip complex expressions 1`] = ` -"const foo = { +{ + "code": "const foo = { foo: 1 , bar: "bar" , } ; - const bar = "bar";" + const bar = "bar";", + "map": undefined, +} `; exports[`transform in strip-only mode should strip nonnull assertions 1`] = ` -"const foo = 1 ; - const bar = "bar";" +{ + "code": "const foo = 1 ; + const bar = "bar";", + "map": undefined, +} `; exports[`transform in strip-only mode should strip satisfies 1`] = ` -"const foo = 1 ; - const bar = "bar";" +{ + "code": "const foo = 1 ; + const bar = "bar";", + "map": undefined, +} `; exports[`transform in strip-only mode should strip type annotations 1`] = ` -"const foo = 1; - const bar = "bar";" +{ + "code": "const foo = 1; + const bar = "bar";", + "map": undefined, +} `; exports[`transform in strip-only mode should strip type assertions 1`] = ` -"const foo = 1 ; - const bar = "bar";" +{ + "code": "const foo = 1 ; + const bar = "bar";", + "map": undefined, +} `; exports[`transform in strip-only mode should strip type declarations 1`] = ` -"const foo = 1; +{ + "code": "const foo = 1; - const bar = "bar";" + const bar = "bar";", + "map": undefined, +} `; exports[`transform in strip-only mode should throw an error when it encounters a module 1`] = ` @@ -78,8 +107,11 @@ exports[`transform in strip-only mode should throw an error when it encounters a `; exports[`transform should strip types 1`] = ` -" +{ + "code": " export const foo = 1; - " + ", + "map": undefined, +} `;