Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support for case-insensitive matches #34

Merged
merged 10 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ impl<R: RegExp> Component<R> {
let part_list = part_list.iter().collect::<Vec<_>>();
let (regexp_string, name_list) =
generate_regular_expression_and_name_list(&part_list, &options);
let regexp = R::parse(&regexp_string).map_err(Error::RegExp);
let flags = if options.ignore_case { "ui" } else { "u" };
let regexp = R::parse(&regexp_string, flags).map_err(Error::RegExp);
let pattern_string = generate_pattern_string(&part_list, &options);
let matcher = generate_matcher::<R>(&part_list, &options);
let matcher = generate_matcher::<R>(&part_list, &options, flags);
Ok(Component {
pattern_string,
regexp,
Expand Down Expand Up @@ -275,6 +276,7 @@ fn escape_pattern_string(input: &str) -> String {
fn generate_matcher<R: RegExp>(
mut part_list: &[&Part],
options: &Options,
flags: &str,
) -> Matcher<R> {
fn is_literal(part: &Part) -> bool {
part.kind == PartType::FixedText && part.modifier == PartModifier::None
Expand Down Expand Up @@ -343,7 +345,7 @@ fn generate_matcher<R: RegExp>(
part_list => {
let (regexp_string, _) =
generate_regular_expression_and_name_list(part_list, options);
let regexp = R::parse(&regexp_string).map_err(Error::RegExp);
let regexp = R::parse(&regexp_string, flags).map_err(Error::RegExp);
InnerMatcher::RegExp { regexp }
}
};
Expand Down
38 changes: 26 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ fn is_absolute_pathname(
/// pathname: Some("/users/:id".to_owned()),
/// ..Default::default()
/// };
/// let pattern = <UrlPattern>::parse(init).unwrap();
/// let pattern = <UrlPattern>::parse(init, false).unwrap();
///
/// // Match the pattern against a URL.
/// let url = "https://example.com/users/123".parse().unwrap();
Expand Down Expand Up @@ -226,13 +226,14 @@ pub enum UrlPatternMatchInput {
impl<R: RegExp> UrlPattern<R> {
// Ref: https://wicg.github.io/urlpattern/#dom-urlpattern-urlpattern
/// Parse a [UrlPatternInit] into a [UrlPattern].
pub fn parse(init: UrlPatternInit) -> Result<Self, Error> {
Self::parse_internal(init, true)
pub fn parse(init: UrlPatternInit, ignore_case: bool) -> Result<Self, Error> {
Self::parse_internal(init, true, ignore_case)
}

pub(crate) fn parse_internal(
init: UrlPatternInit,
report_regex_errors: bool,
ignore_case: bool,
) -> Result<Self, Error> {
let mut processed_init = init.process(
canonicalize_and_process::ProcessType::Pattern,
Expand Down Expand Up @@ -285,18 +286,26 @@ impl<R: RegExp> UrlPattern<R> {
.optionally_transpose_regex_error(report_regex_errors)?
};

let compile_options = parser::Options {
ignore_case,
..Default::default()
};

let pathname = if protocol.protocol_component_matches_special_scheme() {
Component::compile(
processed_init.pathname.as_deref(),
canonicalize_and_process::canonicalize_pathname,
parser::Options::pathname(),
parser::Options {
ignore_case,
..parser::Options::pathname()
},
)?
.optionally_transpose_regex_error(report_regex_errors)?
} else {
Component::compile(
processed_init.pathname.as_deref(),
canonicalize_and_process::canonicalize_an_opaque_pathname,
parser::Options::default(),
compile_options.clone(),
)?
.optionally_transpose_regex_error(report_regex_errors)?
};
Expand Down Expand Up @@ -326,13 +335,13 @@ impl<R: RegExp> UrlPattern<R> {
search: Component::compile(
processed_init.search.as_deref(),
canonicalize_and_process::canonicalize_search,
parser::Options::default(),
compile_options.clone(),
)?
.optionally_transpose_regex_error(report_regex_errors)?,
hash: Component::compile(
processed_init.hash.as_deref(),
canonicalize_and_process::canonicalize_hash,
parser::Options::default(),
compile_options,
)?
.optionally_transpose_regex_error(report_regex_errors)?,
})
Expand Down Expand Up @@ -501,6 +510,7 @@ pub struct UrlPatternComponentResult {

#[cfg(test)]
mod tests {
use regex::Regex;
use std::collections::HashMap;

use serde::Deserialize;
Expand Down Expand Up @@ -603,7 +613,8 @@ mod tests {
base_url.as_deref(),
);

let res = init_res.and_then(<UrlPattern>::parse);
let res =
init_res.and_then(|init_res| UrlPattern::<Regex>::parse(init_res, false)); // TODO: once tests are available set flag accordingly
let expected_obj = match case.expected_obj {
Some(StringOrInit::String(s)) if s == "error" => {
assert!(res.is_err());
Expand Down Expand Up @@ -827,10 +838,13 @@ mod tests {

#[test]
fn issue26() {
<UrlPattern>::parse(UrlPatternInit {
pathname: Some("/:foo.".to_owned()),
..Default::default()
})
UrlPattern::<Regex>::parse(
UrlPatternInit {
pathname: Some("/:foo.".to_owned()),
..Default::default()
},
false,
)
.unwrap();
}
}
6 changes: 5 additions & 1 deletion src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ pub enum RegexSyntax {
pub struct Options {
pub delimiter_code_point: String, // TODO: It must contain one ASCII code point or the empty string. maybe Option<char>?
pub prefix_code_point: String, // TODO: It must contain one ASCII code point or the empty string. maybe Option<char>?
regex_syntax: RegexSyntax,
pub regex_syntax: RegexSyntax,
pub ignore_case: bool,
}

impl std::default::Default for Options {
Expand All @@ -37,6 +38,7 @@ impl std::default::Default for Options {
delimiter_code_point: String::new(),
prefix_code_point: String::new(),
regex_syntax: RegexSyntax::Rust,
ignore_case: false,
}
}
}
Expand All @@ -49,6 +51,7 @@ impl Options {
delimiter_code_point: String::from("."),
prefix_code_point: String::new(),
regex_syntax: RegexSyntax::Rust,
ignore_case: false,
}
}

Expand All @@ -59,6 +62,7 @@ impl Options {
delimiter_code_point: String::from("/"),
prefix_code_point: String::from("/"),
regex_syntax: RegexSyntax::Rust,
ignore_case: false,
}
}

Expand Down
16 changes: 10 additions & 6 deletions src/quirks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,26 +165,30 @@ impl From<crate::matcher::InnerMatcher<EcmaRegexp>> for InnerMatcher {
}
}

struct EcmaRegexp(String);
struct EcmaRegexp(String, String);

impl RegExp for EcmaRegexp {
fn syntax() -> RegexSyntax {
RegexSyntax::EcmaScript
}

fn parse(pattern: &str) -> Result<Self, ()> {
Ok(EcmaRegexp(pattern.to_string()))
fn parse(pattern: &str, flags: &str) -> Result<Self, ()> {
Ok(EcmaRegexp(pattern.to_string(), flags.to_string()))
}

fn matches<'a>(&self, text: &'a str) -> Option<Vec<&'a str>> {
let regexp = regex::Regex::parse(&self.0).ok()?;
let regexp = regex::Regex::parse(&self.0, &self.1).ok()?;
regexp.matches(text)
}
}

/// Parse a pattern into its components.
pub fn parse_pattern(init: crate::UrlPatternInit) -> Result<UrlPattern, Error> {
let pattern = crate::UrlPattern::<EcmaRegexp>::parse_internal(init, false)?;
pub fn parse_pattern(
init: crate::UrlPatternInit,
ignore_case: bool,
) -> Result<UrlPattern, Error> {
let pattern =
crate::UrlPattern::<EcmaRegexp>::parse_internal(init, false, ignore_case)?;
let urlpattern = UrlPattern {
protocol: pattern.protocol.into(),
username: pattern.username.into(),
Expand Down
6 changes: 3 additions & 3 deletions src/regexp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub trait RegExp: Sized {

/// Generates a regexp pattern for the given string. If the pattern is
/// invalid, the parse function should return an error.
fn parse(pattern: &str) -> Result<Self, ()>;
fn parse(pattern: &str, flags: &str) -> Result<Self, ()>;

/// Matches the given text against the regular expression and returns the list
/// of captures. The matches are returned in the order they appear in the
Expand All @@ -22,8 +22,8 @@ impl RegExp for regex::Regex {
RegexSyntax::Rust
}

fn parse(pattern: &str) -> Result<Self, ()> {
regex::Regex::new(pattern).map_err(|_| ())
fn parse(pattern: &str, flags: &str) -> Result<Self, ()> {
regex::Regex::new(&format!("(?{flags}){pattern}")).map_err(|_| ())
}

fn matches<'a>(&self, text: &'a str) -> Option<Vec<&'a str>> {
Expand Down