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
use super::helpers::{
extract_simple_var, extract_string_from_expr, infer_arithmetic, property_assign_compatible,
type_refs_any_template, widen_array_as_list, widen_array_with_value_and_key,
};
use super::ExpressionAnalyzer;
use crate::flow_state::FlowState;
use mir_issues::{IssueKind, Severity};
use mir_types::{Atomic, Type};
use php_ast::ast::AssignOp;
use php_ast::owned::{AssignExpr, Expr, ExprKind};
use php_ast::Span;
use rustc_hash::FxHashSet;
impl<'a> ExpressionAnalyzer<'a> {
pub(super) fn analyze_assign(
&mut self,
a: &AssignExpr,
expr_span: Span,
ctx: &mut FlowState,
) -> Type {
let rhs_tainted = crate::taint::is_expr_tainted(&a.value, ctx);
let rhs_ty = self.analyze(&a.value, ctx);
if rhs_ty.is_never() {
return rhs_ty;
}
match a.op {
AssignOp::Assign => {
self.assign_to_target(&a.target, rhs_ty.clone(), ctx, expr_span);
if rhs_tainted {
if let ExprKind::Variable(name) = &a.target.kind {
ctx.taint_var(name.as_ref());
}
}
rhs_ty
}
AssignOp::Concat => {
if let Some(var_name) = extract_simple_var(&a.target) {
ctx.set_var(&var_name, Type::single(Atomic::TString));
let (line, col_start) = self.offset_to_line_col(a.target.span.start);
let (line_end, col_end) = self.offset_to_line_col(a.target.span.end);
ctx.record_var_location(&var_name, line, col_start, line_end, col_end);
}
Type::single(Atomic::TString)
}
AssignOp::Plus
| AssignOp::Minus
| AssignOp::Mul
| AssignOp::Div
| AssignOp::Mod
| AssignOp::Pow => {
let lhs_ty = self.analyze(&a.target, ctx);
let result_ty = infer_arithmetic(&lhs_ty, &rhs_ty);
if let Some(var_name) = extract_simple_var(&a.target) {
ctx.set_var(&var_name, result_ty.clone());
let (line, col_start) = self.offset_to_line_col(a.target.span.start);
let (line_end, col_end) = self.offset_to_line_col(a.target.span.end);
ctx.record_var_location(&var_name, line, col_start, line_end, col_end);
}
result_ty
}
AssignOp::Coalesce => {
let lhs_ty = self.with_existence_check(|ea| ea.analyze(&a.target, ctx));
let merged = Type::merge(&lhs_ty.remove_null(), &rhs_ty);
if let Some(var_name) = extract_simple_var(&a.target) {
ctx.set_var(&var_name, merged.clone());
let (line, col_start) = self.offset_to_line_col(a.target.span.start);
let (line_end, col_end) = self.offset_to_line_col(a.target.span.end);
ctx.record_var_location(&var_name, line, col_start, line_end, col_end);
}
merged
}
_ => {
if let Some(var_name) = extract_simple_var(&a.target) {
ctx.set_var(&var_name, Type::mixed());
let (line, col_start) = self.offset_to_line_col(a.target.span.start);
let (line_end, col_end) = self.offset_to_line_col(a.target.span.end);
ctx.record_var_location(&var_name, line, col_start, line_end, col_end);
}
Type::mixed()
}
}
}
pub(super) fn assign_to_target(
&mut self,
target: &Expr,
ty: Type,
ctx: &mut FlowState,
span: Span,
) {
match &target.kind {
ExprKind::Variable(name) => {
let name_str = name.trim_start_matches('$').to_string();
let name_sym = mir_types::Name::from(name_str.as_str());
// Assigning to $this is not allowed
if name_str == "this" {
self.emit(
IssueKind::InvalidScope {
in_class: ctx.self_fqcn.is_some(),
},
Severity::Error,
span,
);
}
ctx.set_var(&name_str, ty);
let (line, col_start) = self.offset_to_line_col(target.span.start);
let (line_end, col_end) = self.offset_to_line_col(target.span.end);
if ctx.byref_param_names.contains(&name_sym) {
// Byref/global write: mark as read (externally observable) and clear
// any pending dead-write entry rather than creating a new one.
ctx.read_vars.insert(name_sym);
ctx.mark_consumed(&name_str);
} else {
ctx.record_var_location(&name_str, line, col_start, line_end, col_end);
}
}
ExprKind::Array(elements) => {
let has_non_array = ty.contains(|a| matches!(a, Atomic::TFalse | Atomic::TNull));
let has_array = ty.contains(|a| {
matches!(
a,
Atomic::TArray { .. }
| Atomic::TList { .. }
| Atomic::TNonEmptyArray { .. }
| Atomic::TNonEmptyList { .. }
| Atomic::TKeyedArray { .. }
)
});
if has_non_array && has_array {
self.emit(
IssueKind::PossiblyInvalidArrayOffset {
expected: "array".to_string(),
actual: format!("{ty}"),
},
Severity::Warning,
span,
);
}
let value_ty: Type = ty
.types
.iter()
.find_map(|a| match a {
Atomic::TArray { value, .. }
| Atomic::TList { value }
| Atomic::TNonEmptyArray { value, .. }
| Atomic::TNonEmptyList { value } => Some(*value.clone()),
_ => None,
})
.unwrap_or_else(Type::mixed);
for elem in elements.iter() {
self.assign_to_target(&elem.value, value_ty.clone(), ctx, span);
}
}
ExprKind::PropertyAccess(pa) => {
let obj_ty = self.analyze(&pa.object, ctx);
let prop_name_opt = extract_string_from_expr(&pa.property);
if prop_name_opt.is_none() {
self.analyze(&pa.property, ctx);
}
if let Some(prop_name) = prop_name_opt {
for atomic in &obj_ty.types {
if let Atomic::TNamedObject { fqcn, .. } = atomic {
let db = self.db;
let prop_def = crate::db::find_property_in_chain(
db,
crate::db::Fqcn::new(db, *fqcn),
&prop_name,
)
.map(|(_, p)| p);
// Emit DeprecatedProperty if the property is deprecated
if let Some(ref p) = prop_def {
if let Some(msg) = &p.deprecated {
self.emit(
IssueKind::DeprecatedProperty {
class: fqcn.to_string(),
property: prop_name.clone(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
span,
);
}
}
let prop_info: Option<(bool, Option<Type>)> =
prop_def.map(|p| (p.is_readonly, p.ty.as_deref().cloned()));
if let Some((is_readonly, prop_ty)) = prop_info {
if is_readonly && !ctx.inside_constructor {
self.emit(
IssueKind::ReadonlyPropertyAssignment {
class: fqcn.to_string(),
property: prop_name.clone(),
},
Severity::Error,
span,
);
}
if let Some(prop_ty) = &prop_ty {
if !prop_ty.is_mixed() && !ty.is_mixed() {
// Collect all template param names in scope: class-level
// (from the receiver's class) and method-level.
let class_tp_names: FxHashSet<mir_types::Name> =
crate::db::class_template_params(
self.db,
fqcn.as_ref(),
)
.map(|tps| {
tps.iter()
.map(|tp| {
mir_types::Name::from(tp.name.as_ref())
})
.collect()
})
.unwrap_or_default();
// Skip the check if prop_ty or ty references any
// unresolvable template param (class-level or
// method-level). Inside a generic class, $this carries
// no concrete type args, so class templates in prop_ty
// can't be resolved, and method templates in ty are
// likewise unknown.
let skip = type_refs_any_template(prop_ty, &class_tp_names)
|| type_refs_any_template(&ty, &class_tp_names)
|| type_refs_any_template(
&ty,
&ctx.template_param_names,
);
if !skip
&& !property_assign_compatible(&ty, prop_ty, self.db)
{
self.emit(
IssueKind::InvalidPropertyAssignment {
property: prop_name.clone(),
expected: format!("{prop_ty}"),
actual: format!("{ty}"),
},
Severity::Warning,
span,
);
}
}
}
}
}
}
}
}
ExprKind::StaticPropertyAccess(_) => {}
ExprKind::ArrayAccess(aa) => {
// Collect the full index chain from outermost to innermost.
// For `$arr[$a][$b] = $val`, this gives [type($b), type($a)].
// None means push notation (`[]`), which produces TList rather than TArray.
// The base variable's key is the innermost (last in vec), and
// intermediate indices are used to wrap the value type.
let outer_key: Option<Type> = aa.index.as_ref().map(|idx| self.analyze(idx, ctx));
let mut key_chain: Vec<Option<Type>> = vec![outer_key];
let mut base: &Expr = &aa.array;
loop {
match &base.kind {
ExprKind::Variable(name) => {
let name_str = name.trim_start_matches('$');
// Base key: innermost index in the chain (closest to $arr).
let base_key_opt = key_chain.last().unwrap().clone();
let base_key = base_key_opt.unwrap_or_else(Type::mixed);
// Wrap the assigned value with intermediate keys (outermost first).
// For single-level ($arr[$k] = $v): no wrapping, value stays as-is.
// None entries ([] push) produce TList instead of TArray.
let mut wrapped_value = ty.clone();
for k_opt in key_chain[..key_chain.len() - 1].iter().rev() {
wrapped_value = match k_opt {
None => Type::single(Atomic::TList {
value: Box::new(wrapped_value),
}),
Some(k) => Type::single(Atomic::TArray {
key: Box::new(k.clone()),
value: Box::new(wrapped_value),
}),
};
}
if !ctx.var_is_defined(name_str) {
let name_sym = mir_types::Name::from(name_str);
let init_ty = match &key_chain.last().unwrap() {
None => Type::single(Atomic::TList {
value: Box::new(wrapped_value),
}),
Some(_) => Type::single(Atomic::TArray {
key: Box::new(base_key),
value: Box::new(wrapped_value),
}),
};
std::sync::Arc::make_mut(&mut ctx.vars)
.insert(name_sym, std::sync::Arc::new(init_ty));
std::sync::Arc::make_mut(&mut ctx.assigned_vars).insert(name_sym);
let (line, col_start) = self.offset_to_line_col(base.span.start);
let (line_end, col_end) = self.offset_to_line_col(base.span.end);
ctx.record_var_location(
name_str, line, col_start, line_end, col_end,
);
} else {
let current = ctx.get_var(name_str);
// Check if assigning to array offset of a non-array scalar
if !current.is_mixed()
&& !current.types.is_empty()
&& current.types.iter().all(|a| {
matches!(
a,
Atomic::TInt
| Atomic::TLiteralInt(_)
| Atomic::TIntRange { .. }
| Atomic::TPositiveInt
| Atomic::TFloat
| Atomic::TLiteralFloat(_, _)
| Atomic::TBool
| Atomic::TTrue
| Atomic::TFalse
)
})
{
self.emit(
IssueKind::InvalidArrayAssignment {
ty: current.to_string(),
},
Severity::Error,
span,
);
}
let updated = match &key_chain.last().unwrap() {
None => widen_array_as_list(¤t, &wrapped_value),
Some(_) => widen_array_with_value_and_key(
¤t,
&wrapped_value,
&base_key,
),
};
ctx.set_var(name_str, updated);
}
break;
}
ExprKind::ArrayAccess(inner) => {
let inner_key: Option<Type> =
inner.index.as_ref().map(|idx| self.analyze(idx, ctx));
key_chain.push(inner_key);
base = &inner.array;
}
_ => break,
}
}
}
ExprKind::VariableVariable(inner) => {
if let Some(var_name) = extract_simple_var(inner) {
ctx.read_vars
.insert(mir_types::Name::from(var_name.as_str()));
ctx.mark_consumed(&var_name);
let var_ty = ctx.get_var(&var_name);
for atomic in &var_ty.types {
if let Atomic::TLiteralString(accessed_var_name) = atomic {
ctx.set_var(accessed_var_name.as_ref(), ty.clone());
let (line, col_start) = self.offset_to_line_col(target.span.start);
let (line_end, col_end) = self.offset_to_line_col(target.span.end);
ctx.record_var_location(
accessed_var_name,
line,
col_start,
line_end,
col_end,
);
}
}
}
}
_ => {}
}
}
}