Unverified Commit 78d70501 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

Turbopack: Remove the `lazy-regex` dependency (#82288)

Yes, `lazy_regex` makes this code slightly cleaner, and it does have the
nice side-effect of compile-time checking the regexes but:

- We've got test coverage for all of these regexes.
- It adds a proc macro, proc macros are detrimental to build
performance.
- It doesn't really clean up the code that much versus the new stdlib
`LazyLock`.
- This is the only crate using it.

So I don't think it's worth it.
parent 03c8e5d0
......@@ -3511,29 +3511,6 @@ dependencies = [
"libc",
]
[[package]]
name = "lazy-regex"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57451d19ad5e289ff6c3d69c2a2424652995c42b79dafa11e9c4d5508c913c01"
dependencies = [
"lazy-regex-proc_macros",
"once_cell",
"regex",
]
[[package]]
name = "lazy-regex-proc_macros"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f0a1d9139f0ee2e862e08a9c5d0ba0470f2aa21cd1e1aa1b1562f83116c725f"
dependencies = [
"proc-macro2",
"quote",
"regex",
"syn 2.0.104",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
......@@ -4369,7 +4346,6 @@ dependencies = [
"indexmap 2.9.0",
"indoc",
"itertools 0.10.5",
"lazy-regex",
"mime_guess",
"modularize_imports",
"next-custom-transforms",
......
......@@ -16,7 +16,6 @@ anyhow = { workspace = true }
async-trait = { workspace = true }
base64 = "0.21.0"
either = { workspace = true }
lazy-regex = "3.0.1"
next-custom-transforms = { workspace = true }
once_cell = { workspace = true }
qstring = { workspace = true }
......
use std::ops::Deref;
use std::{ops::Deref, sync::LazyLock};
use anyhow::Result;
use once_cell::sync::Lazy;
use regex::Regex;
use rustc_hash::FxHashMap;
use turbo_rcstr::RcStr;
use turbo_tasks_fs::FileSystemPath;
......@@ -41,11 +42,15 @@ pub struct MetadataFileMatch<'a> {
}
fn match_numbered_metadata(stem: &str) -> Option<(&str, &str)> {
let (_whole, stem, number) = lazy_regex::regex_captures!(
"^(icon|apple-icon|opengraph-image|twitter-image)(\\d+)$",
stem
)?;
static NUMBERED_METADATA_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("^(icon|apple-icon|opengraph-image|twitter-image)(\\d+)$").unwrap()
});
let captures = NUMBERED_METADATA_RE.captures(stem)?;
// these captures must be defined if `captures` is `Some(...)`.
let (stem, number) = (
captures.get(1).unwrap().as_str(),
captures.get(2).unwrap().as_str(),
);
Some((stem, number))
}
......
use std::path::Path;
use std::{path::Path, sync::LazyLock};
use anyhow::{Context, Result, bail};
use futures::FutureExt;
use indoc::formatdoc;
use regex::Regex;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use turbo_rcstr::{RcStr, rcstr};
......@@ -527,14 +528,19 @@ fn find_font_files_in_css(css: &str, subsets_to_preload: &[RcStr]) -> Vec<FontFi
let mut current_subset = "";
for line in css.lines() {
if let Some((_, new_subset)) = lazy_regex::regex_captures!(r#"/\* (.+?) \*/"#, line) {
current_subset = new_subset;
static COMMENT_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"/\* (.+?) \*/"#).unwrap());
if let Some(new_subset) = COMMENT_RE.captures(line).and_then(|c| c.get(1)) {
current_subset = new_subset.as_str();
continue;
}
let Some((_, font_url)) = lazy_regex::regex_captures!(r#"src: url\((.+?)\)"#, line) else {
static FONT_URL_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"src: url\((.+?)\)"#).unwrap());
let Some(font_url) = FONT_URL_RE.captures(line).and_then(|c| c.get(1)) else {
continue;
};
let font_url = font_url.as_str();
if font_files.iter().any(|file| file.font_url == font_url) {
continue;
......
use std::sync::LazyLock;
use anyhow::{Context, Result};
use regex::Regex;
use serde::Deserialize;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::ResolvedVc;
......@@ -78,9 +81,10 @@ pub(crate) async fn can_use_next_font(project_path: FileSystemPath, query: &RcSt
.0,
)?;
let document_re = lazy_regex::regex!("^(src/)?_document\\.[^/]+$");
static DOCUMENT_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new("^(src/)?_document\\.[^/]+$").unwrap());
let path = project_path.join(&request.path)?;
let can_use = !document_re.is_match(&request.path);
let can_use = !DOCUMENT_RE.is_match(&request.path);
if !can_use {
NextFontIssue {
path: path.clone(),
......
use std::sync::LazyLock;
use anyhow::Result;
use regex::Regex;
use serde::{Deserialize, Serialize};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
......@@ -93,13 +96,15 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
};
// from https://github.com/vercel/next.js/blob/8d1c619ad650f5d147207f267441caf12acd91d1/packages/next/src/build/handle-externals.ts#L188
let never_external_regex = lazy_regex::regex!("^(?:private-next-pages\\/|next\\/(?:dist\\/pages\\/|(?:app|cache|document|link|form|head|image|legacy\\/image|constants|dynamic|script|navigation|headers|router|compat\\/router|server)$)|string-hash|private-next-rsc-action-validate|private-next-rsc-action-client-wrapper|private-next-rsc-server-reference|private-next-rsc-cache-wrapper$)");
static NEVER_EXTERNAL_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("^(?:private-next-pages\\/|next\\/(?:dist\\/pages\\/|(?:app|cache|document|link|form|head|image|legacy\\/image|constants|dynamic|script|navigation|headers|router|compat\\/router|server)$)|string-hash|private-next-rsc-action-validate|private-next-rsc-action-client-wrapper|private-next-rsc-server-reference|private-next-rsc-cache-wrapper$)").unwrap()
});
let Pattern::Constant(package_subpath) = package_subpath else {
return Ok(ResolveResultOption::none());
};
let request_str: RcStr = format!("{package}{package_subpath}").into();
if never_external_regex.is_match(&request_str) {
if NEVER_EXTERNAL_RE.is_match(&request_str) {
return Ok(ResolveResultOption::none());
}
......
use std::future::Future;
use std::{future::Future, sync::LazyLock};
use anyhow::{Context, Result, bail};
use regex::Regex;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use swc_core::{
common::{GLOBALS, Spanned, source_map::SmallPos},
......@@ -764,10 +765,11 @@ pub async fn load_next_js_template(
// Update the relative imports to be absolute. This will update any relative
// imports to be relative to the root of the `next` package.
let regex = lazy_regex::regex!("(?:from '(\\..*)'|import '(\\..*)')");
static IMPORT_PATH_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new("(?:from '(\\..*)'|import '(\\..*)')").unwrap());
let mut count = 0;
let mut content = replace_all(regex, &content, |caps| {
let mut content = replace_all(&IMPORT_PATH_RE, &content, |caps| {
let from_request = caps.get(1).map_or("", |c| c.as_str());
let import_request = caps.get(2).map_or("", |c| c.as_str());
......@@ -832,16 +834,13 @@ pub async fn load_next_js_template(
}
// Check to see if there's any remaining template variables.
let regex = lazy_regex::regex!("/VAR_[A-Z_]+");
let matches = regex
.find_iter(&content)
.map(|m| m.as_str().to_string())
.collect::<Vec<_>>();
static TEMPLATE_VAR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new("VAR_[A-Z_]+").unwrap());
let mut matches = TEMPLATE_VAR_RE.find_iter(&content).peekable();
if !matches.is_empty() {
if matches.peek().is_some() {
bail!(
"Invariant: Expected to replace all template variables, found {}",
matches.join(", "),
matches.map(|m| m.as_str()).collect::<Vec<_>>().join(", "),
)
}
......@@ -853,7 +852,7 @@ pub async fn load_next_js_template(
let difference = replacements
.keys()
.filter(|k| !replaced.contains(*k))
.cloned()
.copied()
.collect::<Vec<_>>();
bail!(
......@@ -875,16 +874,14 @@ pub async fn load_next_js_template(
}
// Check to see if there's any remaining injections.
let regex = lazy_regex::regex!("// INJECT:[A-Za-z0-9_]+");
let matches = regex
.find_iter(&content)
.map(|m| m.as_str().to_string())
.collect::<Vec<_>>();
static INJECT_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new("// INJECT:[A-Za-z0-9_]+").unwrap());
let mut matches = INJECT_RE.find_iter(&content).peekable();
if !matches.is_empty() {
if matches.peek().is_some() {
bail!(
"Invariant: Expected to inject all injections, found {}",
matches.join(", "),
matches.map(|m| m.as_str()).collect::<Vec<_>>().join(", "),
)
}
......@@ -896,7 +893,7 @@ pub async fn load_next_js_template(
let difference = injections
.keys()
.filter(|k| !injected.contains(*k))
.cloned()
.copied()
.collect::<Vec<_>>();
bail!(
......@@ -939,16 +936,14 @@ pub async fn load_next_js_template(
}
// Check to see if there's any remaining imports.
let regex = lazy_regex::regex!("// OPTIONAL_IMPORT:(\\* as )?[A-Za-z0-9_]+");
let matches = regex
.find_iter(&content)
.map(|m| m.as_str().to_string())
.collect::<Vec<_>>();
static OPTIONAL_IMPORT_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new("// OPTIONAL_IMPORT:(\\* as )?[A-Za-z0-9_]+").unwrap());
let mut matches = OPTIONAL_IMPORT_RE.find_iter(&content).peekable();
if !matches.is_empty() {
if matches.peek().is_some() {
bail!(
"Invariant: Expected to inject all imports, found {}",
matches.join(", "),
matches.map(|m| m.as_str()).collect::<Vec<_>>().join(", "),
)
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment