mir-analyzer 0.88.0

Analysis engine 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
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! Shared kernel for the narrowing submodules: expression-shape extractors,
//! property-refinement helpers, and small cross-cutting utilities used by
//! multiple narrowing arms.
use php_ast::ast::{AssignOp, BinaryOp, UnaryPrefixOp};
use php_ast::owned::ExprKind;

use mir_types::{Atomic, Name, Type};

use crate::db::MirDatabase;
use crate::flow_state::{FlagValue, FlowState, Guard, GuardKind};

use super::arrays::{
    collect_array_access_path, extract_count_arg, extract_count_static_prop_arg,
    narrow_array_count_comparison, narrow_prop_array_count_comparison,
    narrow_static_prop_array_count_comparison, ShapeBase,
};
use super::literals::{extract_int_literal, narrow_var_null};
use super::strings::{
    extract_strlen_arg, extract_strlen_static_prop_arg, narrow_prop_string_strlen_comparison,
    narrow_static_prop_string_strlen_comparison, narrow_string_strlen_comparison,
};

/// Apply a pre-computed narrowed type to a variable.
///
/// If `mark_diverges` is true and the narrowed type is empty (the current type
/// can never satisfy the constraint), the branch is marked unreachable.
pub(super) fn set_narrowed(
    ctx: &mut FlowState,
    name: &str,
    current: &Type,
    narrowed: Type,
    mark_diverges: bool,
) {
    if !narrowed.is_empty() {
        ctx.narrow_var(name, narrowed);
    } else if mark_diverges && !current.is_empty() && !current.is_mixed() {
        ctx.diverges = true;
    }
}

/// Resolve the current type of `$obj_var->prop`: an existing flow-state
/// refinement if one is already tracked, else the declared type looked up
/// through the object variable's own type (including `self`/`static`, and
/// falling back to `self_fqcn` for `$this`).
pub(crate) fn resolve_prop_current_type(
    ctx: &FlowState,
    obj_var: &str,
    prop: &str,
    db: &dyn MirDatabase,
    file: &str,
) -> Type {
    if let Some(refined) = ctx.get_prop_refined(obj_var, prop) {
        return refined.clone();
    }
    if prop.ends_with("()") {
        return resolve_method_call_current_type(ctx, obj_var, prop, db);
    }
    let obj_ty = match split_prop_hop(obj_var) {
        Some((base, mid)) => resolve_prop_current_type(ctx, base, mid, db, file),
        None => receiver_type(ctx, obj_var, db),
    };
    let mut prop_ty = mir_types::Type::mixed();
    'outer: for atomic in &obj_ty.types {
        if let mir_types::Atomic::TNamedObject { fqcn, .. } = atomic {
            let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
            // Try to find the property in the class chain
            if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                if let Some(ty) = p_def.ty.as_deref() {
                    prop_ty = ty.clone();
                    break 'outer;
                }
            }
        } else if let mir_types::Atomic::TSelf { fqcn }
        | mir_types::Atomic::TStaticObject { fqcn }
        | mir_types::Atomic::TParent { fqcn } = atomic
        {
            let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
            if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                if let Some(ty) = p_def.ty.as_deref() {
                    prop_ty = ty.clone();
                    break 'outer;
                }
            }
        }
    }
    // Also try self_fqcn if obj_var is "this"
    if prop_ty.is_mixed() && obj_var == "this" {
        if let Some(fqcn) = ctx.self_fqcn.as_ref() {
            let resolved = crate::db::resolve_name(db, file, fqcn.as_ref());
            let here = crate::db::Fqcn::from_str(db, &resolved);
            if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                if let Some(ty) = p_def.ty.as_deref() {
                    prop_ty = ty.clone();
                }
            }
        }
    }
    prop_ty
}

/// Narrow a static property access `self::$prop`/`Class::$prop` by a null
/// check. `prop_refined` is keyed by FQCN here instead of a receiver
/// variable name — a FQCN string can never collide with a real PHP variable.
/// Resolve the current type of `self::$prop`/`static::$prop`/`Class::$prop`:
/// an existing flow-state refinement if one is already tracked, else the
/// declared type looked up through the class hierarchy. Static-property
/// counterpart of `resolve_prop_current_type`.
pub(crate) fn resolve_static_prop_current_type(
    ctx: &FlowState,
    fqcn: &str,
    prop: &str,
    db: &dyn MirDatabase,
) -> Type {
    if let Some(refined) = ctx.get_prop_refined(fqcn, prop) {
        return refined.clone();
    }
    let here = crate::db::Fqcn::from_str(db, fqcn);
    crate::db::find_property_in_chain(db, here, prop)
        .and_then(|(_, p)| p.ty.as_deref().cloned())
        .unwrap_or_else(mir_types::Type::mixed)
}

/// Applies a narrowed property type computed from `current`, mirroring
/// `set_narrowed`'s variable-side semantics for the property-refinement store.
pub(crate) fn apply_prop_narrowed(
    ctx: &mut FlowState,
    obj_var: &str,
    prop: &str,
    current: Type,
    narrowed: Type,
    mark_diverges: bool,
) {
    if !narrowed.is_empty() {
        if narrowed != current {
            ctx.set_prop_refined(obj_var, prop, narrowed);
        }
    } else if mark_diverges && !current.is_empty() && !current.is_mixed() {
        ctx.diverges = true;
    }
}

/// After proving `$obj->prop` equals a definite non-null literal value
/// (`proved_match`), the receiver itself must also be non-null: PHP 8 reads
/// `$obj->prop` on a null `$obj` as a warning, still evaluating to `null`
/// (same ambiguity as `narrow_nullsafe_prop_null`).
pub(crate) fn narrow_receiver_non_null_on_prop_match(
    ctx: &mut FlowState,
    obj_var: &str,
    proved_match: bool,
) {
    if proved_match {
        narrow_var_null(ctx, obj_var, false);
    }
}

/// `(base, prop)` of a one-property-hop receiver key (`this->cfg`); `None` for
/// a variable or a call-chain key.
fn split_prop_hop(key: &str) -> Option<(&str, &str)> {
    key.rsplit_once("->")
        .filter(|(_, prop)| !prop.ends_with("()"))
}

/// Type of a property-narrowing receiver key: a variable or a one-hop
/// property path.
pub(crate) fn prop_receiver_type(
    ctx: &FlowState,
    key: &str,
    db: &dyn MirDatabase,
    file: &str,
) -> Type {
    match split_prop_hop(key) {
        Some((base, prop)) => resolve_prop_current_type(ctx, base, prop, db, file),
        None => ctx.get_var(key),
    }
}

/// Removes `null` from a receiver key: the variable, or the intermediate
/// property of a one-hop path.
pub(crate) fn narrow_receiver_non_null(
    ctx: &mut FlowState,
    key: &str,
    db: &dyn MirDatabase,
    file: &str,
) {
    let Some((base, prop)) = split_prop_hop(key) else {
        narrow_var_null(ctx, key, false);
        return;
    };
    let current = resolve_prop_current_type(ctx, base, prop, db, file);
    if !current.is_mixed() {
        let narrowed = current.remove_null();
        apply_prop_narrowed(ctx, base, prop, current, narrowed, false);
    }
}

/// Extract a fully-qualified class name from the first argument of
/// `class_exists()` / `interface_exists()` / `trait_exists()`.
///
/// Recognised forms:
/// - `\Foo\Bar::class` or `Foo\Bar::class` — resolved via `crate::db::resolve_name`
/// - `'Foo\Bar'` or `'Foo\\Bar'` — string literals
pub(crate) fn extract_class_fqcn_from_expr(
    expr: &php_ast::owned::Expr,
    self_fqcn: Option<&str>,
    static_fqcn: Option<&str>,
    parent_fqcn: Option<&str>,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<std::sync::Arc<str>> {
    let expr = peel_parens(expr);
    match &expr.kind {
        // \Foo\Bar::class  or  Foo\Bar::class  (also self::class/static::class/parent::class)
        ExprKind::ClassConstAccess(cca) => {
            if let ExprKind::Identifier(id) = &cca.class.kind {
                let member = match &cca.member.kind {
                    ExprKind::Identifier(s) => s.as_ref(),
                    _ => return None,
                };
                if member.eq_ignore_ascii_case("class") {
                    match id.to_ascii_lowercase().as_str() {
                        "self" | "static" => {
                            let fqcn = if id.eq_ignore_ascii_case("static") {
                                static_fqcn.or(self_fqcn)
                            } else {
                                self_fqcn
                            };
                            return fqcn.map(std::sync::Arc::from);
                        }
                        "parent" => return parent_fqcn.map(std::sync::Arc::from),
                        _ => {
                            let resolved = crate::db::resolve_name(db, file, id.as_ref());
                            return Some(std::sync::Arc::from(resolved.as_str()));
                        }
                    }
                }
            }
            None
        }
        // 'Foo\Bar'  or  'Foo\\Bar'  or  'Foo'
        ExprKind::String(s) => {
            let name = s.as_ref().trim_start_matches('\\');
            if !name.is_empty() {
                Some(std::sync::Arc::from(name))
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Extract `(obj_var, prop_name)` from a simple `$var->prop` expression.
pub(crate) fn extract_prop_access(expr: &php_ast::owned::Expr) -> Option<(String, String)> {
    match &expr.kind {
        ExprKind::PropertyAccess(pa) => {
            let obj = extract_var_name(&pa.object).or_else(|| method_chain_key(&pa.object))?;
            let prop = match &pa.property.kind {
                ExprKind::Identifier(s) => s.as_ref().to_string(),
                _ => return None,
            };
            Some((obj, prop))
        }
        ExprKind::MethodCall(call) if call.args.is_empty() => {
            let obj = extract_var_name(&call.object).or_else(|| method_chain_key(&call.object))?;
            let ExprKind::Identifier(name) = &call.method.kind else {
                return None;
            };
            Some((obj, method_call_key(name)))
        }
        ExprKind::Parenthesized(inner) => extract_prop_access(inner),
        _ => None,
    }
}

/// `prop_refined` key for a zero-arg method call; `()` keeps it disjoint from property names.
pub(crate) fn method_call_key(method: &str) -> String {
    format!("{}()", method.to_ascii_lowercase())
}

/// Key for a chain of zero-arg method calls on a variable (`$a->b()->c()` →
/// `a->b()->c()`). Whether repeated calls are interchangeable is
/// [`receiver_key_is_stable`]'s call, made where a refinement is read.
pub(crate) fn method_chain_key(expr: &php_ast::owned::Expr) -> Option<String> {
    match &expr.kind {
        ExprKind::MethodCall(call) if call.args.is_empty() => {
            let ExprKind::Identifier(name) = &call.method.kind else {
                return None;
            };
            let base = extract_var_name(&call.object).or_else(|| method_chain_key(&call.object))?;
            Some(format!("{base}->{}", method_call_key(name)))
        }
        ExprKind::Parenthesized(inner) => method_chain_key(inner),
        _ => None,
    }
}

/// `prop_refined` receiver key of a method call's object: the variable, or a
/// call chain.
pub(crate) fn memoized_receiver_key(expr: &php_ast::owned::Expr) -> Option<String> {
    match &expr.kind {
        ExprKind::Variable(name) => Some(name.trim_start_matches('$').to_string()),
        _ => method_chain_key(expr),
    }
}

/// Whether every call in `key`'s chain is pure, mutation-free or memoized, so
/// a refinement recorded under `key` still describes a repeated evaluation.
pub(crate) fn receiver_key_is_stable(ctx: &FlowState, key: &str, db: &dyn MirDatabase) -> bool {
    match key.rsplit_once("->") {
        Some((base, call)) if call.ends_with("()") => {
            stable_method_return(ctx, base, call, db).is_some()
                && receiver_key_is_stable(ctx, base, db)
        }
        _ => true,
    }
}

/// Type of a narrowing receiver key: a variable, or a memoized call chain
/// resolved through the declared return types.
fn receiver_type(ctx: &FlowState, key: &str, db: &dyn MirDatabase) -> Type {
    match key.rsplit_once("->") {
        Some((base, call)) if call.ends_with("()") => ctx
            .get_prop_refined(base, call)
            .cloned()
            .unwrap_or_else(|| resolve_method_call_current_type(ctx, base, call, db)),
        _ => ctx.get_var(key),
    }
}

/// Declared return type of `$obj_var->method()` with a single concrete receiver class, or `mixed`
/// when repeated calls aren't provably equal (mutation-free, or memoized) or the type isn't
/// receiver-independent.
fn resolve_method_call_current_type(
    ctx: &FlowState,
    obj_var: &str,
    key: &str,
    db: &dyn MirDatabase,
) -> Type {
    stable_method_return(ctx, obj_var, key, db).unwrap_or_else(Type::mixed)
}

/// Declared return type of `$obj_var->method()` when repeated calls are provably equal
/// (`None` otherwise); see [`resolve_method_call_current_type`].
fn stable_method_return(
    ctx: &FlowState,
    obj_var: &str,
    key: &str,
    db: &dyn MirDatabase,
) -> Option<Type> {
    let method = key.trim_end_matches("()");
    let obj_ty = receiver_type(ctx, obj_var, db);
    let [Atomic::TNamedObject { fqcn, .. }] = obj_ty.types.as_slice() else {
        return None;
    };
    let resolved = crate::call::method::resolve_method_from_db(
        db,
        &std::sync::Arc::from(fqcn.as_ref()),
        method,
    )?;
    let receiver_independent = resolved.template_params.is_empty()
        && resolved.return_ty_raw.types.iter().all(|a| match a {
            Atomic::TNamedObject { type_params, .. } => type_params.is_empty(),
            Atomic::TSelf { .. }
            | Atomic::TStaticObject { .. }
            | Atomic::TParent { .. }
            | Atomic::TTemplateParam { .. }
            | Atomic::TConditional { .. } => false,
            _ => true,
        });
    if resolved.is_static
        || !(resolved.is_pure || resolved.is_mutation_free || db.memoize_method_call_results())
        || !receiver_independent
    {
        return None;
    }
    Some(resolved.return_ty_raw)
}

/// Like `extract_prop_access`, but only matches the nullsafe (`?->`) form.
/// Kept as a separate matcher purely to distinguish the two operators in the
/// AST — both are narrowed by the same logic (`narrow_nullsafe_prop_null`),
/// since a plain `->` on a null receiver also evaluates to `null` in PHP 8
/// (a warning, not a fatal error), same as `?->`'s short-circuit.
pub(super) fn extract_nullsafe_prop_access(
    expr: &php_ast::owned::Expr,
) -> Option<(String, String)> {
    match &expr.kind {
        ExprKind::NullsafePropertyAccess(pa) => {
            let obj = extract_var_name(&pa.object).or_else(|| method_chain_key(&pa.object))?;
            let prop = match &pa.property.kind {
                ExprKind::Identifier(s) => s.as_ref().to_string(),
                _ => return None,
            };
            Some((obj, prop))
        }
        ExprKind::Parenthesized(inner) => extract_nullsafe_prop_access(inner),
        _ => None,
    }
}

/// `extract_prop_access`, but also accepts the nullsafe (`?->`) form —
/// for arms that don't need to distinguish the two operators (a plain
/// `->` on a null receiver also evaluates to null in PHP 8, same as
/// `?->`'s short-circuit, so most literal-comparison narrowing arms
/// should treat both identically).
pub(crate) fn extract_any_prop_access(expr: &php_ast::owned::Expr) -> Option<(String, String)> {
    extract_nullsafe_prop_access(expr).or_else(|| extract_prop_access(expr))
}

/// Compute `prop_refined`'s "object" key component for a property-access
/// receiver expression, accepting one MORE hop than a bare variable —
/// `$this->a` (as a receiver) encodes as `"this->a"` instead of returning
/// `None`. `prop_refined` is a flat `(Name, Name)` map keyed by
/// receiver+property, not a real path; a full path-based refactor is a much
/// bigger change, but a synthetic multi-hop string key (mirroring
/// `extract_expr_guard_key`'s own synthetic-key precedent) lets a 2-hop
/// chain reuse the exact same map without one. Still bottoms out at a bare
/// variable base — a 3+-hop chain or a method-call/array-index hop in the
/// middle is NOT covered.
pub(crate) fn chained_prop_receiver_key(object_expr: &php_ast::owned::Expr) -> Option<String> {
    match &object_expr.kind {
        ExprKind::Variable(name) => Some(name.trim_start_matches('$').to_string()),
        ExprKind::MethodCall(_) => method_chain_key(object_expr),
        ExprKind::PropertyAccess(inner_pa) | ExprKind::NullsafePropertyAccess(inner_pa) => {
            let base = extract_var_name(&inner_pa.object)?;
            let mid_prop = match &inner_pa.property.kind {
                ExprKind::Identifier(s) => s.as_ref(),
                _ => return None,
            };
            Some(format!("{base}->{mid_prop}"))
        }
        _ => None,
    }
}

/// `extract_any_prop_access`, plus the one-more-hop `$this->a->b` form.
pub(crate) fn extract_prop_path_access(expr: &php_ast::owned::Expr) -> Option<(String, String)> {
    extract_any_prop_access(expr).or_else(|| extract_chained_prop_access(expr))
}

/// Like `extract_any_prop_access`, but also accepts one more receiver hop
/// via `chained_prop_receiver_key` (`$this->a->b` encodes as
/// `("this->a", "b")` instead of returning `None`).
pub(crate) fn extract_chained_prop_access(expr: &php_ast::owned::Expr) -> Option<(String, String)> {
    let pa = match &expr.kind {
        ExprKind::PropertyAccess(pa) | ExprKind::NullsafePropertyAccess(pa) => pa,
        ExprKind::Parenthesized(inner) => return extract_chained_prop_access(inner),
        _ => return None,
    };
    let prop = match &pa.property.kind {
        ExprKind::Identifier(s) => s.as_ref().to_string(),
        _ => return None,
    };
    let obj_key = chained_prop_receiver_key(&pa.object)?;
    Some((obj_key, prop))
}

/// Extract `(fqcn, prop_name)` from a `self::$prop` / `static::$prop` /
/// `parent::$prop` / `ClassName::$prop` expression, resolving relative
/// keywords through the current `FlowState`.
pub(crate) fn extract_static_prop_access(
    expr: &php_ast::owned::Expr,
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<(std::sync::Arc<str>, String)> {
    extract_static_prop_access_parts(
        expr,
        db,
        file,
        ctx.self_fqcn.as_deref(),
        ctx.static_fqcn.as_deref(),
        ctx.parent_fqcn.as_deref(),
    )
}

/// Same resolution logic as `extract_static_prop_access`, parameterized on
/// the three relative-keyword FQCNs directly instead of a full `FlowState`
/// borrow — used by the OR-disjunct collector helpers (`collect_static_prop_instanceof`,
/// `extract_type_fn_check_static_prop`), which precompute these once before
/// looping so they don't need to hold a `FlowState` reference alongside a
/// later `&mut FlowState` use in the same function.
pub(super) fn extract_static_prop_access_parts(
    expr: &php_ast::owned::Expr,
    db: &dyn MirDatabase,
    file: &str,
    self_fqcn: Option<&str>,
    static_fqcn: Option<&str>,
    parent_fqcn: Option<&str>,
) -> Option<(std::sync::Arc<str>, String)> {
    match &expr.kind {
        ExprKind::StaticPropertyAccess(spa) => {
            let id = match &spa.class.kind {
                ExprKind::Identifier(id) => id,
                _ => return None,
            };
            let resolved = crate::db::resolve_name(db, file, id.as_ref());
            let fqcn = match resolved.as_str() {
                "self" | "static" => std::sync::Arc::from(self_fqcn.or(static_fqcn)?),
                "parent" => std::sync::Arc::from(parent_fqcn?),
                s => std::sync::Arc::from(s),
            };
            let prop = match &spa.member.kind {
                ExprKind::Variable(name) | ExprKind::Identifier(name) => {
                    name.trim_start_matches('$').to_string()
                }
                _ => return None,
            };
            Some((fqcn, prop))
        }
        ExprKind::Parenthesized(inner) => {
            extract_static_prop_access_parts(inner, db, file, self_fqcn, static_fqcn, parent_fqcn)
        }
        _ => None,
    }
}

/// The array access beneath one or more `->`/`?->` hops: `$a['k']->p->q` →
/// `$a['k']`. `None` when the expression has no property hop or no array
/// access under it.
pub(super) fn array_access_under_prop_hops(
    expr: &php_ast::owned::Expr,
) -> Option<&php_ast::owned::Expr> {
    let mut cur = expr;
    let mut hopped = false;
    loop {
        match &cur.kind {
            ExprKind::PropertyAccess(pa) | ExprKind::NullsafePropertyAccess(pa) => {
                hopped = true;
                cur = &pa.object;
            }
            ExprKind::Parenthesized(inner) => cur = inner,
            ExprKind::ArrayAccess(_) if hopped => return Some(cur),
            _ => return None,
        }
    }
}

/// The guard that holds when `expr` evaluates to `is_true`, for conditions on a plain variable.
pub(crate) fn established_guard(expr: &php_ast::owned::Expr, is_true: bool) -> Option<Guard> {
    let plain_var = |e: &php_ast::owned::Expr| match &strip_parens(e).kind {
        ExprKind::Variable(v) => Some(Name::from(v.trim_start_matches('$'))),
        _ => None,
    };
    let (var, kind) = match &expr.kind {
        ExprKind::Parenthesized(inner) => return established_guard(inner, is_true),
        ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::BooleanNot => {
            return established_guard(&u.operand, !is_true)
        }
        ExprKind::Variable(_) if is_true => (plain_var(expr)?, GuardKind::Truthy),
        ExprKind::Empty(inner) if !is_true => (plain_var(inner)?, GuardKind::Truthy),
        ExprKind::Isset(vars) if is_true && vars.len() == 1 => {
            (plain_var(&vars[0])?, GuardKind::NotNull)
        }
        ExprKind::Binary(b) if matches!(b.op, BinaryOp::Identical | BinaryOp::NotIdentical) => {
            let holds = (b.op == BinaryOp::NotIdentical) != is_true;
            let (var_side, lit_side) =
                match (&strip_parens(&b.left).kind, &strip_parens(&b.right).kind) {
                    (ExprKind::Variable(_), _) => (&b.left, &b.right),
                    (_, ExprKind::Variable(_)) => (&b.right, &b.left),
                    _ => return None,
                };
            let kind = match &strip_parens(lit_side).kind {
                ExprKind::Null if !holds => GuardKind::NotNull,
                ExprKind::String(s) if holds => {
                    GuardKind::Identical(FlagValue::Str(Name::from(&**s)))
                }
                ExprKind::Int(n) if holds => GuardKind::Identical(FlagValue::Int(*n)),
                ExprKind::Bool(true) if holds => GuardKind::Identical(FlagValue::True),
                _ => return None,
            };
            (plain_var(var_side)?, kind)
        }
        _ => return None,
    };
    Some(Guard {
        var,
        kind,
        from_flag: false,
    })
}

fn strip_parens(mut e: &php_ast::owned::Expr) -> &php_ast::owned::Expr {
    while let ExprKind::Parenthesized(inner) = &e.kind {
        e = inner;
    }
    e
}

pub(super) fn extract_var_name(expr: &php_ast::owned::Expr) -> Option<String> {
    match &expr.kind {
        ExprKind::Variable(name) => Some(name.trim_start_matches('$').to_string()),
        ExprKind::Parenthesized(inner) => extract_var_name(inner),
        // is_null($x = expr) — narrow the assigned variable, not the RHS
        ExprKind::Assign(a) if matches!(a.op, AssignOp::Assign) => extract_var_name(&a.target),
        _ => None,
    }
}

/// Extract a compact key for simple expressions used as the first arg of
/// `method_exists`/`property_exists`. Supports `$var` → `"var"`,
/// `$var->prop` → `"var->prop"` (depth-1 only), `Foo::class` and `'Foo'`
/// literals → the resolved FQCN prefixed `"cls:"` (the two class-name forms
/// are interchangeable and register the same key; `cls:` is disjoint from the
/// variable-key namespace, so a variable named e.g. `Foo` can never collide
/// with a class-name guard). Returns `None` for anything more complex so we
/// don't risk false-positive suppression.
pub(crate) fn extract_expr_guard_key(
    expr: &php_ast::owned::Expr,
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<std::sync::Arc<str>> {
    match &expr.kind {
        ExprKind::Variable(name) => Some(std::sync::Arc::from(name.trim_start_matches('$'))),
        ExprKind::Parenthesized(inner) => extract_expr_guard_key(inner, ctx, db, file),
        ExprKind::PropertyAccess(pa) => {
            let base = extract_var_name(&pa.object)?;
            let prop = match &pa.property.kind {
                ExprKind::Identifier(s) => s.as_ref(),
                ExprKind::Variable(s) => s.trim_start_matches('$'),
                _ => return None,
            };
            Some(std::sync::Arc::from(format!("{base}->{prop}").as_str()))
        }
        ExprKind::StaticPropertyAccess(_) => {
            let (fqcn, prop) = extract_static_prop_access(expr, ctx, db, file)?;
            Some(std::sync::Arc::from(
                format!("static:{fqcn}::{prop}").as_str(),
            ))
        }
        ExprKind::ClassConstAccess(cca) => {
            let ExprKind::Identifier(member) = &cca.member.kind else {
                return None;
            };
            if !member.eq_ignore_ascii_case("class") {
                return None;
            }
            let ExprKind::Identifier(class_name) = &cca.class.kind else {
                return None;
            };
            let resolved = crate::db::resolve_name(db, file, class_name.as_ref());
            Some(std::sync::Arc::from(format!("cls:{resolved}").as_str()))
        }
        // 'Foo\Bar' — a class name as a string literal (the form
        // method_exists()/property_exists() take when the object can't be
        // named as an expression). Resolved against the file's namespace
        // exactly like the `Foo::class` form above, so both register the
        // same `cls:` key.
        ExprKind::String(s) => {
            let resolved = crate::db::resolve_name(db, file, s.as_ref());
            Some(std::sync::Arc::from(format!("cls:{resolved}").as_str()))
        }
        _ => None,
    }
}

/// The subject of a `match`/`switch` statement, whichever receiver shape it
/// is — used to narrow each arm's context by intersecting the subject's
/// type with that arm's condition type, same as a plain variable subject
/// already did (a property/static-property subject is just as valid a
/// narrowing target).
pub(crate) enum MatchSubject {
    Var(String),
    Prop(String, String),
    Static(std::sync::Arc<str>, String),
    ShapePath(ShapeBase, Vec<mir_types::atomic::ArrayKey>),
}

impl MatchSubject {
    pub(crate) fn extract(
        expr: &php_ast::owned::Expr,
        ctx: &FlowState,
        db: &dyn MirDatabase,
        file: &str,
    ) -> Option<Self> {
        if let Some(name) = extract_var_name(expr) {
            return Some(MatchSubject::Var(name));
        }
        if let Some((obj, prop)) = extract_prop_access(expr) {
            return Some(MatchSubject::Prop(obj, prop));
        }
        if let Some((base, path)) = collect_array_access_path(expr, ctx, db, file) {
            return Some(MatchSubject::ShapePath(base, path));
        }
        extract_static_prop_access(expr, ctx, db, file)
            .map(|(fqcn, prop)| MatchSubject::Static(fqcn, prop))
    }
}

pub(super) fn extract_null_coalesce(
    expr: &php_ast::owned::Expr,
) -> Option<&php_ast::owned::NullCoalesceExpr> {
    match &expr.kind {
        ExprKind::NullCoalesce(nc) => Some(nc),
        ExprKind::Parenthesized(inner) => extract_null_coalesce(inner),
        _ => None,
    }
}

pub(super) fn same_literal(a: &php_ast::owned::Expr, b: &php_ast::owned::Expr) -> bool {
    let a = peel_parens(a);
    let b = peel_parens(b);
    match (&a.kind, &b.kind) {
        (ExprKind::Null, ExprKind::Null) => true,
        (ExprKind::Bool(a), ExprKind::Bool(b)) => a == b,
        (ExprKind::Int(a), ExprKind::Int(b)) => a == b,
        (ExprKind::String(a), ExprKind::String(b)) => a == b,
        _ => false,
    }
}

pub(super) fn peel_parens(expr: &php_ast::owned::Expr) -> &php_ast::owned::Expr {
    match &expr.kind {
        ExprKind::Parenthesized(inner) => peel_parens(inner),
        _ => expr,
    }
}

/// `self`/`static`/`parent` are bare keywords, not real class names —
/// `db::resolve_name` deliberately returns them unresolved (it has no class
/// context), so they must be resolved to a concrete FQCN here, where the
/// surrounding class context (`self_fqcn`/`parent_fqcn`) is available.
/// `static` resolves to `self_fqcn` too: it's late-static-binding, so the
/// exact runtime class is unknown, but `self_fqcn` is its precise lower
/// bound — the same approximation `Atomic::TStaticObject` uses elsewhere.
pub(super) fn extract_class_name(
    expr: &php_ast::owned::Expr,
    self_fqcn: Option<&str>,
    parent_fqcn: Option<&str>,
) -> Option<String> {
    match &expr.kind {
        ExprKind::Identifier(name) => match name.to_ascii_lowercase().as_str() {
            "self" | "static" => self_fqcn.map(|s| s.to_string()),
            "parent" => parent_fqcn.map(|s| s.to_string()),
            _ => Some(name.to_string()),
        },
        ExprKind::Variable(name) if name.trim_start_matches('$') == "this" => {
            self_fqcn.map(|s| s.to_string())
        }
        ExprKind::Variable(_) => None, // dynamic class — can't narrow
        _ => None,
    }
}

/// Promote variables that were assigned as side effects of evaluating `expr`.
///
/// Called when we know `expr` was definitely evaluated (e.g., from the true-branch
/// of `&&` or the false-branch of `||`). Promotes variables that are in
/// `possibly_assigned_vars` up to `assigned_vars` if they appear as assignment
/// targets inside `expr`.
///
/// Conservative for internal short-circuit operators: only recurses into the
/// guaranteed-evaluated side (LHS) of nested `&&`/`||` sub-expressions, since
/// we cannot know whether the RHS of those was reached.
pub(crate) fn promote_assignment_effects(
    expr: &php_ast::owned::Expr,
    ctx: &mut FlowState,
    db: &dyn crate::db::MirDatabase,
    file: &str,
) {
    match &expr.kind {
        ExprKind::Assign(a) => {
            if let Some(var_name) = extract_var_name(&a.target) {
                let sym = mir_types::Name::from(var_name.as_str());
                if ctx.possibly_assigned_vars.contains(&sym) {
                    let ty = ctx.get_var(&var_name);
                    ctx.narrow_var(&var_name, ty);
                    std::sync::Arc::make_mut(&mut ctx.possibly_assigned_vars).remove(&sym);
                }
            }
            promote_assignment_effects(&a.value, ctx, db, file);
        }
        ExprKind::UnaryPrefix(u) => {
            promote_assignment_effects(&u.operand, ctx, db, file);
        }
        ExprKind::FunctionCall(call) => {
            // Promote variables that were assigned via by-ref parameters
            if let ExprKind::Identifier(fn_name) = &call.name.kind {
                let resolved = crate::db::resolve_name(db, file, fn_name.as_ref());
                let find =
                    |name: &str| crate::db::find_function(db, crate::db::Fqcn::from_str(db, name));
                // Unqualified calls fall back to the global function.
                let func = find(&resolved).or_else(|| {
                    (!fn_name.starts_with('\\') && !fn_name.contains('\\'))
                        .then(|| find(fn_name.as_ref()))
                        .flatten()
                });
                if let Some(func) = func {
                    for (i, param) in func.params.iter().enumerate() {
                        if param.is_byref {
                            let arg = call.args.get(i);
                            if let Some(arg) = arg {
                                if let Some(value) = &arg.value {
                                    if let ExprKind::Variable(name) = &value.kind {
                                        let var_name = name.as_ref().trim_start_matches('$');
                                        let sym = mir_types::Name::from(var_name);
                                        if ctx.possibly_assigned_vars.contains(&sym) {
                                            let ty = ctx.get_var(var_name);
                                            ctx.narrow_var(var_name, ty);
                                            std::sync::Arc::make_mut(
                                                &mut ctx.possibly_assigned_vars,
                                            )
                                            .remove(&sym);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            for arg in call.args.iter() {
                if let Some(value) = &arg.value {
                    promote_assignment_effects(value, ctx, db, file);
                }
            }
        }
        ExprKind::MethodCall(mc) | ExprKind::NullsafeMethodCall(mc) => {
            promote_assignment_effects(&mc.object, ctx, db, file);
            for arg in mc.args.iter() {
                if let Some(value) = &arg.value {
                    promote_assignment_effects(value, ctx, db, file);
                }
            }
        }
        ExprKind::StaticMethodCall(smc) => {
            for arg in smc.args.iter() {
                if let Some(value) = &arg.value {
                    promote_assignment_effects(value, ctx, db, file);
                }
            }
        }
        // For nested &&: LHS is always evaluated; RHS might short-circuit — only recurse LHS.
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanAnd || b.op == BinaryOp::LogicalAnd => {
            promote_assignment_effects(&b.left, ctx, db, file);
        }
        // For nested ||: LHS is always evaluated; RHS might short-circuit — only recurse LHS.
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanOr || b.op == BinaryOp::LogicalOr => {
            promote_assignment_effects(&b.left, ctx, db, file);
        }
        // For all other binary operators (===, !==, instanceof, +, etc.) both sides are evaluated.
        ExprKind::Binary(b) => {
            promote_assignment_effects(&b.left, ctx, db, file);
            promote_assignment_effects(&b.right, ctx, db, file);
        }
        ExprKind::Parenthesized(inner) => {
            promote_assignment_effects(inner, ctx, db, file);
        }
        // The condition always runs; the branches are conditional.
        ExprKind::Ternary(t) => {
            promote_assignment_effects(&t.condition, ctx, db, file);
        }
        ExprKind::Cast(_, inner) => {
            promote_assignment_effects(inner, ctx, db, file);
        }
        // `isset` stops at the first unset operand, so only the first is certain to run.
        ExprKind::Isset(args) => {
            if let Some(first) = args.first() {
                promote_assignment_effects(first, ctx, db, file);
            }
        }
        ExprKind::Array(elements) => {
            for element in elements.iter() {
                if let Some(key) = &element.key {
                    promote_assignment_effects(key, ctx, db, file);
                }
                promote_assignment_effects(&element.value, ctx, db, file);
            }
        }
        // `a ?? b`: only `a` is certain to run — `b` is skipped when `a` is set.
        ExprKind::NullCoalesce(nc) => {
            promote_assignment_effects(&nc.left, ctx, db, file);
        }
        // Array access: both base and index are evaluated; assignments inside either matter.
        ExprKind::ArrayAccess(aa) => {
            promote_assignment_effects(&aa.array, ctx, db, file);
            if let Some(idx) = &aa.index {
                promote_assignment_effects(idx, ctx, db, file);
            }
        }
        _ => {}
    }
}

/// A `gettype()`/`get_debug_type()` argument, resolved to either a plain
/// variable or a `$obj->prop` property access — lets a single literal-mapping
/// function (`narrow_from_gettype_literal`/`narrow_from_get_debug_type_literal`)
/// dispatch to the right narrowing entry point (`narrow_from_type_fn` vs
/// `narrow_prop_from_type_fn`/`narrow_prop_to_specific_class`) for either
/// receiver shape.
pub(super) enum ScalarArgTarget {
    Var(String),
    Prop(String, String),
}

impl ScalarArgTarget {
    pub(super) fn extract(expr: &php_ast::owned::Expr) -> Option<Self> {
        if let Some(name) = extract_var_name(expr) {
            return Some(ScalarArgTarget::Var(name));
        }
        // `extract_any_prop_access` so a nullsafe receiver (`$x?->prop`) is
        // recognized too — a plain `->` on a null receiver evaluates to null
        // in PHP 8 same as `?->`, so every consumer here already narrows both
        // identically once the target is extracted.
        extract_any_prop_access(expr).map(|(obj, prop)| ScalarArgTarget::Prop(obj, prop))
    }
}

// ---------------------------------------------------------------------------
// Extension methods on Type used only in narrowing
// ---------------------------------------------------------------------------

pub(super) trait UnionNarrowExt {
    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type;
}

impl UnionNarrowExt for Type {
    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
        let mut result = Type::empty();
        result.possibly_undefined = self.possibly_undefined;
        result.from_docblock = self.from_docblock;
        for atomic in &self.types {
            if f(atomic) {
                result.types.push(atomic.clone());
            }
        }
        result
    }
}

pub(crate) fn is_numeric_string(s: &str) -> bool {
    let t = s.trim();
    if t.is_empty() {
        return false;
    }
    // Rust's f64 parser accepts "inf"/"nan"/"infinity" (case-insensitively,
    // optionally signed) as valid floats, but PHP's is_numeric() does not —
    // reject non-finite results so e.g. "NAN" isn't treated as numeric.
    t.parse::<i64>().is_ok() || t.parse::<f64>().is_ok_and(f64::is_finite)
}

/// `count($arr) op N` / `strlen($str) op N` for the equality operators
/// (`===`, `!==`, `==`, `!=`) — the `<`/`<=`/`>`/`>=` forms are normalized
/// and handled inline where those operators are matched; equality is
/// symmetric so, unlike that relational-operator normalization, no operator
/// flip is needed when the call is on the right-hand side.
pub(super) fn narrow_count_or_strlen_equality(
    ctx: &mut FlowState,
    db: &dyn MirDatabase,
    file: &str,
    left: &php_ast::owned::Expr,
    right: &php_ast::owned::Expr,
    op: BinaryOp,
    is_true: bool,
) {
    let count_on_left = extract_count_arg(left).is_some()
        || extract_count_static_prop_arg(left, ctx, db, file).is_some();
    let (count_expr, count_lit) = if count_on_left {
        (left, right)
    } else {
        (right, left)
    };
    if let (Some(target), Some(n)) = (
        extract_count_arg(count_expr),
        extract_int_literal(count_lit),
    ) {
        match target {
            ScalarArgTarget::Var(arr_var) => {
                narrow_array_count_comparison(ctx, &arr_var, op, n, is_true)
            }
            ScalarArgTarget::Prop(obj, prop) => {
                narrow_prop_array_count_comparison(ctx, &obj, &prop, db, file, op, n, is_true)
            }
        }
        return;
    } else if let (Some((fqcn, prop)), Some(n)) = (
        extract_count_static_prop_arg(count_expr, ctx, db, file),
        extract_int_literal(count_lit),
    ) {
        narrow_static_prop_array_count_comparison(ctx, &fqcn, &prop, db, op, n, is_true);
        return;
    }
    let strlen_on_left = extract_strlen_arg(left).is_some()
        || extract_strlen_static_prop_arg(left, ctx, db, file).is_some();
    let (strlen_expr, strlen_lit) = if strlen_on_left {
        (left, right)
    } else {
        (right, left)
    };
    if let (Some(target), Some(n)) = (
        extract_strlen_arg(strlen_expr),
        extract_int_literal(strlen_lit),
    ) {
        match target {
            ScalarArgTarget::Var(str_var) => {
                narrow_string_strlen_comparison(ctx, &str_var, op, n, is_true)
            }
            ScalarArgTarget::Prop(obj, prop) => {
                narrow_prop_string_strlen_comparison(ctx, &obj, &prop, db, file, op, n, is_true)
            }
        }
    } else if let (Some((fqcn, prop)), Some(n)) = (
        extract_strlen_static_prop_arg(strlen_expr, ctx, db, file),
        extract_int_literal(strlen_lit),
    ) {
        narrow_static_prop_string_strlen_comparison(ctx, &fqcn, &prop, db, op, n, is_true);
    }
}

/// Whether `count()`/`strlen() op n` being `is_true` proves the underlying
/// collection/string is non-empty (`Some(true)`) or empty (`Some(false)`);
/// `None` if the comparison proves neither (count/strlen is always >= 0, so
/// e.g. `count($x) < 5` proves nothing about emptiness either way).
pub(super) fn count_or_strlen_emptiness(op: BinaryOp, n: i64, is_true: bool) -> Option<bool> {
    match (op, is_true) {
        (BinaryOp::Greater, true) if n >= 0 => Some(true), // len > 0 (or > n>=0)
        (BinaryOp::GreaterOrEqual, true) if n >= 1 => Some(true), // len >= 1
        (BinaryOp::Less, false) if n >= 1 => Some(true),   // NOT (len < 1)
        (BinaryOp::LessOrEqual, false) if n >= 0 => Some(true), // NOT (len <= 0)
        // len === N / == N, true, for a positive N: an exact positive length is non-empty.
        (BinaryOp::Identical | BinaryOp::Equal, true) if n >= 1 => Some(true),
        // len === 0 / == 0, false: length is proven not zero.
        (BinaryOp::Identical | BinaryOp::Equal, false) if n == 0 => Some(true),
        // len !== 0 / != 0, true: length is proven not zero.
        (BinaryOp::NotIdentical | BinaryOp::NotEqual, true) if n == 0 => Some(true),
        // len !== N / != N, false, for a positive N: length equals that N exactly.
        (BinaryOp::NotIdentical | BinaryOp::NotEqual, false) if n >= 1 => Some(true),
        // Mirror image: len < n / len <= n / NOT(len >= n) / NOT(len > n) with
        // n small enough that, combined with len >= 0, length must be exactly 0.
        (BinaryOp::Less, true) if n <= 1 => Some(false),
        (BinaryOp::LessOrEqual, true) if n <= 0 => Some(false),
        (BinaryOp::GreaterOrEqual, false) if n <= 1 => Some(false),
        (BinaryOp::Greater, false) if n <= 0 => Some(false),
        // len === 0 / == 0, true: length is proven exactly zero.
        (BinaryOp::Identical | BinaryOp::Equal, true) if n == 0 => Some(false),
        // len !== N / != N, false, for N == 0: length equals zero exactly.
        (BinaryOp::NotIdentical | BinaryOp::NotEqual, false) if n == 0 => Some(false),
        _ => None,
    }
}

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

    #[test]
    fn numeric_strings_are_recognized() {
        assert!(is_numeric_string("42"));
        assert!(is_numeric_string("-42"));
        assert!(is_numeric_string("+42"));
        assert!(is_numeric_string("3.14"));
        assert!(is_numeric_string(".5"));
        assert!(is_numeric_string("1e10"));
        assert!(is_numeric_string("  123  "));
    }

    #[test]
    fn non_numeric_strings_are_rejected() {
        assert!(!is_numeric_string(""));
        assert!(!is_numeric_string("   "));
        assert!(!is_numeric_string("hello"));
        assert!(!is_numeric_string("0x1A"));
        assert!(!is_numeric_string("12abc"));
    }

    #[test]
    fn nan_and_infinity_keywords_are_not_numeric() {
        // PHP's is_numeric() rejects these, unlike Rust's f64 parser.
        assert!(!is_numeric_string("NAN"));
        assert!(!is_numeric_string("nan"));
        assert!(!is_numeric_string("INF"));
        assert!(!is_numeric_string("-INF"));
        assert!(!is_numeric_string("Infinity"));
        assert!(!is_numeric_string("-Infinity"));
    }
}