Skip to content
Merged
Changes from all 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
33 changes: 11 additions & 22 deletions crates/oxc_linter/src/rules/react/no_unescaped_entities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ use oxc_ast::AstKind;
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;
use phf::{Map, phf_map};

use crate::{
AstNode,
context::{ContextHost, LintContext},
rule::Rule,
};

fn no_unescaped_entities_diagnostic(span: Span, unescaped: char, escaped: &str) -> OxcDiagnostic {
static ESCAPED_DOUBLE_QUOTE: &str = "" or “ or " or ”";
static ESCAPED_SINGLE_QUOTE: &str = "' or ‘ or ' or ’";

fn no_unescaped_entities_diagnostic(span: Span, unescaped: char) -> OxcDiagnostic {
let escaped = if unescaped == '"' { ESCAPED_DOUBLE_QUOTE } else { ESCAPED_SINGLE_QUOTE };
OxcDiagnostic::warn(format!("`{unescaped}` can be escaped with {escaped}")).with_label(span)
}

Expand Down Expand Up @@ -50,20 +53,14 @@ declare_oxc_lint!(
impl Rule for NoUnescapedEntities {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
if let AstKind::JSXText(jsx_text) = node.kind() {
let source = jsx_text.span.source_text(ctx.source_text());
for (i, char) in source.char_indices() {
if !CHARS.contains(&char) {
continue;
}
if let Some(escapes) = DEFAULTS.get(&char) {
let source = jsx_text.raw.unwrap().as_str();
for (i, &byte) in source.as_bytes().iter().enumerate() {
if matches!(byte, b'\'' | b'\"') {
#[expect(clippy::cast_possible_truncation)]
let start = jsx_text.span.start + i as u32;
ctx.diagnostic(no_unescaped_entities_diagnostic(
Span::new(
jsx_text.span.start + i as u32,
jsx_text.span.start + i as u32 + 1,
),
char,
&escapes.join(" or "),
Span::new(start, start + 1),
byte as char,
));
}
}
Expand All @@ -75,14 +72,6 @@ impl Rule for NoUnescapedEntities {
}
}

// NOTE: If we add substantially more characters, we should consider using a hash set instead.
pub const CHARS: [char; 2] = ['"', '\''];

pub const DEFAULTS: Map<char, &'static [&'static str]> = phf_map! {
'"' => &["&quot;", "&ldquo;", "&#34;", "&rdquo;"],
'\'' => &["&apos;", "&lsquo;", "&#39;", "&rsquo;"],
};

#[test]
fn test() {
use crate::tester::Tester;
Expand Down
Loading