cargo-gears-lints 0.0.1

Dylint lint collection for cargo-gears architectural rules
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
extern crate rustc_ast;
extern crate rustc_span;

use crate::lint_utils::{filename_str, is_temp_path};
use gts::{GtsIdSegment, GtsOps};
use rustc_ast::token::LitKind;
use rustc_ast::{AttrKind, Attribute, Expr, ExprKind, Item, ItemKind};
use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
use rustc_span::Span;
use std::cell::RefCell;
use std::collections::HashSet;

// Thread-local storage for spans to skip (inside starts_with calls)
thread_local! {
    static SKIP_SPANS: RefCell<HashSet<Span>> = RefCell::new(HashSet::new());
    static IN_TEST_DEPTH: RefCell<u32> = const { RefCell::new(0) };
}

fn default_allowed_vendors() -> Vec<String> {
    vec!["cf".to_owned()]
}

fn default_test_allowed_vendors() -> Vec<String> {
    [
        "cf", "vendor", "example", "fabrikam", "contoso", "acme", "globex",
    ]
    .iter()
    .map(|&s| s.to_owned())
    .collect()
}

#[derive(serde::Deserialize)]
struct Config {
    #[serde(default = "default_allowed_vendors")]
    allowed_vendors: Vec<String>,
    #[serde(default = "default_test_allowed_vendors")]
    test_allowed_vendors: Vec<String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            allowed_vendors: default_allowed_vendors(),
            test_allowed_vendors: default_test_allowed_vendors(),
        }
    }
}

pub(crate) struct De0901GtsStringPattern {
    allowed_vendors: Vec<String>,
    test_allowed_vendors: Vec<String>,
}

impl De0901GtsStringPattern {
    pub fn new() -> Self {
        let config: Config = dylint_linting::config_or_default(crate::LIBRARY_NAME);
        Self {
            allowed_vendors: config.allowed_vendors,
            test_allowed_vendors: config.test_allowed_vendors,
        }
    }
}

dylint_linting::impl_pre_expansion_lint! {
    /// ### What it does
    ///
    /// Validates GTS schema identifiers used by `gts-macros`.
    ///
    /// Checks:
    /// 1. `schema_id = "..."` in `#[struct_to_gts_schema(...)]` - must be valid GTS type schema
    /// 2. `gts_make_instance_id("...")` - must be valid GTS instance segment id
    /// 3. GTS-looking string literals - must be valid GTS entity id
    ///
    /// Uses `GtsOps::parse_id()` from the GTS library for validation.
    #[doc = include_str!("../../docs/de09_gts_layer/de0901_gts_string_pattern/README.md")]
    pub DE0901_GTS_STRING_PATTERN,
    Deny,
    "invalid GTS string pattern (DE0901)",
    De0901GtsStringPattern::new()
}

impl EarlyLintPass for De0901GtsStringPattern {
    fn check_crate_post(&mut self, _cx: &EarlyContext<'_>, _krate: &rustc_ast::Crate) {
        SKIP_SPANS.with(|s| s.borrow_mut().clear());
        IN_TEST_DEPTH.with(|d| *d.borrow_mut() = 0);
    }

    fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
        self.check_struct_to_gts_schema_attr(cx, attr);
    }

    /// Enforce naming convention for `const`/`static` items holding GTS wildcard strings.
    ///
    /// A wildcard GTS string (contains `*`) stored in a `const` or `static` item
    /// **must** have a name ending with `_WILDCARD`.  This makes wildcard constants
    /// explicitly opt-in and easy to audit.
    ///
    /// | Item name         | Value                             | Result  |
    /// |-------------------|-----------------------------------|---------|
    /// | `SRR_WILDCARD`    | `"gts.cf.core.srr.resource.v1~*"` | ✅ allowed — name ends with `_WILDCARD` |
    /// | `SRR_PATTERN`     | `"gts.cf.core.srr.resource.v1~*"` | ❌ flagged — name must end with `_WILDCARD` |
    ///
    /// Items with a compliant name are added to the skip set so their value span
    /// is not re-checked by `check_expr`.
    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
        if is_test_item(item) {
            IN_TEST_DEPTH.with(|d| *d.borrow_mut() += 1);
        }

        // Extract both the item name and the initializer expression from const/static items.
        // Note: `Item` has no top-level `ident`; it lives inside `ConstItem` / `StaticItem`.
        let (item_name, init_expr): (&str, Option<&Expr>) = match &item.kind {
            ItemKind::Const(ci) => (
                ci.ident.name.as_str(),
                ci.rhs.as_ref().map(|rhs| rhs.expr()),
            ),
            ItemKind::Static(si) => (si.ident.name.as_str(), si.expr.as_deref()),
            _ => return,
        };
        let Some(init) = init_expr else { return };

        // Only act on GTS wildcard string values (starts with "gts." and contains '*').
        let Some(s) = Self::string_lit_value(init) else {
            return;
        };
        if !s.starts_with("gts.") || !s.contains('*') {
            return;
        }

        // Validate the wildcard GTS pattern itself before skip-listing.
        let result = GtsOps::parse_id(s);
        if !result.ok {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, item.span, |diag| {
                diag.primary_message(format!(
                    "invalid GTS wildcard pattern in `{item_name}`: '{s}' (DE0901)"
                ));
                diag.note(result.error);
                diag.help("Example: gts.cf.core.srr.resource.v1~*");
            });
            // Still skip-list so check_expr doesn't double-report the literal.
            SKIP_SPANS.with(|spans| {
                collect_nested_spans(init, &mut spans.borrow_mut());
            });
            return;
        }

        self.check_vendors_in_parse_result(cx, item.span, s, &result);

        if !item_name.ends_with("_WILDCARD") {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, item.span, |diag| {
                diag.primary_message(format!(
                    "GTS wildcard string in `const`/`static` `{item_name}` must have a name ending with `_WILDCARD` (DE0901)"
                ));
                diag.note(format!(
                    "found wildcard GTS pattern `{s}` stored in `{item_name}`"
                ));
                diag.help(format!(
                    "rename to `{item_name}_WILDCARD` or use a non-wildcard value"
                ));
            });
        }

        // Skip-list the span so check_expr doesn't re-flag (or double-report) the literal.
        SKIP_SPANS.with(|spans| {
            collect_nested_spans(init, &mut spans.borrow_mut());
        });
    }

    fn check_item_post(&mut self, _cx: &EarlyContext<'_>, item: &Item) {
        if is_test_item(item) {
            IN_TEST_DEPTH.with(|d| *d.borrow_mut() -= 1);
        }
    }

    fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
        // ── Phase 1: collect spans to skip ────────────────────────────────────
        if let ExprKind::MethodCall(method_call) = &expr.kind {
            let method_name = method_call.seg.ident.name.as_str();
            if method_name == "starts_with" {
                // Add the receiver and all arguments to skip list
                SKIP_SPANS.with(|spans| {
                    let mut spans = spans.borrow_mut();
                    spans.insert(method_call.receiver.span);
                    for arg in &method_call.args {
                        spans.insert(arg.span);
                    }
                });
                // Don't check anything in starts_with calls
                return;
            }
            if method_name == "resource_pattern"
                || method_name == "with_pattern"
                || method_name == "resolve_to_uuids"
            {
                // Validate nested string literals BEFORE skip-listing so that
                // deeply nested GTS strings (e.g. inside &["gts...".to_owned()])
                // are checked rather than silently escaping validation.
                for arg in &method_call.args {
                    self.validate_nested_gts_strings(cx, arg, true);
                }
                // Then add all nested sub-expression spans to the skip list
                // to prevent duplicate reports from check_expr.
                SKIP_SPANS.with(|spans| {
                    let mut spans = spans.borrow_mut();
                    for arg in &method_call.args {
                        collect_nested_spans(arg, &mut spans);
                    }
                });
            }
        }

        // Detect free-function calls: `GtsWildcard::new("...")` or `SomeType::new(...)` where
        // the path contains "GtsWildcard".  Arguments are allowed to contain wildcards.
        if let ExprKind::Call(func, args) = &expr.kind
            && is_gts_wildcard_new_call(func)
        {
            SKIP_SPANS.with(|spans| {
                let mut spans = spans.borrow_mut();
                for arg in args {
                    collect_nested_spans(arg, &mut spans);
                }
            });
            // Validate args (including nested literals) as wildcard-allowed
            // patterns and return early.
            for arg in args {
                self.validate_nested_gts_strings(cx, arg, true);
            }
            return;
        }

        // ── Phase 2: skip if this expression was marked ────────────────────────
        let should_skip = SKIP_SPANS.with(|spans| spans.borrow().contains(&expr.span));
        if should_skip {
            return;
        }

        self.check_gts_make_instance_id_call(cx, expr);

        // Check if this is a method call - handle resource_pattern and with_pattern specially
        if let ExprKind::MethodCall(method_call) = &expr.kind {
            let method_name = method_call.seg.ident.name.as_str();
            // Already validated in Phase 1 via validate_nested_gts_strings
            if method_name == "resource_pattern"
                || method_name == "with_pattern"
                || method_name == "resolve_to_uuids"
            {
                return;
            }

            // Check arguments of other method calls normally
            for arg in &method_call.args {
                self.check_gts_string_literal(cx, arg);
            }
            return;
        }

        // For non-method-call expressions, check normally
        self.check_gts_string_literal(cx, expr);
    }
}

/// Recursively collect spans from all sub-expressions so that deeply nested
/// string literals (e.g. inside `&["gts...".to_owned()]`) are included in the
/// skip set.
fn collect_nested_spans(expr: &Expr, spans: &mut HashSet<Span>) {
    spans.insert(expr.span);
    match &expr.kind {
        ExprKind::MethodCall(mc) => {
            collect_nested_spans(&mc.receiver, spans);
            for arg in &mc.args {
                collect_nested_spans(arg, spans);
            }
        }
        ExprKind::AddrOf(_, _, inner) => {
            collect_nested_spans(inner, spans);
        }
        ExprKind::Array(elements) => {
            for elem in elements {
                collect_nested_spans(elem, spans);
            }
        }
        ExprKind::Call(func, args) => {
            collect_nested_spans(func, spans);
            for arg in args {
                collect_nested_spans(arg, spans);
            }
        }
        ExprKind::Tup(elements) => {
            for elem in elements {
                collect_nested_spans(elem, spans);
            }
        }
        ExprKind::Paren(inner) => {
            collect_nested_spans(inner, spans);
        }
        _ => {}
    }
}

/// Returns `true` if `func_expr` is a path call of the form `GtsWildcard::new`
/// (or `gts::GtsWildcard::new`, `<anything>::GtsWildcard::new`, etc.).
///
/// We check that:
/// 1. The expression is a `Path` with at least two segments.
/// 2. The last segment is named `new`.
/// 3. At least one other segment is named `GtsWildcard`.
fn is_gts_wildcard_new_call(func_expr: &Expr) -> bool {
    let ExprKind::Path(_, path) = &func_expr.kind else {
        return false;
    };
    let segments = &path.segments;
    if segments.len() < 2 {
        return false;
    }
    let last = segments.last().unwrap();
    if last.ident.name.as_str() != "new" {
        return false;
    }
    segments
        .iter()
        .any(|seg| seg.ident.name.as_str() == "GtsWildcard")
}

fn is_in_test() -> bool {
    IN_TEST_DEPTH.with(|d| *d.borrow() > 0)
}

fn is_ui_test(cx: &EarlyContext<'_>, span: Span) -> bool {
    let Some(file_path) = filename_str(cx.sess().source_map(), span) else {
        return false;
    };
    is_temp_path(&file_path)
}

/// Returns `true` if the item is annotated with `#[cfg(test)]` or `#[test]`.
fn is_test_item(item: &Item) -> bool {
    item.attrs.iter().any(|attr| {
        let AttrKind::Normal(normal) = &attr.kind else {
            return false;
        };
        let segments = &normal.item.path.segments;
        if segments.len() != 1 {
            return false;
        }
        let name = segments[0].ident.name.as_str();
        if name == "test" {
            return true;
        }
        if name == "cfg"
            && let Some(items) = normal.item.meta_item_list()
        {
            return items.iter().any(|nested| {
                nested.meta_item().is_some_and(|mi| {
                    mi.path.segments.len() == 1 && mi.path.segments[0].ident.name.as_str() == "test"
                })
            });
        }
        false
    })
}

impl De0901GtsStringPattern {
    fn check_gts_make_instance_id_call(&self, cx: &EarlyContext<'_>, expr: &Expr) {
        let ExprKind::Call(func, args) = &expr.kind else {
            return;
        };

        if args.len() != 1 {
            return;
        }

        let Some(arg0) = args.first() else {
            return;
        };

        let Some(arg_str) = Self::string_lit_value(arg0) else {
            return;
        };

        // Detect `...::gts_make_instance_id("...")`
        let ExprKind::Path(_, path) = &func.kind else {
            return;
        };

        let Some(last) = path.segments.last() else {
            return;
        };

        if last.ident.name.as_str() != "gts_make_instance_id" {
            return;
        }

        self.validate_instance_id_segment(cx, expr.span, arg_str);
    }

    /// Recursively traverse an expression tree and validate any GTS string
    /// literals found within. Mirrors the structure of `collect_nested_spans`
    /// so that every string literal that would be skip-listed is also validated.
    fn validate_nested_gts_strings(
        &self,
        cx: &EarlyContext<'_>,
        expr: &Expr,
        allow_wildcards: bool,
    ) {
        // If this is a string literal, validate it directly
        if Self::string_lit_value(expr).is_some() {
            self.check_gts_string_literal_with_wildcard_flag(cx, expr, allow_wildcards);
            return;
        }
        // Otherwise, recurse into sub-expressions
        match &expr.kind {
            ExprKind::MethodCall(mc) => {
                self.validate_nested_gts_strings(cx, &mc.receiver, allow_wildcards);
                for arg in &mc.args {
                    self.validate_nested_gts_strings(cx, arg, allow_wildcards);
                }
            }
            ExprKind::AddrOf(_, _, inner) => {
                self.validate_nested_gts_strings(cx, inner, allow_wildcards);
            }
            ExprKind::Array(elements) => {
                for elem in elements {
                    self.validate_nested_gts_strings(cx, elem, allow_wildcards);
                }
            }
            ExprKind::Call(_, args) => {
                for arg in args {
                    self.validate_nested_gts_strings(cx, arg, allow_wildcards);
                }
            }
            ExprKind::Tup(elements) => {
                for elem in elements {
                    self.validate_nested_gts_strings(cx, elem, allow_wildcards);
                }
            }
            ExprKind::Paren(inner) => {
                self.validate_nested_gts_strings(cx, inner, allow_wildcards);
            }
            _ => {}
        }
    }

    fn check_gts_string_literal(&self, cx: &EarlyContext<'_>, expr: &Expr) {
        self.check_gts_string_literal_with_wildcard_flag(cx, expr, false);
    }

    fn check_gts_string_literal_with_wildcard_flag(
        &self,
        cx: &EarlyContext<'_>,
        expr: &Expr,
        allow_wildcards: bool,
    ) {
        if let Some(s) = Self::string_lit_value(expr) {
            let s = s.trim();

            // Option 1: String starts with "gts." - validate directly
            if s.starts_with("gts.") {
                if allow_wildcards {
                    self.validate_any_gts_id_allow_wildcards(cx, expr.span, s);
                } else {
                    self.validate_any_gts_id(cx, expr.span, s);
                }
                return;
            }

            // Option 2: String contains ":" - this is a permission string format
            // Permission strings ALWAYS allow wildcards in their GTS parts
            if s.contains(':') {
                for part in s.split(':') {
                    if part.trim().starts_with("gts.") {
                        self.validate_any_gts_id_allow_wildcards(cx, expr.span, part.trim());
                        break; // Only validate the first GTS part found
                    }
                }
            }
        }
    }

    fn string_lit_value(expr: &Expr) -> Option<&str> {
        match &expr.kind {
            ExprKind::Lit(lit) => match lit.kind {
                LitKind::Str | LitKind::StrRaw(_) => Some(lit.symbol.as_str()),
                _ => None,
            },
            _ => None,
        }
    }

    fn check_struct_to_gts_schema_attr(&self, cx: &EarlyContext<'_>, attr: &Attribute) {
        let AttrKind::Normal(normal_attr) = &attr.kind else {
            return;
        };

        // We only care about #[struct_to_gts_schema(...)]
        if normal_attr.item.path.segments.len() != 1
            || normal_attr.item.path.segments[0].ident.name.as_str() != "struct_to_gts_schema"
        {
            return;
        }

        let Some(items) = normal_attr.item.meta_item_list() else {
            return;
        };

        for nested in items {
            let Some(mi) = nested.meta_item() else {
                continue;
            };

            if mi.path.segments.len() != 1 || mi.path.segments[0].ident.name.as_str() != "schema_id"
            {
                continue;
            }

            let Some(val) = mi.value_str() else {
                continue;
            };

            self.validate_schema_id(cx, mi.span, val.as_str());
        }
    }

    /// Validate a GTS schema_id using GtsOps::parse_id()
    /// schema_id must be a valid GTS type schema (ending with ~)
    fn validate_schema_id(&self, cx: &EarlyContext<'_>, span: rustc_span::Span, s: &str) {
        let s = s.trim();

        // Wildcards are NOT allowed in schema_id
        if s.contains('*') {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!("wildcards are not allowed in schema_id: '{}' (DE0901)", s));
                diag.note("Wildcards (*) are only allowed in permission strings, not in schema_id attributes");
                diag.help("Use concrete type names in schema_id");
            });
            return;
        }

        // Use GtsOps::parse_id() for validation - it gives us parsed segments
        let result = GtsOps::parse_id(s);

        if !result.ok {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!("invalid GTS schema_id: '{}' (DE0901)", s));
                diag.note(result.error);
                diag.help("Example: gts.cf.core.events.type.v1~");
            });
            return;
        }

        // Ensure it's actually a schema (type), not an instance
        if result.is_schema != Some(true) {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!(
                    "schema_id must be a type schema, not an instance: '{}' (DE0901)",
                    s
                ));
                diag.note("schema_id must end with '~' to indicate it's a type schema");
                diag.help("Example: gts.cf.core.events.type.v1~");
            });
        } else {
            self.check_vendors_in_parse_result(cx, span, s, &result);
        }
    }

    fn allowed_vendors(&self, cx: &EarlyContext<'_>, span: Span) -> &[String] {
        if is_in_test() || is_ui_test(cx, span) {
            &self.test_allowed_vendors
        } else {
            &self.allowed_vendors
        }
    }

    fn format_vendors(vendors: &[String]) -> String {
        vendors.join(", ")
    }

    fn validate_instance_id_segment(&self, cx: &EarlyContext<'_>, span: rustc_span::Span, s: &str) {
        let s = s.trim();

        // `gts_make_instance_id` accepts a single *segment id* (no `gts.` prefix),
        // so we must not validate it as a full GTS ID.
        // If the input contains delimiters for chained ids / permission strings,
        // it is not a single segment.
        if s.contains('~') || s.contains(':') {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!(
                    "gts_make_instance_id expects a single GTS segment, got: '{}' (DE0901)",
                    s
                ));
                diag.help("Example: vendor.package.sku.abc.v1");
            });
            return;
        }

        if s.contains('*') {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!(
                    "wildcards are not allowed in instance id segments: '{}' (DE0901)",
                    s
                ));
                diag.help("Example: vendor.package.sku.abc.v1");
            });
            return;
        }

        let vendors = self.allowed_vendors(cx, span);
        match GtsIdSegment::new(0, 0, s) {
            Err(e) => {
                cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                    diag.primary_message(format!("invalid GTS segment: '{}' (DE0901)", s));
                    diag.note(e.to_string());
                    diag.help("Example: vendor.package.sku.abc.v1");
                });
            }
            Ok(seg) if !vendors.iter().any(|v| v == &seg.vendor) => {
                cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                    diag.primary_message(format!(
                        "invalid GTS vendor in segment: '{}' (DE0901)",
                        s
                    ));
                    diag.note(format!(
                        "found vendor '{}', allowed vendors: {}",
                        seg.vendor,
                        Self::format_vendors(vendors),
                    ));
                });
            }
            Ok(_) => {}
        }
    }

    fn check_vendors_in_parse_result(
        &self,
        cx: &EarlyContext<'_>,
        span: rustc_span::Span,
        s: &str,
        result: &gts::ops::GtsIdParseResult,
    ) {
        let vendors = self.allowed_vendors(cx, span);
        for (idx, seg) in result.segments.iter().enumerate() {
            if seg.vendor.is_empty()
                || seg.vendor == "*"
                || vendors.iter().any(|v| v == &seg.vendor)
            {
                continue;
            }
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!(
                    "invalid GTS vendor in segment #{idx}: '{}' (DE0901)",
                    s
                ));
                diag.note(format!(
                    "found vendor '{}', allowed vendors: {}",
                    seg.vendor,
                    Self::format_vendors(vendors),
                ));
            });
            break;
        }
    }

    fn validate_any_gts_id(&self, cx: &EarlyContext<'_>, span: rustc_span::Span, s: &str) {
        let s = s.trim();

        // Wildcards are NOT allowed in regular GTS strings (only in permission strings)
        if s.contains('*') {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!("invalid GTS string (wildcards not allowed): '{}' (DE0901)", s));
                diag.note("Wildcards (*) are only allowed in permission strings, not in regular GTS identifiers");
                diag.help("Use concrete type names");
            });
            return;
        }

        let result = GtsOps::parse_id(s);

        if !result.ok {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!("invalid GTS string: '{}' (DE0901)", s));
                diag.note(result.error);
            });
        } else {
            self.check_vendors_in_parse_result(cx, span, s, &result);
        }
    }

    fn validate_any_gts_id_allow_wildcards(
        &self,
        cx: &EarlyContext<'_>,
        span: rustc_span::Span,
        s: &str,
    ) {
        let s = s.trim();

        // For resource_pattern calls, we allow wildcards but still validate the GTS structure
        let result = GtsOps::parse_id(s);

        if !result.ok {
            cx.span_lint(DE0901_GTS_STRING_PATTERN, span, |diag| {
                diag.primary_message(format!("invalid GTS string: '{}' (DE0901)", s));
                diag.note(result.error);
            });
        } else {
            self.check_vendors_in_parse_result(cx, span, s, &result);
        }
    }
}