brrr-lint 0.1.0

A fast linter and language server for F* (FStar) with autofix capabilities
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
//! FST006: Naming convention checker for F* code.
//!
//! F* naming conventions (derived from community codebase analysis of FStar stdlib,
//! hacl-star, everparse, and other major projects):
//!
//! - Modules: CamelCase.Dot.Separated (e.g., FStar.List.Tot)
//! - Types: Must start with lowercase. Both snake_case (nat, pure_wp, int_t) and
//!   camelCase (inttype, secrecy_level) are accepted. PascalCase types are flagged
//!   because they look like constructors or module names.
//! - Functions/values: Must start with lowercase. Both snake_case (fold_left) and
//!   camelCase (loadState, createL, mapT) are widely used in the community.
//!   PascalCase (starts with uppercase) is flagged as it conflicts with
//!   constructor/module/effect conventions.
//! - Lemmas: lemma_* prefix or *_lemma suffix
//! - Effects: CamelCase starting with uppercase (e.g., Tot, GTot, Lemma, Stack)
//! - Constructors: CamelCase (Some, None, U8, Cons) - not checked here as the
//!   parser extracts type names, not constructor names.

use lazy_static::lazy_static;
use regex::Regex;
use std::path::PathBuf;

use super::parser::{parse_fstar_file, BlockType};
use super::rules::{Diagnostic, DiagnosticSeverity, Range, Rule, RuleCode};

lazy_static! {
    /// Pattern for valid F* value/type names: starts with lowercase or underscore,
    /// followed by any alphanumeric or underscore. Accepts both snake_case and
    /// camelCase since the F* community uses both freely (e.g., fold_left,
    /// loadState, createL, mapT, storeState_inner, ivTable_S).
    static ref LOWERCASE_START: Regex = Regex::new(r"^[a-z_][a-zA-Z0-9_]*$").unwrap();

    /// Pattern for CamelCase identifiers: starts with uppercase letter,
    /// followed by alphanumeric characters. Used for effects.
    static ref CAMEL_CASE: Regex = Regex::new(r"^[A-Z][a-zA-Z0-9]*$").unwrap();

    /// Pattern for PascalCase identifiers: starts with uppercase letter.
    /// Used to detect type/function names that look like constructors or modules.
    static ref STARTS_UPPERCASE: Regex = Regex::new(r"^[A-Z]").unwrap();

}

/// Check if name starts with lowercase (valid for F* types, functions, values).
/// Both snake_case and camelCase are accepted since the F* community uses both.
fn is_lowercase_start(name: &str) -> bool {
    LOWERCASE_START.is_match(name)
}

/// Check if name follows CamelCase convention (for effects).
fn is_camel_case(name: &str) -> bool {
    CAMEL_CASE.is_match(name)
}

/// Check if name starts with uppercase (looks like constructor/module/effect).
fn starts_with_uppercase(name: &str) -> bool {
    STARTS_UPPERCASE.is_match(name)
}

/// Convert a PascalCase name to snake_case for suggestion purposes.
///
/// Examples:
/// - "BadType" -> "bad_type"
/// - "FooBar" -> "foo_bar"
/// - "XMLParser" -> "xml_parser"
fn to_snake_case(name: &str) -> String {
    let mut result = String::with_capacity(name.len() + 4);
    let mut prev_was_upper = false;
    let mut prev_was_underscore = true; // Treat start as if preceded by underscore

    for (i, c) in name.chars().enumerate() {
        if c.is_uppercase() {
            // Add underscore before uppercase if:
            // - Not at start
            // - Previous char was not uppercase (to handle "HTTPServer" -> "http_server")
            // - Or next char is lowercase (to handle "XMLParser" -> "xml_parser")
            if i > 0 && !prev_was_underscore {
                let next_is_lower = name
                    .chars()
                    .nth(i + 1)
                    .map(|n| n.is_lowercase())
                    .unwrap_or(false);
                if !prev_was_upper || next_is_lower {
                    result.push('_');
                }
            }
            result.push(c.to_ascii_lowercase());
            prev_was_upper = true;
            prev_was_underscore = false;
        } else if c == '_' {
            result.push(c);
            prev_was_upper = false;
            prev_was_underscore = true;
        } else {
            result.push(c);
            prev_was_upper = false;
            prev_was_underscore = false;
        }
    }

    result
}

/// FST006: Naming convention checker rule.
pub struct NamingRule;

impl NamingRule {
    pub fn new() -> Self {
        Self
    }
}

impl Default for NamingRule {
    fn default() -> Self {
        Self::new()
    }
}

impl Rule for NamingRule {
    fn code(&self) -> RuleCode {
        RuleCode::FST006
    }

    fn check(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();
        let (_, blocks) = parse_fstar_file(content);

        for block in &blocks {
            for name in &block.names {
                // Skip names starting with underscore (intentionally unused/internal)
                if name.starts_with('_') {
                    continue;
                }

                // Strip trailing primes for checking (e.g., expr', pattern')
                let check_name = name.trim_end_matches('\'');
                if check_name.is_empty() {
                    continue;
                }

                match block.block_type {
                    BlockType::Type => {
                        // Types must start with lowercase in F*.
                        // Names starting with uppercase look like constructors or modules.
                        if starts_with_uppercase(check_name) {
                            let suggested = to_snake_case(check_name);
                            diagnostics.push(Diagnostic {
                                rule: RuleCode::FST006,
                                severity: DiagnosticSeverity::Info,
                                file: file.clone(),
                                range: Range::point(block.start_line, 1),
                                message: format!(
                                    "Type `{}` should start with lowercase. \
                                     PascalCase is reserved for constructors/modules. \
                                     Suggested: `{}`",
                                    name, suggested
                                ),
                                fix: None,
                            });
                        }
                    }

                    BlockType::Let
                    | BlockType::Val
                    | BlockType::UnfoldLet
                    | BlockType::InlineLet => {
                        // Functions/values must start with lowercase in F*.
                        // Both snake_case and camelCase are accepted.
                        if starts_with_uppercase(check_name) {
                            let suggested = to_snake_case(check_name);
                            diagnostics.push(Diagnostic {
                                rule: RuleCode::FST006,
                                severity: DiagnosticSeverity::Info,
                                file: file.clone(),
                                range: Range::point(block.start_line, 1),
                                message: format!(
                                    "Function/value `{}` should start with lowercase. \
                                     PascalCase is reserved for constructors/modules. \
                                     Suggested: `{}`",
                                    name, suggested
                                ),
                                fix: None,
                            });
                        }
                    }

                    BlockType::Effect => {
                        // Effects must start with uppercase (CamelCase) in F*.
                        if !starts_with_uppercase(check_name) {
                            diagnostics.push(Diagnostic {
                                rule: RuleCode::FST006,
                                severity: DiagnosticSeverity::Info,
                                file: file.clone(),
                                range: Range::point(block.start_line, 1),
                                message: format!(
                                    "Effect `{}` should use CamelCase (start with uppercase)",
                                    name
                                ),
                                fix: None,
                            });
                        }
                    }

                    // Skip other block types (Module, Open, Friend, etc.)
                    _ => {}
                }
            }
        }

        diagnostics
    }
}

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

    #[test]
    fn test_is_lowercase_start() {
        // snake_case: valid
        assert!(is_lowercase_start("foo"));
        assert!(is_lowercase_start("foo_bar"));
        assert!(is_lowercase_start("foo_bar_baz"));
        assert!(is_lowercase_start("_internal"));
        assert!(is_lowercase_start("int_t"));
        assert!(is_lowercase_start("nat"));

        // camelCase: also valid in F*
        assert!(is_lowercase_start("fooBar"));
        assert!(is_lowercase_start("loadState"));
        assert!(is_lowercase_start("createL"));
        assert!(is_lowercase_start("mapT"));
        assert!(is_lowercase_start("storeState_inner"));
        assert!(is_lowercase_start("ivTable_S"));
        assert!(is_lowercase_start("modBits_t"));

        // PascalCase: invalid for types/values
        assert!(!is_lowercase_start("Foo"));
        assert!(!is_lowercase_start("FooBar"));
        assert!(!is_lowercase_start("FOO_BAR"));
    }

    #[test]
    fn test_starts_with_uppercase() {
        assert!(starts_with_uppercase("Foo"));
        assert!(starts_with_uppercase("FooBar"));
        assert!(starts_with_uppercase("Tot"));
        assert!(starts_with_uppercase("GTot"));
        assert!(starts_with_uppercase("FOO_BAR"));

        assert!(!starts_with_uppercase("foo"));
        assert!(!starts_with_uppercase("fooBar"));
        assert!(!starts_with_uppercase("_foo"));
    }

    #[test]
    fn test_is_camel_case() {
        assert!(is_camel_case("Foo"));
        assert!(is_camel_case("FooBar"));
        assert!(is_camel_case("Tot"));
        assert!(is_camel_case("GTot"));
        assert!(is_camel_case("Lemma"));

        assert!(!is_camel_case("foo"));
        assert!(!is_camel_case("foo_bar"));
        assert!(!is_camel_case("fooBar"));
    }

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("BadType"), "bad_type");
        assert_eq!(to_snake_case("FooBar"), "foo_bar");
        assert_eq!(to_snake_case("foo"), "foo");
        assert_eq!(to_snake_case("XMLParser"), "xml_parser");
    }

    #[test]
    fn test_naming_rule_type_pascal_case_flagged() {
        let rule = NamingRule::new();
        let content = r#"module Test

type BadType = int
type good_type = int
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        // Should flag BadType (PascalCase) but not good_type
        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics[0].message.contains("BadType"));
        assert!(diagnostics[0].message.contains("lowercase"));
    }

    #[test]
    fn test_naming_rule_type_camelcase_accepted() {
        let rule = NamingRule::new();
        let content = r#"module Test

type inttype = int
type range_t = int
type secrecy_level = int
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        // All snake_case types are fine
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_naming_rule_function_camelcase_accepted() {
        // camelCase function names are common in F* (loadState, createL, mapT, etc.)
        let rule = NamingRule::new();
        let content = r#"module Test

val loadState : int -> int
let loadState x = x

val createL : int -> int
let createL x = x

val storeState_inner : int -> int
let storeState_inner x = x

val good_func : int -> int
let good_func x = x
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        // None should be flagged: camelCase and snake_case are both valid
        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics for camelCase functions, got: {:?}",
            diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_naming_rule_function_pascal_case_flagged() {
        // PascalCase (starts with uppercase) is wrong for functions
        let rule = NamingRule::new();
        let content = r#"module Test

val BadFunc : int -> int
let BadFunc x = x
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        // Should flag BadFunc (PascalCase) for both val and let
        assert_eq!(diagnostics.len(), 2);
        assert!(diagnostics[0].message.contains("BadFunc"));
        assert!(diagnostics[0].message.contains("lowercase"));
    }

    #[test]
    fn test_naming_rule_effect() {
        let rule = NamingRule::new();
        let content = r#"module Test

effect bad_effect = Tot
effect GoodEffect = Tot
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        // Should flag bad_effect but not GoodEffect
        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics[0].message.contains("bad_effect"));
        assert!(diagnostics[0].message.contains("CamelCase"));
    }

    #[test]
    fn test_naming_rule_underscore_prefix() {
        let rule = NamingRule::new();
        let content = r#"module Test

val _internal : int -> int
let _internal x = x
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        // Should not flag _internal (starts with underscore)
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_naming_rule_primed_names() {
        let rule = NamingRule::new();
        let content = r#"module Test

val foo' : int -> int
let foo' x = x

val loadState' : int -> int
let loadState' x = x
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        // Primed names with valid bases should not be flagged
        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics for primed names, got: {:?}",
            diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_naming_rule_hacl_star_patterns() {
        // Real patterns from hacl-star that MUST NOT be flagged
        let rule = NamingRule::new();
        let content = r#"module Test

val sigmaTable : int -> int
let sigmaTable x = x

val ivTable_S : int -> int
let ivTable_S x = x

val rTable_B : int -> int
let rTable_B x = x

val msgHash2 : int -> int
let msgHash2 x = x

val modBits_t : int -> int
let modBits_t x = x

inline_for_extraction let fillT x = x

unfold let createL x = x
"#;
        let file = PathBuf::from("test.fst");
        let diagnostics = rule.check(&file, content);

        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics for hacl-star patterns, got: {:?}",
            diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
        );
    }
}