Skip to content

Commit

Permalink
perf(linter): make img-redundant-alt only build a regex once (#4604)
Browse files Browse the repository at this point in the history
  • Loading branch information
DonIsaac committed Aug 2, 2024
1 parent 74fa75a commit f259df0
Showing 1 changed file with 48 additions and 35 deletions.
83 changes: 48 additions & 35 deletions crates/oxc_linter/src/rules/jsx_a11y/img_redundant_alt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use oxc_ast::{
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;
use regex::Regex;
use oxc_span::{CompactStr, Span};
use regex::{Regex, RegexBuilder};
use serde_json::Value;

use crate::{
context::LintContext,
Expand All @@ -23,10 +24,10 @@ fn img_redundant_alt_diagnostic(span0: Span) -> OxcDiagnostic {
#[derive(Debug, Default, Clone)]
pub struct ImgRedundantAlt(Box<ImgRedundantAltConfig>);

#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone)]
pub struct ImgRedundantAltConfig {
types_to_validate: Vec<String>,
redundant_words: Vec<String>,
types_to_validate: Vec<CompactStr>,
redundant_words: Regex,
}

impl std::ops::Deref for ImgRedundantAlt {
Expand All @@ -37,17 +38,28 @@ impl std::ops::Deref for ImgRedundantAlt {
}
}

const COMPONENTS_FIXED_TO_VALIDATE: [&str; 1] = ["img"];
const REDUNDANT_WORDS: [&str; 3] = ["image", "photo", "picture"];
impl Default for ImgRedundantAltConfig {
fn default() -> Self {
Self {
types_to_validate: COMPONENTS_FIXED_TO_VALIDATE
.iter()
.map(|&s| s.to_string())
.collect(),
redundant_words: REDUNDANT_WORDS.iter().map(|&s| s.to_string()).collect(),
types_to_validate: vec![CompactStr::new("img")],
redundant_words: Self::union(&REDUNDANT_WORDS).unwrap(),
}
}
}
impl ImgRedundantAltConfig {
fn new(types_to_validate: Vec<&str>, redundant_words: &[&str]) -> Result<Self, regex::Error> {
Ok(Self {
types_to_validate: types_to_validate.into_iter().map(Into::into).collect(),
redundant_words: Self::union(redundant_words)?,
})
}

fn union(strs: &[&str]) -> Result<Regex, regex::Error> {
RegexBuilder::new(&format!(r"(?i)\b({})\b", strs.join("|"))).case_insensitive(true).build()
}
}

declare_oxc_lint!(
/// ### What it does
Expand Down Expand Up @@ -81,27 +93,27 @@ declare_oxc_lint!(
ImgRedundantAlt,
correctness
);
const COMPONENTS_FIXED_TO_VALIDATE: [&str; 1] = ["img"];
const REDUNDANT_WORDS: [&str; 3] = ["image", "photo", "picture"];

impl Rule for ImgRedundantAlt {
fn from_configuration(value: serde_json::Value) -> Self {
let mut img_redundant_alt = ImgRedundantAltConfig::default();
if let Some(config) = value.get(0) {
if let Some(components) = config.get("components").and_then(|v| v.as_array()) {
img_redundant_alt
.types_to_validate
.extend(components.iter().filter_map(|v| v.as_str().map(ToString::to_string)));
}

if let Some(words) = config.get("words").and_then(|v| v.as_array()) {
img_redundant_alt
.redundant_words
.extend(words.iter().filter_map(|v| v.as_str().map(ToString::to_string)));
}
}
fn from_configuration(value: Value) -> Self {
let Some(config) = value.get(0) else {
return Self::default();
};
let components = config.get("components").and_then(Value::as_array).map_or(
Vec::from(COMPONENTS_FIXED_TO_VALIDATE),
|v| {
v.iter()
.filter_map(Value::as_str)
.chain(COMPONENTS_FIXED_TO_VALIDATE)
.collect::<Vec<_>>()
},
);
let words =
config.get("words").and_then(Value::as_array).map_or(Vec::from(REDUNDANT_WORDS), |v| {
v.iter().filter_map(Value::as_str).chain(REDUNDANT_WORDS).collect::<Vec<_>>()
});

Self(Box::new(img_redundant_alt))
Self(Box::new(ImgRedundantAltConfig::new(components, words.as_slice()).unwrap()))
}

fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
Expand Down Expand Up @@ -144,23 +156,23 @@ impl Rule for ImgRedundantAlt {
JSXAttributeValue::StringLiteral(lit) => {
let alt_text = lit.value.as_str();

if is_redundant_alt_text(alt_text, &self.redundant_words) {
if self.is_redundant_alt_text(alt_text) {
ctx.diagnostic(img_redundant_alt_diagnostic(alt_attribute_name_span));
}
}
JSXAttributeValue::ExpressionContainer(container) => match &container.expression {
JSXExpression::StringLiteral(lit) => {
let alt_text = lit.value.as_str();

if is_redundant_alt_text(alt_text, &self.redundant_words) {
if self.is_redundant_alt_text(alt_text) {
ctx.diagnostic(img_redundant_alt_diagnostic(alt_attribute_name_span));
}
}
JSXExpression::TemplateLiteral(lit) => {
for quasi in &lit.quasis {
let alt_text = quasi.value.raw.as_str();

if is_redundant_alt_text(alt_text, &self.redundant_words) {
if self.is_redundant_alt_text(alt_text) {
ctx.diagnostic(img_redundant_alt_diagnostic(alt_attribute_name_span));
}
}
Expand All @@ -172,10 +184,11 @@ impl Rule for ImgRedundantAlt {
}
}

fn is_redundant_alt_text(alt_text: &str, redundant_words: &[String]) -> bool {
let regexp = Regex::new(&format!(r"(?i)\b({})\b", redundant_words.join("|"),)).unwrap();

regexp.is_match(alt_text)
impl ImgRedundantAlt {
#[inline]
fn is_redundant_alt_text(&self, alt_text: &str) -> bool {
self.redundant_words.is_match(alt_text)
}
}

#[test]
Expand Down

0 comments on commit f259df0

Please sign in to comment.