Skip to content

Commit 31cc5e2

Browse files
calebdwAJenbo
authored andcommitted
fix(diagnostics): resolve literal types for argument type checking
Fixes #180 — string/int/float literal expressions passed as arguments are now narrowed to their precise literal type (e.g. `'desc'` becomes `PhpType::Literal("'desc'")`) instead of the widened base type (`string`). This allows literal values to correctly match PHPDoc literal-union parameter types like `'asc'|'desc'`. Also fixes `is_string_subtype()` and `is_int_subtype()` to handle `PhpType::Union` — a union of string/int literals (e.g. `'asc'|'desc'`) is now recognised as a string/int subtype, allowing PHPDoc `@param` annotations with literal unions to properly override native scalar type hints. The narrowing is applied only in the diagnostic argument-collection path (not in general variable resolution) to avoid changing inferred types for array shapes and list element tracking. Includes 8 new integration tests covering correct and incorrect string, integer, and float literals against literal-union parameters, plus precise numeric-string checking (`'42'` passes, `'hello'` is flagged). Closes #180 Signed-off-by: Anders Jenbo <[email protected]>
1 parent 4951466 commit 31cc5e2

4 files changed

Lines changed: 232 additions & 14 deletions

File tree

‎docs/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3131

3232
### Fixed
3333

34+
- **Literal type matching in argument diagnostics.** String, integer, and float literal arguments now match PHPDoc literal-union parameter types. For example, `orderBy('id', 'desc')` no longer produces a bogus error when the parameter is typed as `'asc'|'desc'`. Conversely, passing a provably wrong literal (e.g. `'invalid'` to `'asc'|'desc'`, or `'hello'` to `numeric-string`) is now correctly flagged. Fixes #180. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/191.
3435
- **Type Hierarchy works in more clients.** The `textDocument/prepareTypeHierarchy` capability was registered without registration options, so some clients (notably Zed) did not reliably expose the Type Hierarchy action. The dynamic registration now carries proper `TypeHierarchyRegistrationOptions` with a PHP document selector, so those clients recognise that the feature applies to PHP files. Contributed by @sidux in https://github.com/PHPantom-dev/phpantom_lsp/pull/179.
3536
- **Extract method generates correct code for more selections.** A variable that the selection reads before it first assigns (for example a parameter the extracted code both consults and updates) is now passed in as an argument as well as returned, instead of being left undefined inside the new method. And an early `return` whose value references a variable defined inside the selection is now kept inside the extracted method and propagated to the caller, instead of being copied to the call site where that variable does not exist.
3637
- **The editor stays responsive during fast typing in large files.** Editors send a burst of requests on every keystroke (completion, a documentation lookup for each suggestion, diagnostics, code lens, semantic highlighting, and more). The server processed only a few at a time, so during continuous typing the burst backed up until the server stopped answering anything at all, including the completion the user was waiting on, and it only recovered after a restart. Now the burst is processed concurrently and every expensive request runs off the main loop: diagnostics (which re-analyze the whole file on each edit) compute in the background instead of on the request that asked for them, so a diagnostic pull returns immediately and never blocks the threads that deliver completion and hover, and repeated whole-file requests (semantic highlighting, code lens, the document outline, folding, document links) are collapsed so a fast typist's superseded requests no longer pile up and monopolize the CPU. Completion and other requests keep coming back while you type.

‎src/diagnostics/type_errors.rs‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,13 @@ use mago_span::HasSpan;
1616
use mago_syntax::ast::argument::Argument;
1717
use mago_syntax::ast::call::Call;
1818
use mago_syntax::ast::expression::Expression;
19+
use mago_syntax::ast::literal::Literal;
1920
use mago_syntax::ast::statement::Statement;
2021

2122
use tower_lsp::lsp_types::*;
2223

2324
use crate::Backend;
25+
use crate::atom::bytes_to_str;
2426
use crate::completion::resolver::{Loaders, VarResolutionCtx};
2527
use crate::completion::variable::foreach_resolution::resolve_expression_type;
2628
use crate::parser::{with_parse_cache, with_parsed_program};
@@ -300,13 +302,21 @@ fn is_type_compatible(
300302
// ── PHP type juggling: int → string ─────────────────────────
301303
// PHP coerces int to string in many contexts (concatenation,
302304
// function calls with declare(strict_types=0)). Since we can't
303-
// know the strict_types setting, stay silent.
305+
// know the strict_types setting, stay silent. Also covers
306+
// integer literals (e.g. `42` passed to `string`).
304307
if let PhpType::Named(sup) = param_type
305308
&& sup.eq_ignore_ascii_case("string")
306-
&& let PhpType::Named(sub) = arg_type
307-
&& matches!(sub.to_ascii_lowercase().as_str(), "int" | "integer")
308309
{
309-
return true;
310+
let is_int_like = match arg_type {
311+
PhpType::Named(sub) => {
312+
matches!(sub.to_ascii_lowercase().as_str(), "int" | "integer")
313+
}
314+
PhpType::Literal(lit) => lit.parse::<i64>().is_ok(),
315+
_ => false,
316+
};
317+
if is_int_like {
318+
return true;
319+
}
310320
}
311321

312322
// ── PHP type juggling: numeric-string → float/int ───────────
@@ -1441,6 +1451,34 @@ impl Backend {
14411451
let arg_ctx = var_ctx.with_cursor_offset(start as u32);
14421452
let ty = resolve_expression_type(arg_expr, &arg_ctx)
14431453
.unwrap_or_else(PhpType::untyped);
1454+
// Narrow scalar literals to their precise literal
1455+
// type so that e.g. `'desc'` matches `'asc'|'desc'`
1456+
// and `2` matches `1|2|3`. The general expression
1457+
// resolver returns the widened base type (`string`,
1458+
// `int`, `float`) which is correct for variable
1459+
// tracking, but for argument diagnostics we need
1460+
// the exact value to compare against literal types.
1461+
//
1462+
// Numeric literals use the parsed value rather than
1463+
// the raw source text so that non-decimal forms
1464+
// (`0xFF`, `0b1010`, `0o17`, `1_000`) still match
1465+
// `int`/`float`/`numeric` parameters and decimal
1466+
// literal unions (`1|2|3`). The raw text would not
1467+
// parse back into a number and would be flagged as
1468+
// an incompatible argument.
1469+
let ty = match arg_expr {
1470+
Expression::Literal(Literal::String(s)) => {
1471+
PhpType::Literal(bytes_to_str(s.raw).to_string())
1472+
}
1473+
Expression::Literal(Literal::Integer(i)) => match i.value {
1474+
Some(value) => PhpType::Literal(value.to_string()),
1475+
None => ty,
1476+
},
1477+
Expression::Literal(Literal::Float(f)) => {
1478+
PhpType::Literal(f.value.into_inner().to_string())
1479+
}
1480+
_ => ty,
1481+
};
14441482
// Resolve any short class names in the arg type
14451483
// to FQN via the class loader. Variable
14461484
// resolution may return raw docblock names

‎src/php_type.rs‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,9 @@ impl PhpType {
739739
name.to_ascii_lowercase().as_str(),
740740
"class-string" | "interface-string" | "model-property"
741741
),
742+
PhpType::Union(members) => {
743+
!members.is_empty() && members.iter().all(|m| m.is_string_subtype())
744+
}
742745
_ => false,
743746
}
744747
}
@@ -767,17 +770,26 @@ impl PhpType {
767770
!trimmed.is_empty() && trimmed.bytes().all(|b| b.is_ascii_digit())
768771
}
769772
PhpType::Nullable(inner) => inner.is_int_subtype(),
773+
PhpType::Union(members) => {
774+
!members.is_empty() && members.iter().all(|m| m.is_int_subtype())
775+
}
770776
_ => false,
771777
}
772778
}
773779

774-
/// Whether this type is `float` or `double` (case-insensitive).
780+
/// Whether this type is `float`, `double`, a float literal, or a
781+
/// union of float subtypes (case-insensitive).
775782
///
776-
/// This is currently identical to [`is_float`], but exists for
777-
/// symmetry with [`is_string_subtype`] and [`is_int_subtype`] and
778-
/// may be extended with float refinement types in the future.
783+
/// Extends [`is_float`] with literal and union handling for
784+
/// symmetry with [`is_string_subtype`] and [`is_int_subtype`].
779785
pub fn is_float_subtype(&self) -> bool {
780-
self.is_float()
786+
match self {
787+
PhpType::Literal(s) => s.parse::<f64>().is_ok(),
788+
PhpType::Union(members) => {
789+
!members.is_empty() && members.iter().all(|m| m.is_float_subtype())
790+
}
791+
_ => self.is_float(),
792+
}
781793
}
782794

783795
/// Whether this type is `object` (case-insensitive).

‎tests/integration/diagnostics_type_errors.rs‎

Lines changed: 172 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,22 +1078,39 @@ function test(): void {
10781078
}
10791079

10801080
#[test]
1081-
fn no_diagnostic_for_non_numeric_string_literal_to_numeric_string() {
1082-
// String literals resolve as bare `string` in the expression resolver,
1083-
// so we cannot distinguish numeric from non-numeric at the type level.
1084-
// Conservative: stay silent because the string *might* be numeric.
1081+
fn flags_non_numeric_string_literal_to_numeric_string() {
1082+
// String literals are now narrowed to their literal type in argument
1083+
// diagnostics, so we CAN prove `'hello'` is not a numeric-string.
10851084
let php = r#"<?php
10861085
/** @param numeric-string $v */
10871086
function takes_numeric_string(string $v): void {}
10881087
10891088
function test(): void {
10901089
takes_numeric_string('hello');
10911090
}
1091+
"#;
1092+
let diags = collect(php);
1093+
assert!(
1094+
has_type_error(&diags),
1095+
"Should flag non-numeric string literal 'hello' passed to numeric-string param, got: {diags:?}"
1096+
);
1097+
}
1098+
1099+
#[test]
1100+
fn no_diagnostic_for_numeric_string_literal_to_numeric_string_precise() {
1101+
// A numeric string literal like '42' IS a valid numeric-string.
1102+
let php = r#"<?php
1103+
/** @param numeric-string $v */
1104+
function takes_numeric_string(string $v): void {}
1105+
1106+
function test(): void {
1107+
takes_numeric_string('42');
1108+
}
10921109
"#;
10931110
let diags = collect(php);
10941111
assert!(
10951112
!has_type_error(&diags),
1096-
"Should not flag string literal passed to numeric-string param (conservative), got: {diags:?}"
1113+
"Should not flag numeric string literal '42' passed to numeric-string param, got: {diags:?}"
10971114
);
10981115
}
10991116

@@ -3863,3 +3880,153 @@ class TestCase {
38633880
"Property narrowed via instanceof should be accepted as MockInterface, got: {msgs:?}"
38643881
);
38653882
}
3883+
3884+
// ─── Literal string matching literal type in union ──────────────────────────
3885+
3886+
#[test]
3887+
fn no_false_positive_for_string_literal_matching_literal_type() {
3888+
let php = r#"<?php
3889+
/** @param 'asc'|'desc' $direction */
3890+
function orderBy(string $column, string $direction): void {}
3891+
3892+
function test(): void {
3893+
orderBy('id', 'desc');
3894+
orderBy('name', 'asc');
3895+
}
3896+
"#;
3897+
let diags = collect(php);
3898+
let msgs = type_error_messages(&diags);
3899+
assert!(
3900+
msgs.is_empty(),
3901+
"String literal 'desc' should match literal type 'desc' in union, got: {msgs:?}"
3902+
);
3903+
}
3904+
3905+
#[test]
3906+
fn flags_wrong_string_literal_for_literal_type() {
3907+
let php = r#"<?php
3908+
/** @param 'asc'|'desc' $direction */
3909+
function orderBy(string $column, string $direction): void {}
3910+
3911+
function test(): void {
3912+
orderBy('id', 'invalid');
3913+
}
3914+
"#;
3915+
let diags = collect(php);
3916+
assert!(
3917+
has_type_error(&diags),
3918+
"String literal 'invalid' should NOT match 'asc'|'desc', got: {diags:?}"
3919+
);
3920+
}
3921+
3922+
#[test]
3923+
fn no_false_positive_for_int_literal_matching_literal_type() {
3924+
let php = r#"<?php
3925+
/** @param 1|2|3 $mode */
3926+
function setMode(int $mode): void {}
3927+
3928+
function test(): void {
3929+
setMode(2);
3930+
}
3931+
"#;
3932+
let diags = collect(php);
3933+
let msgs = type_error_messages(&diags);
3934+
assert!(
3935+
msgs.is_empty(),
3936+
"Integer literal 2 should match literal type 2 in union, got: {msgs:?}"
3937+
);
3938+
}
3939+
3940+
#[test]
3941+
fn flags_wrong_int_literal_for_literal_type() {
3942+
let php = r#"<?php
3943+
/** @param 1|2|3 $mode */
3944+
function setMode(int $mode): void {}
3945+
3946+
function test(): void {
3947+
setMode(99);
3948+
}
3949+
"#;
3950+
let diags = collect(php);
3951+
assert!(
3952+
has_type_error(&diags),
3953+
"Integer literal 99 should NOT match 1|2|3, got: {diags:?}"
3954+
);
3955+
}
3956+
3957+
#[test]
3958+
fn no_false_positive_for_float_literal_matching_literal_type() {
3959+
let php = r#"<?php
3960+
/** @param 1.5|2.5|3.5 $rate */
3961+
function setRate(float $rate): void {}
3962+
3963+
function test(): void {
3964+
setRate(2.5);
3965+
}
3966+
"#;
3967+
let diags = collect(php);
3968+
let msgs = type_error_messages(&diags);
3969+
assert!(
3970+
msgs.is_empty(),
3971+
"Float literal 2.5 should match literal type 2.5 in union, got: {msgs:?}"
3972+
);
3973+
}
3974+
3975+
#[test]
3976+
fn flags_wrong_float_literal_for_literal_type() {
3977+
let php = r#"<?php
3978+
/** @param 1.5|2.5|3.5 $rate */
3979+
function setRate(float $rate): void {}
3980+
3981+
function test(): void {
3982+
setRate(9.9);
3983+
}
3984+
"#;
3985+
let diags = collect(php);
3986+
assert!(
3987+
has_type_error(&diags),
3988+
"Float literal 9.9 should NOT match 1.5|2.5|3.5, got: {diags:?}"
3989+
);
3990+
}
3991+
3992+
#[test]
3993+
fn no_false_positive_for_non_decimal_int_literals_matching_int_param() {
3994+
// Hex, binary, octal, and underscore-separated integer literals are
3995+
// narrowed to their parsed value, so they still satisfy an `int`
3996+
// parameter (their raw source text would not parse back into a number).
3997+
let php = r#"<?php
3998+
function takes_int(int $x): void {}
3999+
4000+
function test(): void {
4001+
takes_int(0xFF);
4002+
takes_int(0b1010);
4003+
takes_int(1_000);
4004+
takes_int(0o17);
4005+
}
4006+
"#;
4007+
let diags = collect(php);
4008+
assert!(
4009+
!has_type_error(&diags),
4010+
"Non-decimal int literals should match int param, got: {:?}",
4011+
type_error_messages(&diags)
4012+
);
4013+
}
4014+
4015+
#[test]
4016+
fn no_false_positive_for_hex_literal_matching_decimal_literal_union() {
4017+
// `0x2` is value 2, which is a member of the decimal literal union.
4018+
let php = r#"<?php
4019+
/** @param 1|2|3 $mode */
4020+
function setMode(int $mode): void {}
4021+
4022+
function test(): void {
4023+
setMode(0x2);
4024+
}
4025+
"#;
4026+
let diags = collect(php);
4027+
let msgs = type_error_messages(&diags);
4028+
assert!(
4029+
msgs.is_empty(),
4030+
"Hex literal 0x2 should match decimal literal 2 in union, got: {msgs:?}"
4031+
);
4032+
}

0 commit comments

Comments
 (0)