|
| 1 | +use oxc_ast::AstKind; |
| 2 | +use oxc_diagnostics::OxcDiagnostic; |
| 3 | +use oxc_macros::declare_oxc_lint; |
| 4 | +use oxc_span::Span; |
| 5 | + |
| 6 | +use crate::{context::LintContext, rule::Rule, AstNode}; |
| 7 | + |
| 8 | +fn no_multi_str_diagnostic(span0: Span) -> OxcDiagnostic { |
| 9 | + OxcDiagnostic::warn("eslint(no-multi-str): Unexpected multi string.").with_label(span0) |
| 10 | +} |
| 11 | + |
| 12 | +#[derive(Debug, Default, Clone)] |
| 13 | +pub struct NoMultiStr; |
| 14 | + |
| 15 | +declare_oxc_lint!( |
| 16 | + /// ### What it does |
| 17 | + /// |
| 18 | + /// Disallow multiline strings. |
| 19 | + /// |
| 20 | + /// ### Why is this bad? |
| 21 | + /// |
| 22 | + /// Some consider this to be a bad practice as it was an undocumented feature of JavaScript |
| 23 | + /// that was only formalized later. |
| 24 | + /// |
| 25 | + /// ### Example |
| 26 | + /// ```javascript |
| 27 | + /// var x = "Line 1 \ |
| 28 | + /// Line 2"; |
| 29 | + /// ``` |
| 30 | + NoMultiStr, |
| 31 | + style, |
| 32 | +); |
| 33 | + |
| 34 | +impl Rule for NoMultiStr { |
| 35 | + fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { |
| 36 | + if let AstKind::StringLiteral(literal) = node.kind() { |
| 37 | + let source = literal.span.source_text(ctx.source_text()); |
| 38 | + // https://github.com/eslint/eslint/blob/9e6d6405c3ee774c2e716a3453ede9696ced1be7/lib/shared/ast-utils.js#L12 |
| 39 | + let position = |
| 40 | + source.find(|ch| matches!(ch, '\r' | '\n' | '\u{2028}' | '\u{2029}')).unwrap_or(0); |
| 41 | + if position != 0 { |
| 42 | + // We found the "newline" character but want to highlight the '\', so go back one |
| 43 | + // character. |
| 44 | + let multi_span_start = |
| 45 | + literal.span.start + u32::try_from(position).unwrap_or_default() - 1; |
| 46 | + ctx.diagnostic(no_multi_str_diagnostic(Span::new( |
| 47 | + multi_span_start, |
| 48 | + multi_span_start + 1, |
| 49 | + ))); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +#[test] |
| 56 | +fn test() { |
| 57 | + use crate::tester::Tester; |
| 58 | + |
| 59 | + let pass = vec![ |
| 60 | + "var a = 'Line 1 Line 2';", |
| 61 | + "var a = <div> |
| 62 | + <h1>Wat</h1> |
| 63 | + </div>;", // { "ecmaVersion": 6, "parserOptions": { "ecmaFeatures": { "jsx": true } } } |
| 64 | + ]; |
| 65 | + |
| 66 | + let fail = vec![ |
| 67 | + "var x = 'Line 1 \\ |
| 68 | + Line 2'", |
| 69 | + "test('Line 1 \\ |
| 70 | + Line 2');", |
| 71 | + "'foo\\\rbar';", |
| 72 | + "'foo\\
bar';", |
| 73 | + "'foo\\
ar';", |
| 74 | + "'\\
still fails';", |
| 75 | + ]; |
| 76 | + |
| 77 | + Tester::new(NoMultiStr::NAME, pass, fail).test_and_snapshot(); |
| 78 | +} |
0 commit comments