mir-types 0.26.0

Type system primitives for the mir PHP static analyzer
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
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
use std::hash::Hash;
use std::sync::Arc;

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::Union;

// ---------------------------------------------------------------------------
// FnParam — used inside callable/closure atomics
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FnParam {
    pub name: Arc<str>,
    /// Parameter type stored as SimpleType for compact representation.
    /// Most params are simple scalars (string, int, etc.) and fit inline.
    pub ty: Option<crate::compact::SimpleType>,
    /// Default value stored as SimpleType. Usually None or a simple scalar.
    pub default: Option<crate::compact::SimpleType>,
    pub is_variadic: bool,
    pub is_byref: bool,
    pub is_optional: bool,
}

// ---------------------------------------------------------------------------
// Variance — covariance / contravariance for template type parameters
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum Variance {
    /// Default: exact type match required (no `@template-covariant` / `@template-contravariant`).
    #[default]
    Invariant,
    /// `@template-covariant T` — `C<Sub>` is assignable to `C<Super>`.
    Covariant,
    /// `@template-contravariant T` — `C<Super>` is assignable to `C<Sub>`.
    Contravariant,
}

// ---------------------------------------------------------------------------
// TemplateParam — `@template T` / `@template T of Bound`
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TemplateParam {
    pub name: Arc<str>,
    pub bound: Option<Union>,
    pub variance: Variance,
}

// ---------------------------------------------------------------------------
// KeyedProperty — entry in TKeyedArray
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ArrayKey {
    String(Arc<str>),
    Int(i64),
}

impl PartialOrd for ArrayKey {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ArrayKey {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match (self, other) {
            (ArrayKey::Int(a), ArrayKey::Int(b)) => a.cmp(b),
            (ArrayKey::String(a), ArrayKey::String(b)) => a.cmp(b),
            // Int < String
            (ArrayKey::Int(_), ArrayKey::String(_)) => std::cmp::Ordering::Less,
            (ArrayKey::String(_), ArrayKey::Int(_)) => std::cmp::Ordering::Greater,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct KeyedProperty {
    pub ty: Union,
    pub optional: bool,
}

// ---------------------------------------------------------------------------
// Atomic — every distinct PHP type variant
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Atomic {
    // --- Scalars ---
    /// `string`
    TString,
    /// `"hello"` — a specific string literal
    TLiteralString(Arc<str>),
    /// `class-string` or `class-string<T>`
    TClassString(Option<Arc<str>>),
    /// `non-empty-string`
    TNonEmptyString,
    /// `numeric-string`
    TNumericString,

    /// `int`
    TInt,
    /// `42` — a specific integer literal
    TLiteralInt(i64),
    /// `int<min, max>` — bounded integer range
    TIntRange { min: Option<i64>, max: Option<i64> },
    /// `positive-int`
    TPositiveInt,
    /// `negative-int`
    TNegativeInt,
    /// `non-negative-int`
    TNonNegativeInt,

    /// `float`
    TFloat,
    /// `3.14` — a specific float literal
    TLiteralFloat(i64, i64), // stored as (int_bits, frac_bits) to be PartialEq+Hash-friendly
    // We use ordered_float or just store as ordered pair for equality purposes.
    /// `bool`
    TBool,
    /// `true`
    TTrue,
    /// `false`
    TFalse,

    /// `null`
    TNull,

    // --- Bottom / top ---
    /// `void` — return-only; can't be used as a value
    TVoid,
    /// `never` — function that never returns (throws or infinite loop)
    TNever,
    /// `mixed` — top type; accepts anything
    TMixed,
    /// `scalar` — int | float | string | bool
    TScalar,
    /// `numeric` — int | float | numeric-string
    TNumeric,

    // --- Objects ---
    /// `object` — any object
    TObject,
    /// `ClassName` / `ClassName<T1, T2>` — specific named class/interface
    TNamedObject {
        fqcn: Arc<str>,
        /// Resolved generic type arguments (e.g. `Collection<int>`)
        type_params: Vec<Union>,
    },
    /// `static` — late static binding type; resolved to calling class at call site
    TStaticObject { fqcn: Arc<str> },
    /// `self` — the class in whose body the type appears
    TSelf { fqcn: Arc<str> },
    /// `parent` — the parent class
    TParent { fqcn: Arc<str> },

    // --- Callables ---
    /// `callable` or `callable(T): R`
    TCallable {
        params: Option<Vec<FnParam>>,
        return_type: Option<Box<Union>>,
    },
    /// `Closure` or `Closure(T): R` — more specific than TCallable
    TClosure {
        params: Vec<FnParam>,
        return_type: Box<Union>,
        this_type: Option<Box<Union>>,
    },

    // --- Arrays ---
    /// `array` or `array<K, V>`
    TArray { key: Box<Union>, value: Box<Union> },
    /// `list<T>` — integer-keyed sequential array (keys 0, 1, 2, …)
    TList { value: Box<Union> },
    /// `non-empty-array<K, V>`
    TNonEmptyArray { key: Box<Union>, value: Box<Union> },
    /// `non-empty-list<T>`
    TNonEmptyList { value: Box<Union> },
    /// `array{key: T, ...}` — shape / keyed array
    TKeyedArray {
        properties: IndexMap<ArrayKey, KeyedProperty>,
        /// If true, additional keys beyond the declared ones may exist
        is_open: bool,
        /// If true, the shape represents a list (integer keys only)
        is_list: bool,
    },

    // --- Generics / meta-types ---
    /// `T` — a template type parameter
    TTemplateParam {
        name: Arc<str>,
        as_type: Box<Union>,
        /// The entity (class or function FQN) that declared this template
        defining_entity: Arc<str>,
    },
    /// `(T is string ? A : B)` — conditional type
    TConditional {
        subject: Box<Union>,
        if_true: Box<Union>,
        if_false: Box<Union>,
    },

    // --- Special object strings ---
    /// `interface-string`
    TInterfaceString,
    /// `enum-string`
    TEnumString,
    /// `trait-string`
    TTraitString,

    // --- Enum cases ---
    /// `EnumName::CaseName` — a specific enum case literal
    TLiteralEnumCase {
        enum_fqcn: Arc<str>,
        case_name: Arc<str>,
    },

    // --- Intersection ---
    /// `A&B&C` — PHP 8.1+ pure intersection type
    TIntersection { parts: Vec<Union> },
}

impl Atomic {
    /// Whether this atomic type can ever evaluate to a falsy value.
    pub fn can_be_falsy(&self) -> bool {
        match self {
            Atomic::TNull
            | Atomic::TFalse
            | Atomic::TBool
            | Atomic::TNever
            | Atomic::TLiteralInt(0)
            | Atomic::TLiteralFloat(0, 0)
            | Atomic::TInt
            | Atomic::TFloat
            | Atomic::TNumeric
            | Atomic::TScalar
            | Atomic::TMixed
            | Atomic::TString
            | Atomic::TNonEmptyString
            | Atomic::TArray { .. }
            | Atomic::TList { .. }
            | Atomic::TNonEmptyArray { .. }
            | Atomic::TNonEmptyList { .. } => true,

            Atomic::TLiteralString(s) => s.as_ref().is_empty() || s.as_ref() == "0",

            Atomic::TKeyedArray { properties, .. } => properties.is_empty(),

            _ => false,
        }
    }

    /// Whether this atomic type can ever evaluate to a truthy value.
    pub fn can_be_truthy(&self) -> bool {
        match self {
            Atomic::TNever
            | Atomic::TVoid
            | Atomic::TNull
            | Atomic::TFalse
            | Atomic::TLiteralInt(0)
            | Atomic::TLiteralFloat(0, 0) => false,
            Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => false,
            _ => true,
        }
    }

    /// Whether this atomic represents a numeric type (int, float, or numeric-string).
    pub fn is_numeric(&self) -> bool {
        matches!(
            self,
            Atomic::TInt
                | Atomic::TLiteralInt(_)
                | Atomic::TIntRange { .. }
                | Atomic::TPositiveInt
                | Atomic::TNegativeInt
                | Atomic::TNonNegativeInt
                | Atomic::TFloat
                | Atomic::TLiteralFloat(..)
                | Atomic::TNumeric
                | Atomic::TNumericString
        )
    }

    /// Whether this atomic is an integer variant.
    pub fn is_int(&self) -> bool {
        matches!(
            self,
            Atomic::TInt
                | Atomic::TLiteralInt(_)
                | Atomic::TIntRange { .. }
                | Atomic::TPositiveInt
                | Atomic::TNegativeInt
                | Atomic::TNonNegativeInt
        )
    }

    /// Whether this atomic is a string variant.
    pub fn is_string(&self) -> bool {
        matches!(
            self,
            Atomic::TString
                | Atomic::TLiteralString(_)
                | Atomic::TClassString(_)
                | Atomic::TNonEmptyString
                | Atomic::TNumericString
                | Atomic::TInterfaceString
                | Atomic::TEnumString
                | Atomic::TTraitString
        )
    }

    /// Whether this atomic is an array variant.
    pub fn is_array(&self) -> bool {
        matches!(
            self,
            Atomic::TArray { .. }
                | Atomic::TList { .. }
                | Atomic::TNonEmptyArray { .. }
                | Atomic::TNonEmptyList { .. }
                | Atomic::TKeyedArray { .. }
        )
    }

    /// Whether this atomic is an object variant.
    pub fn is_object(&self) -> bool {
        matches!(
            self,
            Atomic::TObject
                | Atomic::TNamedObject { .. }
                | Atomic::TStaticObject { .. }
                | Atomic::TSelf { .. }
                | Atomic::TParent { .. }
                | Atomic::TIntersection { .. }
        )
    }

    /// Whether this atomic is a callable variant.
    pub fn is_callable(&self) -> bool {
        matches!(self, Atomic::TCallable { .. } | Atomic::TClosure { .. })
    }

    /// Returns the FQCN if this is a named object type.
    pub fn named_object_fqcn(&self) -> Option<&str> {
        match self {
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TSelf { fqcn }
            | Atomic::TParent { fqcn } => Some(fqcn.as_ref()),
            _ => None,
        }
    }

    /// A human-readable name for this type (used in error messages).
    pub fn type_name(&self) -> &'static str {
        match self {
            Atomic::TString
            | Atomic::TLiteralString(_)
            | Atomic::TNonEmptyString
            | Atomic::TNumericString => "string",
            Atomic::TClassString(_) => "class-string",
            Atomic::TInt | Atomic::TLiteralInt(_) | Atomic::TIntRange { .. } => "int",
            Atomic::TPositiveInt => "positive-int",
            Atomic::TNegativeInt => "negative-int",
            Atomic::TNonNegativeInt => "non-negative-int",
            Atomic::TFloat | Atomic::TLiteralFloat(..) => "float",
            Atomic::TBool => "bool",
            Atomic::TTrue => "true",
            Atomic::TFalse => "false",
            Atomic::TNull => "null",
            Atomic::TVoid => "void",
            Atomic::TNever => "never",
            Atomic::TMixed => "mixed",
            Atomic::TScalar => "scalar",
            Atomic::TNumeric => "numeric",
            Atomic::TObject => "object",
            Atomic::TNamedObject { .. } => "object",
            Atomic::TStaticObject { .. } => "static",
            Atomic::TSelf { .. } => "self",
            Atomic::TParent { .. } => "parent",
            Atomic::TCallable { .. } => "callable",
            Atomic::TClosure { .. } => "Closure",
            Atomic::TArray { .. } => "array",
            Atomic::TList { .. } => "list",
            Atomic::TNonEmptyArray { .. } => "non-empty-array",
            Atomic::TNonEmptyList { .. } => "non-empty-list",
            Atomic::TKeyedArray { .. } => "array",
            Atomic::TTemplateParam { .. } => "template-param",
            Atomic::TConditional { .. } => "conditional-type",
            Atomic::TInterfaceString => "interface-string",
            Atomic::TEnumString => "enum-string",
            Atomic::TTraitString => "trait-string",
            Atomic::TLiteralEnumCase { .. } => "enum-case",
            Atomic::TIntersection { .. } => "intersection",
        }
    }
}

// ---------------------------------------------------------------------------
// Hash impls
// ---------------------------------------------------------------------------

impl Hash for FnParam {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.ty.hash(state);
        self.default.hash(state);
        self.is_variadic.hash(state);
        self.is_byref.hash(state);
        self.is_optional.hash(state);
    }
}

/// Discriminant tags for `Atomic` used in the manual `Hash` impl below.
#[allow(non_camel_case_types, clippy::enum_variant_names)]
#[repr(u8)]
enum AtomicTag {
    TString = 0,
    TLiteralString,
    TClassString,
    TNonEmptyString,
    TNumericString,
    TInt,
    TLiteralInt,
    TIntRange,
    TPositiveInt,
    TNegativeInt,
    TNonNegativeInt,
    TFloat,
    TLiteralFloat,
    TBool,
    TTrue,
    TFalse,
    TNull,
    TVoid,
    TNever,
    TMixed,
    TScalar,
    TNumeric,
    TObject,
    TNamedObject,
    TStaticObject,
    TSelf,
    TParent,
    TCallable,
    TClosure,
    TArray,
    TList,
    TNonEmptyArray,
    TNonEmptyList,
    TKeyedArray,
    TTemplateParam,
    TConditional,
    TInterfaceString,
    TEnumString,
    TTraitString,
    TLiteralEnumCase,
    TIntersection,
}

impl Hash for Atomic {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        use AtomicTag as T;
        match self {
            // --- tag-only variants ---
            Atomic::TString => (T::TString as u8).hash(state),
            Atomic::TNonEmptyString => (T::TNonEmptyString as u8).hash(state),
            Atomic::TNumericString => (T::TNumericString as u8).hash(state),
            Atomic::TInt => (T::TInt as u8).hash(state),
            Atomic::TPositiveInt => (T::TPositiveInt as u8).hash(state),
            Atomic::TNegativeInt => (T::TNegativeInt as u8).hash(state),
            Atomic::TNonNegativeInt => (T::TNonNegativeInt as u8).hash(state),
            Atomic::TFloat => (T::TFloat as u8).hash(state),
            Atomic::TBool => (T::TBool as u8).hash(state),
            Atomic::TTrue => (T::TTrue as u8).hash(state),
            Atomic::TFalse => (T::TFalse as u8).hash(state),
            Atomic::TNull => (T::TNull as u8).hash(state),
            Atomic::TVoid => (T::TVoid as u8).hash(state),
            Atomic::TNever => (T::TNever as u8).hash(state),
            Atomic::TMixed => (T::TMixed as u8).hash(state),
            Atomic::TScalar => (T::TScalar as u8).hash(state),
            Atomic::TNumeric => (T::TNumeric as u8).hash(state),
            Atomic::TObject => (T::TObject as u8).hash(state),
            Atomic::TInterfaceString => (T::TInterfaceString as u8).hash(state),
            Atomic::TEnumString => (T::TEnumString as u8).hash(state),
            Atomic::TTraitString => (T::TTraitString as u8).hash(state),

            // --- variants with fields ---
            Atomic::TLiteralString(s) => {
                (T::TLiteralString as u8).hash(state);
                s.hash(state);
            }
            Atomic::TClassString(opt) => {
                (T::TClassString as u8).hash(state);
                opt.hash(state);
            }
            Atomic::TLiteralInt(n) => {
                (T::TLiteralInt as u8).hash(state);
                n.hash(state);
            }
            Atomic::TIntRange { min, max } => {
                (T::TIntRange as u8).hash(state);
                min.hash(state);
                max.hash(state);
            }
            Atomic::TLiteralFloat(int_bits, frac_bits) => {
                (T::TLiteralFloat as u8).hash(state);
                int_bits.hash(state);
                frac_bits.hash(state);
            }
            Atomic::TNamedObject { fqcn, type_params } => {
                (T::TNamedObject as u8).hash(state);
                fqcn.hash(state);
                type_params.hash(state);
            }
            Atomic::TStaticObject { fqcn } => {
                (T::TStaticObject as u8).hash(state);
                fqcn.hash(state);
            }
            Atomic::TSelf { fqcn } => {
                (T::TSelf as u8).hash(state);
                fqcn.hash(state);
            }
            Atomic::TParent { fqcn } => {
                (T::TParent as u8).hash(state);
                fqcn.hash(state);
            }
            Atomic::TCallable {
                params,
                return_type,
            } => {
                (T::TCallable as u8).hash(state);
                params.hash(state);
                return_type.hash(state);
            }
            Atomic::TClosure {
                params,
                return_type,
                this_type,
            } => {
                (T::TClosure as u8).hash(state);
                params.hash(state);
                return_type.hash(state);
                this_type.hash(state);
            }
            Atomic::TArray { key, value } => {
                (T::TArray as u8).hash(state);
                key.hash(state);
                value.hash(state);
            }
            Atomic::TList { value } => {
                (T::TList as u8).hash(state);
                value.hash(state);
            }
            Atomic::TNonEmptyArray { key, value } => {
                (T::TNonEmptyArray as u8).hash(state);
                key.hash(state);
                value.hash(state);
            }
            Atomic::TNonEmptyList { value } => {
                (T::TNonEmptyList as u8).hash(state);
                value.hash(state);
            }
            Atomic::TKeyedArray {
                properties,
                is_open,
                is_list,
            } => {
                (T::TKeyedArray as u8).hash(state);
                // Sort by key before hashing so the hash is order-independent,
                // consistent with PartialEq which uses IndexMap value equality.
                let mut pairs: Vec<_> = properties.iter().collect();
                pairs.sort_by_key(|(a, _)| *a);
                for (k, v) in pairs {
                    k.hash(state);
                    v.hash(state);
                }
                is_open.hash(state);
                is_list.hash(state);
            }
            Atomic::TTemplateParam {
                name,
                as_type,
                defining_entity,
            } => {
                (T::TTemplateParam as u8).hash(state);
                name.hash(state);
                as_type.hash(state);
                defining_entity.hash(state);
            }
            Atomic::TConditional {
                subject,
                if_true,
                if_false,
            } => {
                (T::TConditional as u8).hash(state);
                subject.hash(state);
                if_true.hash(state);
                if_false.hash(state);
            }
            Atomic::TLiteralEnumCase {
                enum_fqcn,
                case_name,
            } => {
                (T::TLiteralEnumCase as u8).hash(state);
                enum_fqcn.hash(state);
                case_name.hash(state);
            }
            Atomic::TIntersection { parts } => {
                (T::TIntersection as u8).hash(state);
                parts.hash(state);
            }
        }
    }
}