@@ -9,7 +9,8 @@ use swc_ecmascript::visit::Visit;
99pub struct NoOctal ;
1010
1111const CODE : & str = "no-octal" ;
12- const MESSAGE : & str = "`Octal number` is not allowed" ;
12+ const MESSAGE : & str = "Numeric literals beginning with `0` are not allowed" ;
13+ const HINT : & str = "To express octal numbers, use `0o` as a prefix instead" ;
1314
1415impl LintRule for NoOctal {
1516 fn new ( ) -> Box < Self > {
@@ -35,6 +36,33 @@ impl LintRule for NoOctal {
3536 ProgramRef :: Script ( ref s) => visitor. visit_script ( s, & DUMMY_NODE ) ,
3637 }
3738 }
39+
40+ fn docs ( & self ) -> & ' static str {
41+ r#"Disallows expressing octal numbers via numeric literals beginning with `0`
42+
43+ Octal numbers can be expressed via numeric literals with leading `0` like `042`,
44+ but this expression often confuses programmers. That's why ECMAScript's strict
45+ mode throws `SyntaxError` for the expression.
46+
47+ Since ES2015, the other prefix `0o` has been introduced as an alternative. This
48+ new one is always encouraged to use in today's code.
49+
50+ ### Invalid:
51+
52+ ```typescript
53+ const a = 042;
54+ const b = 7 + 042;
55+ ```
56+
57+ ### Valid:
58+
59+ ```typescript
60+ const a = 0o42;
61+ const b = 7 + 0o42;
62+ const c = "042";
63+ ```
64+ "#
65+ }
3866}
3967
4068struct NoOctalVisitor < ' c , ' view > {
@@ -58,7 +86,12 @@ impl<'c, 'view> Visit for NoOctalVisitor<'c, 'view> {
5886 . expect ( "error in loading snippet" ) ;
5987
6088 if OCTAL . is_match ( & raw_number) {
61- self . context . add_diagnostic ( literal_num. span , CODE , MESSAGE ) ;
89+ self . context . add_diagnostic_with_hint (
90+ literal_num. span ,
91+ CODE ,
92+ MESSAGE ,
93+ HINT ,
94+ ) ;
6295 }
6396 }
6497}
@@ -82,12 +115,12 @@ mod tests {
82115 fn no_octal_invalid ( ) {
83116 assert_lint_err ! {
84117 NoOctal ,
85- "07" : [ { col: 0 , message: MESSAGE } ] ,
86- "let x = 7 + 07" : [ { col: 12 , message: MESSAGE } ] ,
118+ "07" : [ { col: 0 , message: MESSAGE , hint : HINT } ] ,
119+ "let x = 7 + 07" : [ { col: 12 , message: MESSAGE , hint : HINT } ] ,
87120
88121 // https://github.com/denoland/deno/issues/10954
89122 // Make sure it doesn't panic
90- "020000000000000000000;" : [ { col: 0 , message: MESSAGE } ] ,
123+ "020000000000000000000;" : [ { col: 0 , message: MESSAGE , hint : HINT } ] ,
91124 }
92125 }
93126}
0 commit comments