elint 0.0.2

Erlang code linter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Rustc-style rendering of diagnostics for the CLI.

use std::io::{IsTerminal, Write};
use std::path::Path;

use unicode_width::UnicodeWidthChar;

use crate::Span;

/// Maps byte offsets in a source text to line / column positions.
#[derive(Debug)]
pub struct LineIndex {
    /// Byte offset of the start of each line.
    starts: Vec<usize>,
}

impl LineIndex {
    /// Builds an index from `text`.
    pub fn new(text: &str) -> Self {
        let mut starts = vec![0];
        for (i, ch) in text.char_indices() {
            if ch == '\n' {
                starts.push(i + 1);
            }
        }
        Self { starts }
    }

    /// Returns the 1-based line number and 1-based display column of
    /// `offset`.
    pub fn line_col(&self, text: &str, offset: usize) -> (usize, usize) {
        let offset = offset.min(text.len());
        let idx = self
            .starts
            .partition_point(|&start| start <= offset)
            .saturating_sub(1);
        let line = idx + 1;
        let column = display_width(&text[self.starts[idx]..offset]) + 1;
        (line, column)
    }

    /// Byte range `[start, end)` of the 0-based `line`, excluding the
    /// trailing newline.
    pub fn line_range(&self, text: &str, line: usize) -> (usize, usize) {
        let start = self.starts[line];
        let end = self
            .starts
            .get(line + 1)
            .map_or(text.len(), |&next| next.saturating_sub(1));
        (start, end)
    }
}

/// A source file plus its [`LineIndex`], ready for diagnostic rendering.
#[derive(Debug)]
pub struct Source<'a> {
    path: &'a Path,
    text: &'a str,
    index: LineIndex,
}

impl<'a> Source<'a> {
    /// Builds a renderable source from a file path and its text.
    pub fn new(path: &'a Path, text: &'a str) -> Self {
        Self {
            path,
            text,
            index: LineIndex::new(text),
        }
    }
}

/// Controls whether ANSI color codes are emitted.
#[derive(Debug, Clone, Copy)]
pub struct Color {
    enabled: bool,
}

impl Color {
    /// Detects from the stderr terminal and the `NO_COLOR` environment
    /// variable.
    pub fn detect() -> Self {
        let enabled = std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none();
        Self { enabled }
    }

    fn paint(self, code: &str, s: &str) -> String {
        if self.enabled {
            format!("\x1b[{code}m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }

    /// Bold red `error` label.
    pub fn error(self, s: &str) -> String {
        self.paint("1;31", s)
    }

    /// Cyan code (`[rule]`).
    pub fn code(self, s: &str) -> String {
        self.paint("36", s)
    }

    /// Blue `-->` arrow.
    pub fn arrow(self, s: &str) -> String {
        self.paint("34", s)
    }

    /// Blue `note:` label.
    pub fn note(self, s: &str) -> String {
        self.paint("34", s)
    }

    /// Bold cyan line number.
    pub fn line_number(self, s: &str) -> String {
        self.paint("1;36", s)
    }

    /// Bold red caret.
    pub fn caret(self, s: &str) -> String {
        self.paint("1;31", s)
    }
}

/// Renders one rustc-style diagnostic block:
///
/// ```text
/// error[code]: message
///   --> path:line:col
///    |
/// 10 |     element(1, T)
///    |     ^^^^^^^^^^^^
///    |
/// note: a follow-up line when provided
/// ```
///
/// The caret spans `span` within the first line it touches. Tabs are
/// expanded to four columns in the source and caret lines so the caret
/// stays aligned.
pub fn render(
    w: &mut impl Write,
    color: Color,
    source: &Source<'_>,
    code: Option<&str>,
    message: &str,
    span: Span,
    note: Option<&str>,
) -> std::io::Result<()> {
    let (line, column) = source.index.line_col(source.text, span.start);
    let width = line.to_string().len();
    let bar = format!("{} |", " ".repeat(width));
    let gutter = format!("{} | ", " ".repeat(width));

    let header = match code {
        Some(code) => format!(
            "{}[{}]: {}",
            color.error("error"),
            color.code(code),
            message
        ),
        None => format!("{}: {}", color.error("error"), message),
    };
    let location = format!("{}:{}:{}", source.path.display(), line, column);
    writeln!(w, "{header}")?;
    writeln!(w, "{}{} {location}", " ".repeat(width), color.arrow("-->"))?;
    writeln!(w, "{bar}")?;

    let (line_start, line_end) = source.index.line_range(source.text, line - 1);
    let line_text = &source.text[line_start..line_end];
    let line_number = color.line_number(&format!("{line:>width$}"));
    writeln!(w, "{line_number} | {}", expand_tabs(line_text))?;

    let span_end = span.end.min(line_end);
    let visual = display_width(&source.text[line_start..span.start]);
    let caret_len = display_width(&source.text[span.start..span_end]).max(1);
    let caret = color.caret(&"^".repeat(caret_len));
    writeln!(w, "{gutter}{}{caret}", " ".repeat(visual))?;
    writeln!(w, "{bar}")?;

    if let Some(note) = note {
        writeln!(w, "{} {note}", color.note("note:"))?;
    }

    Ok(())
}

fn display_width(text: &str) -> usize {
    text.chars()
        .map(|c| {
            if c == '\t' {
                4
            } else {
                UnicodeWidthChar::width(c).unwrap_or(0)
            }
        })
        .sum()
}

fn expand_tabs(s: &str) -> String {
    s.replace('\t', "    ")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn render_to_string(
        text: &str,
        span: Span,
        code: Option<&str>,
        message: &str,
        note: Option<&str>,
    ) -> String {
        let source = Source::new(Path::new("t.erl"), text);
        let mut out = Vec::new();
        render(
            &mut out,
            Color { enabled: false },
            &source,
            code,
            message,
            span,
            note,
        )
        .expect("write to Vec");
        String::from_utf8(out).expect("utf8")
    }

    #[test]
    fn renders_single_line_span() {
        let text = "-module(t).\nfoo() -> ok.\n";
        let start = text.find("ok.").expect("finding");
        let out = render_to_string(
            text,
            Span::new(start, start + 2),
            Some("newline_after_arrow"),
            "summary",
            None,
        );
        assert_eq!(
            out,
            "\
error[newline_after_arrow]: summary
 --> t.erl:2:10
  |
2 | foo() -> ok.
  |          ^^
  |
"
        );
    }

    #[test]
    fn pads_line_numbers_to_width() {
        let text = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nfoo() -> ok.\n";
        let start = text.find("ok.").expect("finding");
        let out = render_to_string(text, Span::new(start, start + 2), None, "message", None);
        assert_eq!(
            out,
            "\
error: message
  --> t.erl:11:10
   |
11 | foo() -> ok.
   |          ^^
   |
"
        );
    }

    #[test]
    fn expands_tabs_in_caret_alignment() {
        let text = "foo() ->\n\tok.\n";
        let start = text.find("ok.").expect("finding");
        let out = render_to_string(text, Span::new(start, start + 2), None, "message", None);
        // Tab becomes four columns, so the caret sits at column 5.
        assert_eq!(
            out,
            "\
error: message
 --> t.erl:2:5
  |
2 |     ok.
  |     ^^
  |
"
        );
    }

    #[test]
    fn aligns_caret_after_wide_characters() {
        let text = "foo(\"おはよう\", X)\n";
        let start = text.find('X').expect("finding");
        let out = render_to_string(text, Span::new(start, start + 1), None, "message", None);
        // `おはよう` is four wide characters (8 columns), so the caret is
        // at display column 17.
        assert_eq!(
            out,
            "\
error: message
 --> t.erl:1:17
  |
1 | foo(\"おはよう\", X)
  |                 ^
  |
"
        );
    }

    #[test]
    fn aligns_caret_after_combining_characters() {
        let text = "caf\u{301} X\n";
        let start = text.find('X').expect("finding");
        let out = render_to_string(text, Span::new(start, start + 1), None, "message", None);
        // The combining acute accent has display width 0, so the caret is
        // at display column 5.
        assert_eq!(
            out,
            "\
error: message
 --> t.erl:1:5
  |
1 | caf\u{301} X
  |     ^
  |
"
        );
    }

    #[test]
    fn aligns_caret_with_tab_and_wide_characters() {
        let text = "\tおX\n";
        let start = text.find('X').expect("finding");
        let out = render_to_string(text, Span::new(start, start + 1), None, "message", None);
        // Tab expands to four columns and `お` is two columns wide, so the
        // caret is at display column 7.
        assert_eq!(
            out,
            "\
error: message
 --> t.erl:1:7
  |
1 |     おX
  |       ^
  |
"
        );
    }

    #[test]
    fn clamps_empty_span_to_one_caret() {
        let text = "-module(t).\n";
        let out = render_to_string(text, Span::new(0, 0), None, "message", None);
        assert!(out.contains("^\n"), "{out:?}");
    }

    #[test]
    fn renders_note_after_block() {
        let text = "foo() -> ok.\n";
        let start = text.find("ok.").expect("finding");
        let out = render_to_string(
            text,
            Span::new(start, start + 1),
            Some("r"),
            "m",
            Some("see `elint explain r`"),
        );
        assert_eq!(
            out,
            "\
error[r]: m
 --> t.erl:1:10
  |
1 | foo() -> ok.
  |          ^
  |
note: see `elint explain r`
"
        );
    }

    #[test]
    fn color_codes_are_emitted_when_enabled() {
        let text = "foo() -> ok.\n";
        let start = text.find("ok.").expect("finding");
        let source = Source::new(Path::new("t.erl"), text);
        let mut out = Vec::new();
        render(
            &mut out,
            Color { enabled: true },
            &source,
            Some("r"),
            "m",
            Span::new(start, start + 1),
            Some("note"),
        )
        .expect("write");
        let out = String::from_utf8(out).expect("utf8");
        assert!(out.contains("\x1b[1;31merror\x1b[0m"), "{out:?}");
        assert!(out.contains("\x1b[36mr\x1b[0m"), "{out:?}");
        assert!(out.contains("\x1b[34mnote:\x1b[0m"), "{out:?}");
    }
}