forked from PHPantom-dev/phpantom_lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheloquent_string.rs
More file actions
620 lines (568 loc) · 19.9 KB
/
Copy patheloquent_string.rs
File metadata and controls
620 lines (568 loc) · 19.9 KB
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
//! Eloquent relation dot-notation and column name string completion.
//!
//! Detects when the cursor is inside a string argument to an Eloquent
//! method that accepts relationship names (with dot-notation for nested
//! eager loads) or column/attribute names, and offers appropriate
//! completions.
//!
//! # Relation string completion
//!
//! Methods like `with()`, `load()`, `has()`, `whereHas()` etc. accept
//! relationship method names as string arguments. Dot-notation chains
//! traverse nested relationships: `'mother.sister.son'`.
//!
//! # Column name string completion
//!
//! Methods like `where()`, `orderBy()`, `select()`, `pluck()` etc.
//! accept column/attribute names as string arguments.
use std::sync::Arc;
use tower_lsp::lsp_types::*;
use crate::Backend;
use crate::php_type::PhpType;
use crate::types::{ClassInfo, FileContext};
use crate::util::position_to_offset;
use crate::virtual_members::laravel::{
ELOQUENT_BUILDER_FQN, classify_relationship_typed, extends_eloquent_model,
resolve_relation_chain,
};
/// Relationship-building method names on the Model base class.
/// These return relationship types but are not actual relationship
/// declarations — they are the factory methods used *inside*
/// relationship methods (e.g. `return $this->hasMany(...)`).
const RELATIONSHIP_BUILDER_METHODS: &[&str] = &[
"hasOne",
"hasMany",
"belongsTo",
"belongsToMany",
"morphOne",
"morphMany",
"morphTo",
"morphToMany",
"morphedByMany",
"hasManyThrough",
"hasOneThrough",
];
/// Methods whose first string argument is a relation name (supports dot-notation).
const RELATION_METHODS: &[&str] = &[
"with",
"without",
"load",
"loadMissing",
"loadCount",
"loadMorph",
"has",
"orHas",
"doesntHave",
"orDoesntHave",
"whereHas",
"orWhereHas",
"withWhereHas",
"whereDoesntHave",
"orWhereDoesntHave",
"withCount",
"withSum",
"withAvg",
"withMin",
"withMax",
"withExists",
];
/// Methods whose first string argument is a column/attribute name.
const COLUMN_METHODS: &[&str] = &[
"where",
"orWhere",
"whereIn",
"whereNotIn",
"whereBetween",
"whereNotBetween",
"whereNull",
"whereNotNull",
"orderBy",
"orderByDesc",
"groupBy",
"having",
"select",
"addSelect",
"pluck",
"value",
"increment",
"decrement",
"latest",
"oldest",
];
/// The kind of string argument the cursor is inside.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EloquentStringKind {
/// A relation name (supports dot-notation).
Relation,
/// A column/attribute name.
Column,
}
/// Context extracted when the cursor is inside an Eloquent string argument.
#[derive(Debug)]
pub(crate) struct EloquentStringContext {
/// The kind of string completion needed.
kind: EloquentStringKind,
/// The text the user has typed so far inside the string (e.g. `"mother.si"`).
pub partial: String,
/// The quote character used.
#[allow(dead_code)]
pub quote_char: char,
/// The subject text before the method call (e.g. `"User"`, `"$user"`, `"$query"`).
pub subject: String,
/// Whether this is a static call (`::`) vs instance call (`->`).
pub is_static: bool,
/// Byte offset where the string content starts (after the opening quote).
#[allow(dead_code)]
pub string_content_start: usize,
}
/// Try to detect an Eloquent string context at the given cursor position.
///
/// Returns `None` if the cursor is not inside a string argument to a
/// recognized Eloquent method.
pub(crate) fn detect_eloquent_string_context(
content: &str,
position: Position,
) -> Option<EloquentStringContext> {
let cursor_offset = position_to_offset(content, position) as usize;
let bytes = content.as_bytes();
if cursor_offset == 0 || cursor_offset > bytes.len() {
return None;
}
// Find the opening quote before the cursor.
let mut quote_pos = None;
let mut quote_char = '\'';
let mut i = cursor_offset;
while i > 0 {
i -= 1;
let ch = bytes[i];
if ch == b'\'' || ch == b'"' {
// Make sure this isn't an escaped quote.
let mut backslashes = 0;
let mut j = i;
while j > 0 && bytes[j - 1] == b'\\' {
backslashes += 1;
j -= 1;
}
if backslashes % 2 == 0 {
quote_pos = Some(i);
quote_char = ch as char;
break;
}
}
// Stop at newlines — strings don't span lines in PHP (except heredoc).
if ch == b'\n' {
return None;
}
}
let quote_pos = quote_pos?;
let string_content_start = quote_pos + 1;
// The partial text typed so far.
let partial = content[string_content_start..cursor_offset].to_string();
// Scan backwards from the quote to find the method call pattern.
// We expect: `subject->method(` or `subject::method(` possibly with
// additional arguments before us (e.g. inside an array `['posts', '`).
let before_quote = &content[..quote_pos];
let trimmed = before_quote.trim_end();
// The character before the string could be `(`, `,`, or `[` (for array args).
let last_char = trimmed.as_bytes().last().copied()?;
if last_char != b'(' && last_char != b',' && last_char != b'[' {
return None;
}
// Find the opening paren of the method call.
let paren_pos = find_matching_open_paren(trimmed)?;
let before_paren = content[..paren_pos].trim_end();
// Extract the method name.
let (method_name, before_method) = extract_identifier_backwards(before_paren)?;
// Determine the kind based on method name.
let kind = if RELATION_METHODS.contains(&method_name.as_str()) {
EloquentStringKind::Relation
} else if COLUMN_METHODS.contains(&method_name.as_str()) {
EloquentStringKind::Column
} else {
return None;
};
// Extract the access operator and subject.
let before_method_trimmed = before_method.trim_end();
let (is_static, before_op) = if let Some(stripped) = before_method_trimmed.strip_suffix("::") {
(true, stripped)
} else if let Some(stripped) = before_method_trimmed.strip_suffix("?->") {
(false, stripped)
} else if let Some(stripped) = before_method_trimmed.strip_suffix("->") {
(false, stripped)
} else {
return None;
};
// Extract subject (class name or variable).
let subject = extract_subject_backwards(before_op.trim_end())?;
Some(EloquentStringContext {
kind,
partial,
quote_char,
subject,
is_static,
string_content_start,
})
}
/// Find the opening paren for the method call, scanning backwards.
/// Handles the case where we might be past a comma (second+ argument).
fn find_matching_open_paren(text: &str) -> Option<usize> {
let bytes = text.as_bytes();
let mut depth = 0i32;
let mut i = bytes.len();
while i > 0 {
i -= 1;
match bytes[i] {
b')' | b']' => depth += 1,
b'(' => {
if depth == 0 {
return Some(i);
}
depth -= 1;
}
b'[' => {
if depth == 0 {
// We hit an array bracket — keep scanning for the paren.
continue;
}
depth -= 1;
}
b'\n' => {
// Allow multi-line, but limit scan depth.
// Count newlines; bail after 5 lines.
}
_ => {}
}
}
None
}
/// Extract an identifier (method name) scanning backwards from the end of `text`.
/// Returns (identifier, text_before_identifier).
fn extract_identifier_backwards(text: &str) -> Option<(String, &str)> {
let trimmed = text.trim_end();
let bytes = trimmed.as_bytes();
let mut end = bytes.len();
// Walk backwards while we have valid identifier chars.
while end > 0 && (bytes[end - 1].is_ascii_alphanumeric() || bytes[end - 1] == b'_') {
end -= 1;
}
if end == bytes.len() {
return None; // no identifier found
}
let ident = &trimmed[end..];
if ident.is_empty() {
return None;
}
Some((ident.to_string(), &trimmed[..end]))
}
/// Extract a subject (class name or $variable) scanning backwards.
fn extract_subject_backwards(text: &str) -> Option<String> {
let trimmed = text.trim_end();
let bytes = trimmed.as_bytes();
if bytes.is_empty() {
return None;
}
let mut end = bytes.len();
// Walk backwards collecting identifier chars and backslashes (for FQNs).
while end > 0
&& (bytes[end - 1].is_ascii_alphanumeric()
|| bytes[end - 1] == b'_'
|| bytes[end - 1] == b'\\'
|| bytes[end - 1] == b'$')
{
end -= 1;
}
let subject = &trimmed[end..];
if subject.is_empty() {
return None;
}
Some(subject.to_string())
}
impl Backend {
/// Try Eloquent relation/column string completion.
///
/// Returns `Some(CompletionResponse)` when the cursor is inside a string
/// argument to a recognized Eloquent method and we can resolve the model.
pub(crate) fn try_eloquent_string_completion(
&self,
content: &str,
position: Position,
ctx: &FileContext,
) -> Option<CompletionResponse> {
let es_ctx = detect_eloquent_string_context(content, position)?;
// Resolve the model class.
let class_loader = self.class_loader(ctx);
let model_class = self.resolve_eloquent_model_from_subject(
&es_ctx.subject,
es_ctx.is_static,
content,
position,
ctx,
&class_loader,
)?;
// Verify it's actually an Eloquent model.
if !extends_eloquent_model(&model_class, &class_loader) {
return None;
}
let items = match es_ctx.kind {
EloquentStringKind::Relation => {
self.build_relation_completions(&model_class, &es_ctx, &class_loader)
}
EloquentStringKind::Column => self.build_column_completions(&model_class, &es_ctx),
};
if items.is_empty() {
None
} else {
Some(CompletionResponse::Array(items))
}
}
/// Resolve the model class from the subject of the method call.
fn resolve_eloquent_model_from_subject(
&self,
subject: &str,
is_static: bool,
content: &str,
position: Position,
ctx: &FileContext,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Option<Arc<ClassInfo>> {
if is_static {
// Static call: `User::with(...)` — subject is the class name.
let fqn = self.resolve_class_name_to_fqn(subject, ctx)?;
class_loader(&fqn)
} else if subject == "$this" || subject == "static" || subject == "self" {
// Inside the model class itself.
let cursor_offset = position_to_offset(content, position);
let current_class = crate::util::find_class_at_offset(&ctx.classes, cursor_offset)?;
Some(Arc::new(current_class.clone()))
} else if subject.starts_with('$') {
// Variable — resolve its type. Use a simplified approach:
// look for the resolved type in the class hierarchy.
// For now, try to resolve via the forward walker.
let cursor_offset = position_to_offset(content, position);
let default_class = ClassInfo::default();
let current_class = crate::util::find_class_at_offset(&ctx.classes, cursor_offset)
.unwrap_or(&default_class);
let results = crate::completion::variable::resolution::resolve_variable_types(
subject,
current_class,
&ctx.classes,
content,
cursor_offset,
class_loader,
crate::completion::resolver::Loaders::default(),
);
for rt in &results {
if let Some(model_fqn) = extract_model_from_builder_type(&rt.type_string)
&& let Some(cls) = class_loader(&model_fqn)
{
return Some(cls);
}
if let Some(base) = rt.type_string.base_name()
&& let Some(cls) = class_loader(base)
&& extends_eloquent_model(&cls, class_loader)
{
return Some(cls);
}
}
None
} else {
let fqn = self.resolve_class_name_to_fqn(subject, ctx)?;
class_loader(&fqn)
}
}
/// Resolve a short/relative class name to FQN using use statements.
fn resolve_class_name_to_fqn(&self, name: &str, ctx: &FileContext) -> Option<String> {
let clean = name.trim_start_matches('\\');
// Check use map.
if let Some(fqn) = ctx.use_map.get(clean) {
return Some(fqn.clone());
}
// If it looks like a FQN already.
if clean.contains('\\') {
return Some(clean.to_string());
}
// Try prepending the file namespace.
if let Some(ref ns) = ctx.namespace {
let fqn = format!("{}\\{}", ns, clean);
if self.find_or_load_class(&fqn).is_some() {
return Some(fqn);
}
}
// Try bare name.
if self.find_or_load_class(clean).is_some() {
return Some(clean.to_string());
}
None
}
/// Build completion items for relation names on the given model.
fn build_relation_completions(
&self,
model: &ClassInfo,
es_ctx: &EloquentStringContext,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Vec<CompletionItem> {
let partial = &es_ctx.partial;
// If there's a dot, resolve the chain up to the last dot.
let (prefix, current_partial, current_model) = if let Some(dot_pos) = partial.rfind('.') {
let chain_prefix = &partial[..dot_pos];
let after_dot = &partial[dot_pos + 1..];
// Resolve the chain to get the model at the end.
let Some(resolved_fqn) =
resolve_relation_chain(model, chain_prefix, class_loader, None)
else {
return Vec::new();
};
let Some(resolved_model) = class_loader(&resolved_fqn) else {
return Vec::new();
};
// Resolve with inheritance for full method list.
let resolved = crate::virtual_members::resolve_class_fully_maybe_cached(
&resolved_model,
class_loader,
None,
);
(
format!("{}.", chain_prefix),
after_dot.to_string(),
resolved,
)
} else {
// No dot — complete on the root model.
let resolved =
crate::virtual_members::resolve_class_fully_maybe_cached(model, class_loader, None);
(String::new(), partial.clone(), resolved)
};
// Collect relationship methods from the current model.
let mut items = Vec::new();
for method in current_model.methods.iter() {
// Only public methods.
if method.visibility != crate::types::Visibility::Public {
continue;
}
// Check if the return type is a relationship.
let Some(ref return_type) = method.return_type else {
continue;
};
if classify_relationship_typed(return_type).is_none() {
continue;
}
let method_name = method.name.to_string();
// Skip relationship-builder methods (hasOne, hasMany, etc.)
// which are factory methods, not actual relationship declarations.
if RELATIONSHIP_BUILDER_METHODS.contains(&method_name.as_str()) {
continue;
}
// Filter by partial.
if !current_partial.is_empty()
&& !method_name
.to_lowercase()
.starts_with(¤t_partial.to_lowercase())
{
continue;
}
let insert_text = method_name.clone();
let detail = return_type.to_string();
items.push(CompletionItem {
label: format!("{}{}", prefix, &method_name),
kind: Some(CompletionItemKind::FIELD),
detail: Some(detail),
insert_text: Some(insert_text),
filter_text: Some(method_name),
..Default::default()
});
}
items
}
/// Build completion items for column/attribute names on the given model.
fn build_column_completions(
&self,
model: &ClassInfo,
es_ctx: &EloquentStringContext,
) -> Vec<CompletionItem> {
let partial = &es_ctx.partial;
let columns = collect_model_columns(model);
let mut items = Vec::new();
for col in &columns {
if !partial.is_empty() && !col.to_lowercase().starts_with(&partial.to_lowercase()) {
continue;
}
items.push(CompletionItem {
label: col.clone(),
kind: Some(CompletionItemKind::FIELD),
detail: Some("column".to_string()),
insert_text: Some(col.clone()),
..Default::default()
});
}
items
}
}
/// Extract the model FQN from a `Builder<Model>` type.
fn extract_model_from_builder_type(ty: &PhpType) -> Option<String> {
if let PhpType::Generic(base, args) = ty
&& (base.ends_with("Builder") || base == ELOQUENT_BUILDER_FQN)
&& let Some(first) = args.first()
{
return first.base_name().map(|s| s.to_string());
}
None
}
/// Collect all column/attribute names from a model class.
///
/// Uses the same sources as `where_property::collect_column_names` but
/// we call it here to avoid coupling to internal module functions.
fn collect_model_columns(class: &ClassInfo) -> Vec<String> {
use std::collections::HashSet;
let mut seen = HashSet::new();
let mut columns = Vec::new();
let mut push = |name: &str| {
if seen.insert(name.to_string()) {
columns.push(name.to_string());
}
};
if let Some(laravel) = class.laravel() {
for (col, _) in &laravel.casts_definitions {
push(col);
}
for col in &laravel.dates_definitions {
push(col);
}
for (col, _) in &laravel.attributes_definitions {
push(col);
}
for col in &laravel.column_names {
push(col);
}
// Timestamps.
let timestamps_enabled = laravel.timestamps.unwrap_or(true);
if timestamps_enabled {
let created_col = match &laravel.created_at_name {
Some(Some(name)) => Some(name.as_str()),
Some(None) => None,
None => Some("created_at"),
};
let updated_col = match &laravel.updated_at_name {
Some(Some(name)) => Some(name.as_str()),
Some(None) => None,
None => Some("updated_at"),
};
for col in [created_col, updated_col].into_iter().flatten() {
push(col);
}
}
}
// Properties on the class (including virtual @property tags).
for prop in class.properties.iter() {
push(&prop.name);
}
// @property tags from docblock.
if let Some(ref doc_text) = class.class_docblock {
for (name, _type_str) in crate::docblock::extract_property_tags(doc_text) {
push(&name);
}
}
columns
}
#[cfg(test)]
#[path = "eloquent_string_tests.rs"]
mod tests;