comex 1.0.0

Fast, dependency-free comment extraction and removal for source files, with content-based syntax detection (no file extensions required).
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! **comex** strips the comments out of source code, or strips everything *but* the
//! comments, without being told what language it is looking at.
//!
//! ```
//! let src = "int x = 1; // the answer\n/* gone */\nint y = 2;\n";
//! assert_eq!(comex::strip_comments(src), "int x = 1;\nint y = 2;\n");
//! assert_eq!(comex::extract_comments(src), "the answer\ngone\n");
//! ```
//!
//! # How it works
//!
//! Languages are grouped by *comment syntax*, not by name: `//` + `/* */` covers C,
//! C++, C#, Java, JavaScript, TypeScript, Go, Rust, Swift, Kotlin and PHP; `#` covers
//! Python, Ruby, shell, Perl, YAML, TOML and Make. [`detect`] scores those families
//! against structural evidence in the text — line-leading markers, balanced block
//! delimiters, shebangs, preprocessor lines, how lines end — and picks a winner, or
//! [`Dialect::Unknown`] when the evidence is too thin. [`scan`] then makes one linear
//! pass with a hand-written state machine: no regex, no backtracking, and a lookup
//! table so uninteresting bytes cost one probe each.
//!
//! String literals are tracked, which is the whole difficulty: `"https://example.com"`
//! contains `//` and `"#hashtag"` contains `#`, and neither is a comment. Raw strings,
//! character literals, Rust lifetimes, doubled-quote escapes and Lua long brackets are
//! all handled, and an unterminated quote is confined to its own line so that one odd
//! apostrophe cannot swallow a file.
//!
//! # Safety bias
//!
//! Ambiguity resolves toward *leaving the input alone*. Deleting a real line of code is
//! much worse than missing a comment, so weak evidence yields [`Dialect::Unknown`] and
//! an untouched file. When you do know the language, skip detection entirely:
//!
//! ```
//! use comex::{Dialect, Options};
//! let out = comex::strip_comments_with("x = 1 # hi\n", &Dialect::Hash.syntax(), &Options::default());
//! assert_eq!(out, "x = 1\n");
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

mod detect;
mod scan;
mod syntax;

pub use crate::detect::{detect, Detection, THRESHOLD};
pub use crate::scan::{scan, ScanConfig, Span, SpanKind};
pub use crate::syntax::{BlockRule, Dialect, LineRule, StringRule, Syntax};

/// Output settings for stripping and extraction.
///
/// [`Options::default`] is the sane behaviour for both directions: comment-only lines
/// disappear entirely, trailing whitespace left behind by a removed comment is cleaned
/// up, a leading `#!` line is preserved, and extracted comments have their markers and
/// common indentation removed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
    /// Keep line numbering identical to the input by leaving blank lines behind
    /// instead of removing them. In extraction mode, each comment is printed on the
    /// line it came from.
    pub preserve_lines: bool,
    /// Keep the (now blank) line when a comment was the only thing on it.
    /// Implied by `preserve_lines`.
    pub keep_blank_lines: bool,
    /// Trim whitespace left dangling at the end of a line by a removed comment.
    pub trim_trailing_whitespace: bool,
    /// Never treat a leading `#!` line as a comment.
    pub keep_shebang: bool,
    /// Count line-leading triple-quoted strings (Python-style docstrings) as comments.
    pub docstrings: bool,
    /// Remove comment markers from extracted comments (`// note` becomes `note`).
    pub strip_markers: bool,
    /// Remove common leading indentation from extracted block comments.
    pub dedent: bool,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            preserve_lines: false,
            keep_blank_lines: false,
            trim_trailing_whitespace: true,
            keep_shebang: true,
            docstrings: false,
            strip_markers: true,
            dedent: true,
        }
    }
}

impl Options {
    /// Preserve input line numbering in the output.
    pub fn preserve_lines(mut self, yes: bool) -> Self {
        self.preserve_lines = yes;
        self
    }
    /// Treat line-leading triple-quoted strings as comments.
    pub fn docstrings(mut self, yes: bool) -> Self {
        self.docstrings = yes;
        self
    }
    /// Keep comment markers when extracting.
    pub fn keep_markers(mut self, yes: bool) -> Self {
        self.strip_markers = !yes;
        self
    }

    fn scan_config(&self) -> ScanConfig {
        ScanConfig {
            record_strings: false,
            docstrings: self.docstrings,
            keep_shebang: self.keep_shebang,
        }
    }
}

/// Remove every comment from `src`, detecting the syntax from its content.
///
/// If no comment syntax can be identified, `src` is returned unchanged.
pub fn strip_comments(src: &str) -> String {
    strip_comments_with(src, &detect(src).syntax(), &Options::default())
}

/// Remove every comment from `src` using an explicit syntax.
pub fn strip_comments_with(src: &str, syn: &Syntax, opts: &Options) -> String {
    let spans = scan(src, syn, opts.scan_config());
    let mut w = LineWriter::new(src.len(), opts);
    let mut idx = 0;
    for s in spans.iter().filter(|s| s.kind.is_comment()) {
        w.push(&src[idx..s.start]);
        w.removed(&src[s.start..s.end]);
        idx = s.end;
    }
    w.push(&src[idx..]);
    w.finish()
}

/// Keep only the comments in `src`, detecting the syntax from its content.
///
/// Returns an empty string when no comment syntax can be identified.
pub fn extract_comments(src: &str) -> String {
    extract_comments_with(src, &detect(src).syntax(), &Options::default())
}

/// Keep only the comments in `src` using an explicit syntax.
pub fn extract_comments_with(src: &str, syn: &Syntax, opts: &Options) -> String {
    let spans = comments_with(src, syn, opts);
    if opts.preserve_lines {
        extract_positioned(src, &spans, opts)
    } else {
        extract_compact(src, &spans, opts)
    }
}

/// The comment spans of `src`, detecting the syntax from its content.
pub fn comments(src: &str) -> Vec<Span> {
    comments_with(src, &detect(src).syntax(), &Options::default())
}

/// The comment spans of `src` under an explicit syntax.
pub fn comments_with(src: &str, syn: &Syntax, opts: &Options) -> Vec<Span> {
    let mut spans = scan(src, syn, opts.scan_config());
    spans.retain(|s| s.kind.is_comment());
    spans
}

// --- stripping -------------------------------------------------------------

/// Buffers one output line at a time so that a line emptied by a removed comment can be
/// dropped, and a line left with trailing whitespace can be tidied.
struct LineWriter<'a> {
    out: String,
    line: String,
    dirty: bool,
    opts: &'a Options,
}

impl<'a> LineWriter<'a> {
    fn new(capacity: usize, opts: &'a Options) -> Self {
        LineWriter {
            out: String::with_capacity(capacity),
            line: String::new(),
            dirty: false,
            opts,
        }
    }

    fn push(&mut self, text: &str) {
        let mut parts = text.split('\n');
        if let Some(first) = parts.next() {
            self.line.push_str(first);
        }
        for part in parts {
            self.flush(true);
            self.line.push_str(part);
        }
    }

    fn removed(&mut self, text: &str) {
        self.dirty = true;
        if self.opts.preserve_lines {
            for _ in text.bytes().filter(|b| *b == b'\n') {
                self.flush(true);
            }
        }
    }

    fn flush(&mut self, newline: bool) {
        let mut content: &str = &self.line;
        // Keep CRLF endings intact: the CR belongs to the terminator, not the text.
        let cr = newline && content.ends_with('\r');
        if cr {
            content = &content[..content.len() - 1];
        }
        if self.dirty && self.opts.trim_trailing_whitespace {
            content = content.trim_end_matches([' ', '\t']);
        }
        let drop_line = self.dirty
            && newline
            && content.is_empty()
            && !self.opts.keep_blank_lines
            && !self.opts.preserve_lines;
        if !drop_line {
            self.out.push_str(content);
            if cr {
                self.out.push('\r');
            }
            if newline {
                self.out.push('\n');
            }
        }
        self.line.clear();
        self.dirty = false;
    }

    fn finish(mut self) -> String {
        if !self.line.is_empty() || self.dirty {
            self.flush(false);
        }
        self.out
    }
}

// --- extraction ------------------------------------------------------------

fn extract_compact(src: &str, spans: &[Span], opts: &Options) -> String {
    let mut out = String::new();
    let mut prev_end_line: Option<usize> = None;
    let mut line = 0usize;
    let mut cursor = 0usize;
    for s in spans {
        let start_line = line + count_newlines(&src[cursor..s.start]);
        line = start_line + count_newlines(&src[s.start..s.end]);
        cursor = s.end;

        let text = render(src, s, opts);
        if text.trim().is_empty() {
            continue;
        }
        // Blank line between comments that were not neighbours in the source.
        if prev_end_line.is_some_and(|prev| start_line > prev + 1) {
            out.push('\n');
        }
        out.push_str(&text);
        out.push('\n');
        prev_end_line = Some(line);
    }
    out
}

fn extract_positioned(src: &str, spans: &[Span], opts: &Options) -> String {
    let total = src.lines().count().max(count_newlines(src));
    let mut lines: Vec<String> = vec![String::new(); total];
    let mut line = 0usize;
    let mut cursor = 0usize;
    for s in spans {
        let start_line = line + count_newlines(&src[cursor..s.start]);
        line = start_line + count_newlines(&src[s.start..s.end]);
        cursor = s.end;
        for (k, part) in render(src, s, opts).split('\n').enumerate() {
            let at = start_line + k;
            if at >= lines.len() {
                break;
            }
            if !lines[at].is_empty() {
                lines[at].push(' ');
            }
            lines[at].push_str(part);
        }
    }
    let mut out = lines.join("\n");
    if !out.is_empty() {
        out.push('\n');
    }
    out
}

/// Turn one comment span into its output text.
fn render(src: &str, span: &Span, opts: &Options) -> String {
    if !opts.strip_markers {
        return span.text(src).to_string();
    }
    let raw = span.inner(src);
    let mut lines: Vec<&str> = raw.split('\n').collect();

    // `///`, `##`, `;;;`, `/**` - drop the repeated marker character.
    if let Some(first) = lines.first_mut() {
        let repeat = span.text(src).as_bytes()[span.inner_start - span.start - 1];
        *first = first.trim_start_matches(repeat as char);
    }
    // `* ` continuation lines of a block comment, only when they all agree.
    let starred = lines.len() > 1
        && lines[1..]
            .iter()
            .filter(|l| !l.trim().is_empty())
            .all(|l| l.trim_start().starts_with('*'));
    if starred {
        for l in lines[1..].iter_mut() {
            let t = l.trim_start();
            *l = match t.strip_prefix('*') {
                Some(rest) => rest.strip_prefix(' ').unwrap_or(rest),
                None => t,
            };
        }
    }

    if opts.dedent && lines.len() > 1 && !starred {
        let indent = lines[1..]
            .iter()
            .filter(|l| !l.trim().is_empty())
            .map(|l| l.len() - l.trim_start().len())
            .min()
            .unwrap_or(0);
        for l in lines[1..].iter_mut() {
            *l = if l.len() >= indent {
                &l[indent..]
            } else {
                l.trim_start()
            };
        }
    }

    let mut parts: Vec<&str> = lines.iter().map(|l| l.trim_end()).collect();
    if let Some(first) = parts.first_mut() {
        *first = first.strip_prefix(' ').unwrap_or(first);
    }
    while parts.first().is_some_and(|l| l.trim().is_empty()) {
        parts.remove(0);
    }
    while parts.last().is_some_and(|l| l.trim().is_empty()) {
        parts.pop();
    }
    parts.join("\n")
}

fn count_newlines(s: &str) -> usize {
    s.bytes().filter(|b| *b == b'\n').count()
}

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

    #[test]
    fn strip_removes_comment_only_lines_entirely() {
        let src = "a();\n// gone\nb(); // tail\n";
        assert_eq!(strip_comments(src), "a();\nb();\n");
    }

    #[test]
    fn preserve_lines_keeps_numbering() {
        let src = "a();\n// gone\n/* two\nlines */\nb();\n";
        let out = strip_comments_with(
            src,
            &Dialect::CFamily.syntax(),
            &Options::default().preserve_lines(true),
        );
        assert_eq!(out, "a();\n\n\n\nb();\n");
        assert_eq!(out.lines().count(), src.lines().count());
    }

    #[test]
    fn extraction_strips_markers_and_stars() {
        let src = "/**\n * One.\n * Two.\n */\nfn x() {} // three\n";
        assert_eq!(extract_comments(src), "One.\nTwo.\nthree\n");
        // Comments separated by code get a blank line between them.
        let src = "// one\nfn a() {}\nfn b() {}\n// two\n";
        assert_eq!(extract_comments(src), "one\n\ntwo\n");
    }

    #[test]
    fn extraction_can_keep_markers() {
        let src = "x = 1 # note\n";
        let opts = Options::default().keep_markers(true);
        assert_eq!(
            extract_comments_with(src, &Dialect::Hash.syntax(), &opts),
            "# note\n"
        );
    }

    #[test]
    fn unknown_syntax_is_a_no_op() {
        let src = "just prose, nothing else\n";
        assert_eq!(strip_comments(src), src);
        assert_eq!(extract_comments(src), "");
    }

    #[test]
    fn input_without_trailing_newline_stays_that_way() {
        let syn = Dialect::CFamily.syntax();
        let o = Options::default();
        assert_eq!(strip_comments_with("x = 1; // c", &syn, &o), "x = 1;");
        assert_eq!(strip_comments_with("x = 1;", &syn, &o), "x = 1;");
        assert_eq!(strip_comments_with("x = 1;\n// c", &syn, &o), "x = 1;\n");
    }

    #[test]
    fn a_lone_fragment_is_too_little_evidence_to_act_on() {
        // Deleting real code is worse than leaving a comment behind, so a single
        // ambiguous line is left alone. Name the syntax to override that.
        assert_eq!(strip_comments("x = 1; // c"), "x = 1; // c");
    }

    #[test]
    fn crlf_line_endings_survive() {
        let src = "a();\r\n// gone\r\nb(); // tail\r\n";
        assert_eq!(strip_comments(src), "a();\r\nb();\r\n");
    }

    #[test]
    fn docstrings_are_opt_in() {
        let src = "def f():\n    \"\"\"Doc.\"\"\"\n    return 1\n# c\n";
        let syn = Dialect::Hash.syntax();
        assert_eq!(
            strip_comments_with(src, &syn, &Options::default()),
            "def f():\n    \"\"\"Doc.\"\"\"\n    return 1\n"
        );
        let opts = Options::default().docstrings(true);
        assert_eq!(
            strip_comments_with(src, &syn, &opts),
            "def f():\n    return 1\n"
        );
        assert_eq!(extract_comments_with(src, &syn, &opts), "Doc.\n\nc\n");
    }

    #[test]
    fn stripping_never_grows_the_input() {
        for src in [
            "// a\n",
            "#!/bin/sh\n# a\necho \"# not\"\n",
            "<!-- x -->\n<p>y</p>\n",
            "SELECT 1; -- c\n",
            "",
        ] {
            assert!(strip_comments(src).len() <= src.len(), "{src:?}");
        }
    }
}