From 2d0bcffde8a1ba041324b0500ec3e0e697699f83 Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Tue, 10 Nov 2026 18:08:48 +0100 Subject: [PATCH 1/6] Navigate Drupal form and render callbacks In a Drupal project, a callback written as a string in a form or render array's callback keys (#submit, #validate, #process, #pre_render, the #ajax callback and the others Drupal calls) now leads to the method or function it names: go-to-definition, hover, find references and rename. '::method' names a method of the form it is written in, or of the trait; 'Class::method' and a class name joined to '::method' name a method of that class, the class name in the string read as fully qualified; a name without a colon names a global function. The playground's acme module has a form with a callback of each shape. Assisted-by: claude-code/claude-opus-5-5 --- examples/drupal/README.md | 8 + examples/drupal/assertions.php | 25 + .../web/modules/custom/acme/acme.module | 13 + .../custom/acme/src/Form/GreetingForm.php | 102 ++ src/call_hierarchy.rs | 10 +- src/code_actions/replace_fqcn.rs | 1 + src/definition/member/mod.rs | 3 + src/definition/resolve.rs | 1 + src/definition/type_definition.rs | 6 + src/diagnostics/deprecated.rs | 11 + src/diagnostics/unknown_functions.rs | 1 + src/drupal/forms.rs | 43 + src/drupal/mod.rs | 1 + src/highlight/mod.rs | 63 +- src/hover/member.rs | 4 + src/references/dispatch.rs | 4 +- src/references/receivers.rs | 3 + src/rename/class/siblings.rs | 1 + src/rename/prepare.rs | 29 +- src/rename/validate.rs | 28 +- src/resolution/functions.rs | 8 + src/semantic_export/calls.rs | 3 + src/semantic_export/occurrences.rs | 7 +- src/semantic_tokens.rs | 15 +- src/symbol_map/docblock.rs | 2 + src/symbol_map/extraction/class_like.rs | 2 + src/symbol_map/extraction/drupal.rs | 342 +++++- .../extraction/expressions/assignment.rs | 1 + .../extraction/expressions/calls.rs | 2 + src/symbol_map/extraction/expressions/mod.rs | 2 + src/symbol_map/extraction/mod.rs | 4 + src/symbol_map/extraction/phpunit.rs | 1 + src/symbol_map/span.rs | 14 + tests/integration/drupal_callbacks.rs | 992 ++++++++++++++++++ tests/integration/main.rs | 1 + 35 files changed, 1736 insertions(+), 17 deletions(-) create mode 100644 examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php create mode 100644 src/drupal/forms.rs create mode 100644 tests/integration/drupal_callbacks.rs diff --git a/examples/drupal/README.md b/examples/drupal/README.md index a58191439..f4785d362 100644 --- a/examples/drupal/README.md +++ b/examples/drupal/README.md @@ -154,6 +154,14 @@ Run `composer install` here first. Composer puts core and contrib into `Details` class. Complete a name inside `'#type' => ''` or `$build['more']['#type'] = ''`; core's elements are offered too. A name no element class declares is reported. +- Form and render callbacks navigate to the method or function they name. + In `web/modules/custom/acme/src/Form/GreetingForm.php`, go to the + definition of `validateName` in `'::validateName'`, which lands on the + form's own method, hover `trimName` in `static::class . '::trimName'`, or + go to the definition of `addHint` in + `'Drupal\acme\Form\GreetingForm::addHint'` and of + `'acme_greeting_form_submit'`, a function of `acme.module`. Find the + references of a callback method, or rename it, and the strings follow. - Plugin IDs navigate to the plugin class that declares them, for every plugin type a plugin manager declares, core's and contributed modules' included. In `block()` in diff --git a/examples/drupal/assertions.php b/examples/drupal/assertions.php index 39fdf41ae..b89443512 100644 --- a/examples/drupal/assertions.php +++ b/examples/drupal/assertions.php @@ -17,6 +17,7 @@ use Drupal\acme\Controller\NoteController; use Drupal\acme\Element\GreetingCard; use Drupal\acme\Entity\Note; +use Drupal\acme\Form\GreetingForm; use Drupal\acme\Form\SettingsForm; use Drupal\acme\Greeter; use Drupal\acme\Hook\AcmeHooks; @@ -53,6 +54,8 @@ use Drupal\Core\Extension\InfoParser; use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\ConfigTarget; +use Drupal\Core\Form\FormInterface; +use Drupal\Core\Form\FormState; use Drupal\Core\Hook\Attribute\Hook; use Drupal\Core\Language\LanguageManager; use Drupal\Core\Session\AccountInterface; @@ -433,6 +436,28 @@ protected function getDefaultLanguageValues() check("core's Twig extension declares attach_library()", str_contains((string) file_get_contents("$web/core/lib/Drupal/Core/Template/TwigExtension.php"), "new TwigFunction('attach_library'")); check("core's ThemeManager collects the #attached a preprocess function sets", str_contains((string) file_get_contents("$web/core/lib/Drupal/Core/Theme/ThemeManager.php"), "foreach (['#attached', '#cache'] as \$key)")); +// ─── Callbacks ────────────────────────────────────────────────────────────── + +// Drupal rewrites a '::method' callback as a call on the form object, and +// calls every other one as written. Each one GreetingForm declares names a +// public method or function, so each one is callable. +$greetingForm = new GreetingForm(); +$greetingFormState = (new FormState())->setFormObject($greetingForm); +$greetingBuild = $greetingForm->buildForm([], $greetingFormState); +$greetingCallbacks = [ + ...$greetingBuild['#validate'], + $greetingBuild['name']['#value_callback'], + $greetingBuild['name']['#ajax']['callback'], + ...$greetingBuild['#after_build'], + ...$greetingBuild['actions']['submit']['#submit'], +]; +check('GreetingForm declares a callback of each shape', $greetingCallbacks === ['::validateName', GreetingForm::class . '::trimName', '::refreshGreeting', 'Drupal\acme\Form\GreetingForm::addHint', '::submitForm', 'acme_greeting_form_submit']); +foreach ($greetingCallbacks as $callback) { + check("Drupal can call GreetingForm's $callback", is_callable($greetingFormState->prepareCallback($callback))); +} +check("FormState rewrites '::validateName' as a call on the form object", $greetingFormState->prepareCallback('::validateName') === [$greetingForm, 'validateName']); +check('GreetingForm is a form', $greetingForm instanceof FormInterface); + // ─── Summary ──────────────────────────────────────────────────────────────── echo "\n"; diff --git a/examples/drupal/web/modules/custom/acme/acme.module b/examples/drupal/web/modules/custom/acme/acme.module index 60dbb8440..3376c5905 100644 --- a/examples/drupal/web/modules/custom/acme/acme.module +++ b/examples/drupal/web/modules/custom/acme/acme.module @@ -8,6 +8,7 @@ declare(strict_types=1); use Drupal\acme\Greeter; +use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Routing\RouteMatchInterface; /** @@ -80,3 +81,15 @@ function acme_request_age(): int return $clock->secondsSinceRequest(); } + +/** + * Submit handler of GreetingForm, which names it in its `#submit` list. + * + * @param array $form + */ +function acme_greeting_form_submit(array &$form, FormStateInterface $form_state): void +{ + // Try: find the references of acme_greeting_form_submit(), which list + // the string in GreetingForm::buildForm(). + \Drupal::logger('acme')->info('Greeted @name.', ['@name' => $form_state->getValue('name')]); +} diff --git a/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php b/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php new file mode 100644 index 000000000..d310db17b --- /dev/null +++ b/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php @@ -0,0 +1,102 @@ + $form + * @return array + */ + public function buildForm(array $form, FormStateInterface $form_state): array + { + // Try: go to the definition of validateName after the `::`, which + // lands on the method of this form: Drupal calls a '::method' + // callback on the form object. Find the references of + // validateName(), or rename it, and the string follows. + $form['#validate'][] = '::validateName'; + $form['name'] = [ + '#type' => 'textfield', + '#title' => 'Name', + // Try: hover trimName. A class name joined to '::method' reads + // as one 'Class::method'. + '#value_callback' => static::class . '::trimName', + // Try: go to the definition of refreshGreeting, the callback + // the `#ajax` array holds. + '#ajax' => ['callback' => '::refreshGreeting'], + ]; + // Try: go to the definition of addHint. The class name in a + // 'Class::method' string is fully qualified, whatever the file + // imports. + $form['#after_build'] = ['Drupal\acme\Form\GreetingForm::addHint']; + $form['actions']['submit'] = [ + '#type' => 'submit', + '#value' => 'Greet', + // Try: go to the definition of acme_greeting_form_submit, a + // function of acme.module. A function name in a callback string + // is global, whatever namespace the file is in. + '#submit' => ['::submitForm', 'acme_greeting_form_submit'], + ]; + + return $form; + } + + /** + * @param array $form + */ + public function validateName(array &$form, FormStateInterface $form_state): void + { + if (trim((string) $form_state->getValue('name')) === '') { + $form_state->setErrorByName('name', 'Enter a name.'); + } + } + + /** + * @param array $element + */ + public static function trimName(array &$element, mixed $input, FormStateInterface $form_state): mixed + { + return is_string($input) ? trim($input) : null; + } + + /** + * @param array $form + * @return array + */ + public function refreshGreeting(array &$form, FormStateInterface $form_state): array + { + return $form['name']; + } + + /** + * @param array $form + * @return array + */ + public static function addHint(array $form, FormStateInterface $form_state): array + { + $form['name']['#description'] = 'The name the greeting uses.'; + + return $form; + } + + /** + * @param array $form + */ + public function submitForm(array &$form, FormStateInterface $form_state): void + { + $form_state->setRedirect('acme.greeting', ['name' => $form_state->getValue('name')]); + } +} diff --git a/src/call_hierarchy.rs b/src/call_hierarchy.rs index 9dec19951..f18893482 100644 --- a/src/call_hierarchy.rs +++ b/src/call_hierarchy.rs @@ -20,7 +20,7 @@ use tower_lsp_server::gen_lsp_types::{ }; use crate::Backend; -use crate::symbol_map::{ClassRefContext, SymbolKind, SymbolMap, SymbolSpan}; +use crate::symbol_map::{ClassRefContext, DocblockMemberRef, SymbolKind, SymbolMap, SymbolSpan}; use crate::text_position::{byte_range_to_lsp_range, offset_to_position, position_to_offset}; use crate::types::{ClassInfo, FunctionInfo, MethodInfo}; @@ -371,6 +371,8 @@ impl Backend { /// Reading a same-named property (`$this->leaf`), naming the method in a /// `@see` tag, and calling it (`$this->leaf()`) all reference the same member, /// so both directions filter down to the occurrences that actually invoke it. +/// A Drupal form callback's `'::method'` is a call Drupal makes on the form, +/// which the resolution of its subject keeps to forms and traits. fn is_call_site(span: &SymbolSpan) -> bool { match &span.kind { SymbolKind::FunctionCall { @@ -382,7 +384,11 @@ fn is_call_site(span: &SymbolSpan) -> bool { is_method_call, docblock_ref, .. - } => *is_method_call && !docblock_ref.is_reference(), + } => { + *is_method_call + && (!docblock_ref.is_reference() + || *docblock_ref == DocblockMemberRef::FormCallback) + } SymbolKind::ClassReference { context, .. } => matches!(context, ClassRefContext::New), _ => false, } diff --git a/src/code_actions/replace_fqcn.rs b/src/code_actions/replace_fqcn.rs index 32eede49d..d0a446428 100644 --- a/src/code_actions/replace_fqcn.rs +++ b/src/code_actions/replace_fqcn.rs @@ -100,6 +100,7 @@ fn symbol_name_and_kind(span: &SymbolSpan) -> Option<(&str, ImportKind)> { name, is_definition: false, is_docblock_reference: false, + is_callback: false, } => Some((name, ImportKind::Function)), SymbolKind::ConstantReference { name, diff --git a/src/definition/member/mod.rs b/src/definition/member/mod.rs index 7e28b4aa7..4e9b60d58 100644 --- a/src/definition/member/mod.rs +++ b/src/definition/member/mod.rs @@ -257,6 +257,9 @@ impl Backend { crate::symbol_map::DocblockMemberRef::YiiProperty { form_model: true } => { candidates = crate::yii::forms::form_model_classes(candidates, class_loader); } + crate::symbol_map::DocblockMemberRef::FormCallback => { + candidates = crate::drupal::forms::form_callback_classes(candidates, class_loader); + } _ => {} } let first = candidates.first()?; diff --git a/src/definition/resolve.rs b/src/definition/resolve.rs index 02d6ef51f..1c4ba0f3b 100644 --- a/src/definition/resolve.rs +++ b/src/definition/resolve.rs @@ -435,6 +435,7 @@ impl Backend { name, is_definition, is_docblock_reference, + .. } => { // The cursor is on the function's own name at its // declaration, so there is nothing to jump to: resolving diff --git a/src/definition/type_definition.rs b/src/definition/type_definition.rs index a5f0486ad..042e75e38 100644 --- a/src/definition/type_definition.rs +++ b/src/definition/type_definition.rs @@ -128,6 +128,12 @@ impl Backend { &resolved_class_loader, ); } + DocblockMemberRef::FormCallback => { + candidates = crate::drupal::forms::form_callback_classes( + candidates, + &resolved_class_loader, + ); + } _ => {} } diff --git a/src/diagnostics/deprecated.rs b/src/diagnostics/deprecated.rs index 1e4a79c27..90c6b0251 100644 --- a/src/diagnostics/deprecated.rs +++ b/src/diagnostics/deprecated.rs @@ -249,6 +249,17 @@ impl Backend { { continue; } + // A form callback's `'::method'` names a method only of a + // form. + if *docblock_ref == crate::symbol_map::DocblockMemberRef::FormCallback + && crate::drupal::forms::form_callback_classes( + vec![Arc::clone(&base_class)], + resolved_class_loader, + ) + .is_empty() + { + continue; + } // An attribute's named-argument label uses a property // only when the constructor promotes the parameter. diff --git a/src/diagnostics/unknown_functions.rs b/src/diagnostics/unknown_functions.rs index 7bc4bf8bc..7b5c68479 100644 --- a/src/diagnostics/unknown_functions.rs +++ b/src/diagnostics/unknown_functions.rs @@ -124,6 +124,7 @@ impl Backend { name, is_definition: false, is_docblock_reference, + is_callback: false, } => (name, *is_docblock_reference), _ => continue, }; diff --git a/src/drupal/forms.rs b/src/drupal/forms.rs new file mode 100644 index 000000000..94c354a38 --- /dev/null +++ b/src/drupal/forms.rs @@ -0,0 +1,43 @@ +//! Drupal forms: the classes a form callback's `'::method'` can name a +//! method of. +//! +//! Drupal rewrites `'::method'` as `[$form_object, 'method']` before it +//! calls it, so the string names a method of the form being built, which +//! is the class it is written in only when that class is a form. Written +//! in a trait, it names a method of whichever form uses the trait, which +//! the trait stands for. Anywhere else it names a method of a form the +//! code does not know. + +use std::sync::Arc; + +use crate::class_lookup::{Fqn, ResolvedClassLoader, is_subtype_of}; +use crate::types::{ClassInfo, ClassLikeKind}; + +/// The interface every Drupal form implements. +const FORM_INTERFACE: &str = "Drupal\\Core\\Form\\FormInterface"; + +/// Whether `'::method'` written in `class` names a method of it. +fn names_own_method(class: &ClassInfo, class_loader: &ResolvedClassLoader<'_>) -> bool { + class.kind == ClassLikeKind::Trait || is_subtype_of(class, FORM_INTERFACE, class_loader) +} + +/// The classes among `classes`, those `'::method'` is written in, that it +/// names a method of. +pub(crate) fn form_callback_classes( + mut classes: Vec>, + class_loader: &ResolvedClassLoader<'_>, +) -> Vec> { + classes.retain(|class| names_own_method(class, class_loader)); + classes +} + +/// [`form_callback_classes`] for classes known by name. +pub(crate) fn form_callback_class_names( + mut fqns: Vec, + class_loader: &ResolvedClassLoader<'_>, +) -> Vec { + fqns.retain(|fqn| { + class_loader(Fqn::new(fqn)).is_some_and(|class| names_own_method(&class, class_loader)) + }); + fqns +} diff --git a/src/drupal/mod.rs b/src/drupal/mod.rs index d6b539b33..2c110a1a8 100644 --- a/src/drupal/mod.rs +++ b/src/drupal/mod.rs @@ -20,6 +20,7 @@ pub(crate) mod computed_hooks; pub(crate) mod config; pub(crate) mod config_keys; pub(crate) mod elements; +pub(crate) mod forms; pub(crate) mod hooks; pub(crate) mod libraries; pub(crate) mod links; diff --git a/src/highlight/mod.rs b/src/highlight/mod.rs index 1d0617f39..f32964b41 100644 --- a/src/highlight/mod.rs +++ b/src/highlight/mod.rs @@ -90,8 +90,12 @@ impl Backend { name, MemberRefKind::of_declaration(*is_static, *is_method), ), - SymbolKind::FunctionCall { name, .. } => { - self.highlight_function(symbol_map, content, name) + SymbolKind::FunctionCall { + name, + is_definition, + .. + } => { + self.highlight_function(uri, symbol_map, content, name, *is_definition, span.start) } SymbolKind::ConstantReference { name, .. } => { self.highlight_constant(symbol_map, content, name) @@ -245,18 +249,69 @@ impl Backend { } /// Highlight all occurrences of a standalone function name. + /// + /// A Drupal callback string names its function fully qualified + /// (`\foo`), where a call or a declaration spells its short name, so a + /// callback and another occurrence name the same function when the FQNs + /// they resolve to match. fn highlight_function( &self, + uri: &str, symbol_map: &SymbolMap, content: &str, target_name: &str, + target_is_definition: bool, + target_offset: u32, ) -> Vec { + let ctx = std::cell::OnceCell::new(); + let ctx = || ctx.get_or_init(|| self.file_context(uri)); + let target_fqn = std::cell::OnceCell::new(); collect_highlights(symbol_map, content, |span| { - matches!(&span.kind, SymbolKind::FunctionCall { name, .. } if name == target_name) - .then_some(DocumentHighlightKind::Read) + let SymbolKind::FunctionCall { + name, + is_definition, + .. + } = &span.kind + else { + return None; + }; + let same = if name.starts_with('\\') || target_name.starts_with('\\') { + let target_fqn = target_fqn.get_or_init(|| { + self.function_span_fqn(ctx(), target_name, target_is_definition, target_offset) + }); + self.function_span_fqn(ctx(), name, *is_definition, span.start) + .eq_ignore_ascii_case(target_fqn) + } else { + name == target_name + }; + same.then_some(DocumentHighlightKind::Read) }) } + /// The FQN of the function a function span named `name` at `offset` + /// names: a declaration's in its namespace, a call's by PHP's rule, + /// falling back to the global function when the namespace declares + /// none, and a name with a leading `\` as it is. + fn function_span_fqn( + &self, + ctx: &FileContext, + name: &str, + is_definition: bool, + offset: u32, + ) -> String { + if let Some(fqn) = name.strip_prefix('\\') { + return fqn.to_string(); + } + if is_definition { + return build_fqn(name, ctx.namespace_at(offset).as_deref()); + } + let fqn = ctx.resolve_name_at(name, offset); + if !name.contains('\\') && fqn != name && !self.has_indexed_function(&fqn) { + return name.to_string(); + } + fqn + } + /// Highlight all occurrences of a constant name. fn highlight_constant( &self, diff --git a/src/hover/member.rs b/src/hover/member.rs index aff168c29..20e415291 100644 --- a/src/hover/member.rs +++ b/src/hover/member.rs @@ -402,6 +402,10 @@ impl Backend { candidates = crate::yii::forms::form_model_classes(candidates, &resolved_class_loader); } + DocblockMemberRef::FormCallback => { + candidates = + crate::drupal::forms::form_callback_classes(candidates, &resolved_class_loader); + } _ => {} } diff --git a/src/references/dispatch.rs b/src/references/dispatch.rs index bc74b6ff0..189db585b 100644 --- a/src/references/dispatch.rs +++ b/src/references/dispatch.rs @@ -276,7 +276,8 @@ impl Backend { // attribute's named-argument label whose parameter the // constructor does not promote names no property, and a // field helper's string given something other than a form - // model names none either. + // model names none either, nor does a form callback's + // `'::method'` outside a form. if hierarchy.is_none() && matches!( docblock_ref, @@ -285,6 +286,7 @@ impl Backend { | DocblockMemberRef::EntityField | DocblockMemberRef::YiiAttribute | DocblockMemberRef::YiiProperty { form_model: true } + | DocblockMemberRef::FormCallback ) { return Vec::new(); diff --git a/src/references/receivers.rs b/src/references/receivers.rs index 51cdb02c9..0fac3dbc1 100644 --- a/src/references/receivers.rs +++ b/src/references/receivers.rs @@ -184,6 +184,9 @@ impl Backend { DocblockMemberRef::YiiProperty { form_model: true } => { crate::yii::forms::form_model_class_names(fqns, &class_loader) } + DocblockMemberRef::FormCallback => { + crate::drupal::forms::form_callback_class_names(fqns, &class_loader) + } _ => fqns, } } diff --git a/src/rename/class/siblings.rs b/src/rename/class/siblings.rs index 563694aa4..16f7add8e 100644 --- a/src/rename/class/siblings.rs +++ b/src/rename/class/siblings.rs @@ -98,6 +98,7 @@ impl Backend { name, is_definition: false, is_docblock_reference: false, + is_callback: false, } => (SiblingKind::Function, name.as_str()), SymbolKind::ConstantReference { name, diff --git a/src/rename/prepare.rs b/src/rename/prepare.rs index c9ad1f813..d2d77a768 100644 --- a/src/rename/prepare.rs +++ b/src/rename/prepare.rs @@ -122,7 +122,10 @@ impl Backend { // The range below is built from this span's byte offsets, and the // editor shows it as the text about to be replaced. A map that // predates the buffer would put it over unrelated code. - if !self.rename_map_matches(uri, content) || !span_spells_its_name(content, &span) { + if !self.rename_map_matches(uri, content) + || !span_spells_its_name(content, &span) + || self.is_callback_naming_no_function(&span.kind) + { return None; } @@ -267,7 +270,10 @@ impl Backend { // from this span. If the map it came from predates the buffer the // whole response is nonsense, so drop it rather than rename the // wrong symbol. - if !self.rename_map_matches(uri, content) || !span_spells_its_name(content, &span) { + if !self.rename_map_matches(uri, content) + || !span_spells_its_name(content, &span) + || self.is_callback_naming_no_function(&span.kind) + { return Ok(None); } @@ -697,6 +703,19 @@ impl Backend { Some((target_uri, target_content, target_position)) } + /// Whether `kind` is a Drupal callback string that names no function, + /// but an invokable class or service. + fn is_callback_naming_no_function(&self, kind: &SymbolKind) -> bool { + matches!( + kind, + SymbolKind::FunctionCall { + name, + is_callback: true, + .. + } if !self.callback_names_function(name) + ) + } + /// Extract the renameable symbol name and its source range. /// /// Returns `None` for symbols that cannot be renamed. @@ -723,7 +742,11 @@ impl Backend { SymbolKind::ClassDeclaration { name } => Some((name.to_string(), range)), SymbolKind::MemberAccess { member_name, .. } => Some((member_name.to_string(), range)), SymbolKind::MemberDeclaration { name, .. } => Some((name.to_string(), range)), - SymbolKind::FunctionCall { name, .. } => Some((name.to_string(), range)), + // A callback string's function name keeps the leading `\` that + // makes it global; the name to edit goes without it. + SymbolKind::FunctionCall { name, .. } => { + Some((crate::util::strip_fqn_prefix(name).to_string(), range)) + } SymbolKind::ConstantReference { name, .. } => Some((name.to_string(), range)), SymbolKind::NamespaceDeclaration { name } => Some((name.to_string(), range)), SymbolKind::LaravelMacroString { name } => Some((name.clone(), range)), diff --git a/src/rename/validate.rs b/src/rename/validate.rs index e0ad31c48..da0b2cf98 100644 --- a/src/rename/validate.rs +++ b/src/rename/validate.rs @@ -43,6 +43,9 @@ enum Expected<'a> { /// text at a reference site is not predictable from the symbol name. /// All we can require is that the range still covers one whole name. Name, + /// [`Expected::Name`] for a function, which a Drupal callback string in + /// PHP may also spell with escaped backslashes (`'Drupal\\\\acme\\\\fn'`). + FunctionName, /// The full key, or one of its segments. A Laravel string key is /// written out in full at its use sites (`config('app.name')`) and as /// a single segment at its declaration (`'name' => ...`). @@ -92,7 +95,13 @@ impl Backend { if !self.rename_map_matches(uri, content) { return false; } - if !range_matches(content, location.range, &expected) + // A YAML or XML document spells escaped backslashes for its own + // quoting, which no edit here is planned for. + let expected = match expected { + Expected::FunctionName if self.is_resource_uri(uri) => &Expected::Name, + _ => &expected, + }; + if !range_matches(content, location.range, expected) && !magic_expected .as_ref() .is_some_and(|magic| range_matches(content, location.range, magic)) @@ -129,6 +138,19 @@ pub(super) fn span_spells_its_name(content: &str, span: &SymbolSpan) -> bool { let text = text.strip_prefix('\\').unwrap_or(text); let name = name.strip_prefix('\\').unwrap_or(name); text.eq_ignore_ascii_case(name) + || matches!( + span.kind, + SymbolKind::FunctionCall { + is_callback: true, + .. + } + ) && unescaped_name(text).is_some_and(|text| text.eq_ignore_ascii_case(name)) +} + +/// The name a string literal spells as `text` with escaped backslashes +/// (`'Drupal\\acme\\fn'`), as a callback names a namespaced function. +fn unescaped_name(text: &str) -> Option { + text.contains("\\\\").then(|| text.replace("\\\\", "\\")) } /// The name a span's own source text should spell. @@ -171,6 +193,7 @@ fn expected_text(kind: &SymbolKind) -> Expected<'_> { } SymbolKind::LaravelMacroString { name } => Expected::Exact(name), SymbolKind::StringKey { key, .. } => Expected::Key(key), + SymbolKind::FunctionCall { .. } => Expected::FunctionName, _ => Expected::Name, } } @@ -207,6 +230,9 @@ fn range_matches(content: &str, range: Range, expected: &Expected) -> bool { token.eq_ignore_ascii_case(name) } Expected::Name => is_name_token(text), + Expected::FunctionName => { + is_name_token(text) || unescaped_name(text).is_some_and(|text| is_name_token(&text)) + } Expected::Key(key) => { // A view name is stored in its canonical dotted spelling, so // the source may still read `partials/card` for `partials.card`. diff --git a/src/resolution/functions.rs b/src/resolution/functions.rs index 1181a6e3b..dc4835c3e 100644 --- a/src/resolution/functions.rs +++ b/src/resolution/functions.rs @@ -328,6 +328,14 @@ impl Backend { .is_some() } + /// Whether a function named `name` exists, read as the fully qualified + /// name a Drupal callback string spells, its leading `\\` included. A + /// callback that names none names an invokable class or service. + pub(crate) fn callback_names_function(&self, name: &str) -> bool { + let fqn = name.trim_start_matches('\\'); + self.has_indexed_function(fqn) || self.find_or_load_declared_function(&[fqn]).is_some() + } + /// Whether discovery or full parsing has seen this exact class FQN. /// /// Laravel's optional root facade aliases are used only when no real diff --git a/src/semantic_export/calls.rs b/src/semantic_export/calls.rs index 4619e78a6..9efe14e33 100644 --- a/src/semantic_export/calls.rs +++ b/src/semantic_export/calls.rs @@ -249,6 +249,9 @@ fn resolve_member_owner( if docblock_ref == (DocblockMemberRef::YiiProperty { form_model: true }) { names = crate::yii::forms::form_model_class_names(names, &class_loader); } + if docblock_ref == DocblockMemberRef::FormCallback { + names = crate::drupal::forms::form_callback_class_names(names, &class_loader); + } (names.len() == 1).then(|| names.swap_remove(0)) } diff --git a/src/semantic_export/occurrences.rs b/src/semantic_export/occurrences.rs index 074fcd415..a066e1949 100644 --- a/src/semantic_export/occurrences.rs +++ b/src/semantic_export/occurrences.rs @@ -121,6 +121,7 @@ pub(super) fn export_span( name, is_definition, is_docblock_reference, + is_callback, } => { let loader = backend.function_loader_with( context.resolved_names.as_deref(), @@ -137,7 +138,7 @@ pub(super) fn export_span( resolved_symbol: symbol, is_definition: *is_definition, }); - if !is_definition && function.is_none() && !is_docblock_reference { + if !is_definition && function.is_none() && !is_docblock_reference && !is_callback { output.diagnostics.push(ExportDiagnostic { kind: ExportDiagnosticKind::UnresolvedFunction, range, @@ -197,7 +198,8 @@ pub(super) fn export_span( // and so is a key of an array passed to something other than a // repository, or a name passed to the `get()` of something // other than a record, or a field helper's string given - // something other than a form model. + // something other than a form model, or a form callback's + // `'::method'` outside a form. if target.is_none() && matches!( docblock_ref, @@ -205,6 +207,7 @@ pub(super) fn export_span( | DocblockMemberRef::EntityField | DocblockMemberRef::YiiAttribute | DocblockMemberRef::YiiProperty { form_model: true } + | DocblockMemberRef::FormCallback ) { return; diff --git a/src/semantic_tokens.rs b/src/semantic_tokens.rs index b3273564f..f795543ff 100644 --- a/src/semantic_tokens.rs +++ b/src/semantic_tokens.rs @@ -336,7 +336,8 @@ impl Backend { // a repository call's field name is an array key first, // as a record's attribute name is a string first. A // property a Yii form field or map names is a string or - // a key first, too. + // a key first, too, and so is a form callback's + // `'::method'`, which names a method only of a form. if matches!( docblock_ref, crate::symbol_map::DocblockMemberRef::MockedMethod @@ -344,6 +345,7 @@ impl Backend { | crate::symbol_map::DocblockMemberRef::EntityField | crate::symbol_map::DocblockMemberRef::YiiAttribute | crate::symbol_map::DocblockMemberRef::YiiProperty { .. } + | crate::symbol_map::DocblockMemberRef::FormCallback ) { continue; } @@ -412,8 +414,15 @@ impl Backend { (tt, mods) } - SymbolKind::FunctionCall { is_definition, .. } => { - if mode == SemanticTokensMode::Contextual { + SymbolKind::FunctionCall { + name, + is_definition, + is_callback, + .. + } => { + if mode == SemanticTokensMode::Contextual + || (*is_callback && !self.callback_names_function(name)) + { continue; } let mods = if *is_definition { TM_DECLARATION } else { 0 }; diff --git a/src/symbol_map/docblock.rs b/src/symbol_map/docblock.rs index 2310c08f6..eefa7ef01 100644 --- a/src/symbol_map/docblock.rs +++ b/src/symbol_map/docblock.rs @@ -777,6 +777,7 @@ fn emit_covers_reference( // for a *global* function, not shorthand for a member of the test // class, so the enclosing class must not be consulted for it. is_docblock_reference: false, + is_callback: false, }, }; @@ -1508,6 +1509,7 @@ fn emit_see_reference(reference: &str, file_offset: u32, spans: &mut Vec(func: &'a Function<'a>, ctx: &mut Extrac name, is_definition: true, is_docblock_reference: false, + is_callback: false, }, }); emit_drupal_hook_doc_span(func, ctx); @@ -1120,6 +1121,7 @@ pub(super) fn extract_from_use_statement(use_stmt: &Use<'_>, spans: &mut Vec SymbolKind::ConstantReference { name, diff --git a/src/symbol_map/extraction/drupal.rs b/src/symbol_map/extraction/drupal.rs index 76afd8c6d..96fb8d8a1 100644 --- a/src/symbol_map/extraction/drupal.rs +++ b/src/symbol_map/extraction/drupal.rs @@ -1,6 +1,7 @@ //! The entity types a Drupal entity class declares, by attribute or by the //! annotation older code uses, the route names Drupal's static and -//! constructor calls read, and the libraries a render array attaches (see +//! constructor calls read, the libraries a render array attaches, and the +//! methods and functions a form or render array's callbacks name (see //! [`crate::drupal`]). use super::*; @@ -2767,6 +2768,266 @@ fn push_library(expression: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { } } +// ─── Callbacks ────────────────────────────────────────────────────────────── + +/// The keys of a form or render array that hold a list of callbacks. +const CALLBACK_LIST_KEYS: [&str; 8] = [ + "#after_build", + "#element_validate", + "#entity_builders", + "#post_render", + "#pre_render", + "#process", + "#submit", + "#validate", +]; + +/// The keys that hold one callback. +const CALLBACK_KEYS: [&str; 2] = ["#access_callback", "#value_callback"]; + +/// The key whose list holds its callback first, then the arguments. +const LAZY_BUILDER: &str = "#lazy_builder"; + +/// The key whose array holds its callback under [`AJAX_CALLBACK`]. +const AJAX: &str = "#ajax"; +const AJAX_CALLBACK: &str = "callback"; + +/// Whether `content` quotes a key Drupal reads a callback under, found in +/// one pass over its `#`s. +pub(in crate::symbol_map::extraction) fn has_callback_key(content: &str) -> bool { + let bytes = content.as_bytes(); + memchr::memchr_iter(b'#', bytes).any(|at| { + at > 0 && matches!(bytes[at - 1], b'\'' | b'"') && { + let rest = &bytes[at..]; + CALLBACK_LIST_KEYS + .iter() + .chain(&CALLBACK_KEYS) + .chain([&LAZY_BUILDER, &AJAX]) + .any(|key| { + rest.starts_with(key.as_bytes()) + && matches!(rest.get(key.len()), Some(b'\'' | b'"')) + }) + } + }) +} + +/// Record the callbacks an array literal's entries name under the keys +/// Drupal reads callbacks from. +pub(in crate::symbol_map::extraction) fn emit_drupal_callback_spans( + elements: &TokenSeparatedSequence<'_, ArrayElement<'_>>, + ctx: &mut ExtractionCtx<'_>, +) { + if !ctx.drupal_callback_keys { + return; + } + for element in elements.iter() { + if let ArrayElement::KeyValue(entry) = element + && let Some((key, _, _)) = resolved_string_literal(entry.key, ctx.content) + { + push_keyed_callbacks(key, entry.value, ctx); + } + } +} + +/// Record the callbacks an assignment into a form or render array names: +/// `$form['#submit'][] = …`, a whole list or callback under its key, and +/// `$form['x']['#ajax']['callback'] = …`. +pub(in crate::symbol_map::extraction) fn emit_drupal_callback_assignment( + assign: &Assignment<'_>, + ctx: &mut ExtractionCtx<'_>, +) { + if !ctx.drupal_callback_keys || !assign.operator.is_assign() { + return; + } + match assign.lhs { + Expression::ArrayAppend(append) => { + if let Expression::ArrayAccess(access) = append.array + && let Some((key, _, _)) = resolved_string_literal(access.index, ctx.content) + && CALLBACK_LIST_KEYS.contains(&key) + { + push_callback(assign.rhs, ctx); + } + } + Expression::ArrayAccess(access) => { + let Some((key, _, _)) = resolved_string_literal(access.index, ctx.content) else { + return; + }; + if key == AJAX_CALLBACK { + if accesses_keys(access.array, &[AJAX], ctx.content) { + push_callback(assign.rhs, ctx); + } + } else { + push_keyed_callbacks(key, assign.rhs, ctx); + } + } + _ => {} + } +} + +/// Record the callbacks `value`, written under `key`, names. +fn push_keyed_callbacks(key: &str, value: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { + if CALLBACK_KEYS.contains(&key) { + push_callback(value, ctx); + return; + } + let lazy_builder = key == LAZY_BUILDER; + if !lazy_builder && key != AJAX && !CALLBACK_LIST_KEYS.contains(&key) { + return; + } + let Some(entries) = crate::parser::array_literal_elements(value) else { + return; + }; + for entry in entries.iter() { + match entry { + ArrayElement::Value(item) if key != AJAX => push_callback(item.value, ctx), + ArrayElement::KeyValue(entry) + if key == AJAX && is_literal_key(entry.key, AJAX_CALLBACK, ctx.content) => + { + push_callback(entry.value, ctx); + } + _ => {} + } + if lazy_builder { + return; + } + } +} + +/// Record what one callback names: a method of the form for `'::method'`, +/// a method of the class for `'Class::method'` or a class name joined to +/// `'::method'`, and a function for a name without a colon. An array +/// callable is read wherever it is written, and `'service:method'` names a +/// service rather than a class. +fn push_callback(callback: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { + if let Expression::Binary(binary) = callback + && binary.operator.is_concatenation() + { + push_joined_callback(binary.lhs, binary.rhs, ctx); + return; + } + let Some((value, start, end)) = resolved_string_literal(callback, ctx.content) else { + return; + }; + if let Some((class, method)) = value.rsplit_once("::") { + if !is_identifier(method) || !ctx.content[..end].ends_with(method) { + return; + } + let method_start = (end - method.len()) as u32; + if class.is_empty() { + push_callback_method( + SubjectText::owned("$this".to_string()), + false, + DocblockMemberRef::FormCallback, + method, + method_start, + ctx, + ); + return; + } + // A class name in a string is a runtime name, which is fully + // qualified whether or not it says so. + let class = class.strip_prefix('\\').unwrap_or(class); + if is_qualified_name(class) { + push_callback_method( + SubjectText::owned(format!("\\{class}")), + true, + DocblockMemberRef::No, + method, + method_start, + ctx, + ); + } + } else if !value.contains(':') { + let name = value.strip_prefix('\\').unwrap_or(value); + if is_qualified_name(name) { + ctx.spans.push(SymbolSpan { + start: start as u32, + end: end as u32, + kind: SymbolKind::FunctionCall { + name: crate::atom::atom(&format!("\\{name}")), + is_definition: false, + is_docblock_reference: false, + is_callback: true, + }, + }); + } + } +} + +/// Record the method `X::class . '::method'`, `static::class . '::method'`, +/// `self::class . '::method'` or `__CLASS__ . '::method'` names. The +/// `'::method'` half is never read on its own. +fn push_joined_callback( + class: &Expression<'_>, + method: &Expression<'_>, + ctx: &mut ExtractionCtx<'_>, +) { + let Some((value, _, end)) = resolved_string_literal(method, ctx.content) else { + return; + }; + let Some(name) = value + .strip_prefix("::") + .filter(|name| is_identifier(name) && ctx.content[..end].ends_with(name)) + else { + return; + }; + let subject = match class { + Expression::Access(Access::ClassConstant(fetch)) + if crate::parser::is_class_fetch(fetch) => + { + let span = fetch.class.span(); + SubjectText::new( + expr_to_subject_text(fetch.class), + span.start.offset, + span.end.offset, + ctx.content, + ) + } + Expression::MagicConstant(MagicConstant::Class(_)) => { + SubjectText::owned("self".to_string()) + } + _ => return, + }; + push_callback_method( + subject, + true, + DocblockMemberRef::No, + name, + (end - name.len()) as u32, + ctx, + ); +} + +/// Record the method `name`, at `start`, of `subject` that a callback +/// names, read like the method of an array callable. +fn push_callback_method( + subject: SubjectText, + is_static: bool, + docblock_ref: DocblockMemberRef, + name: &str, + start: u32, + ctx: &mut ExtractionCtx<'_>, +) { + ctx.spans.push(SymbolSpan { + start, + end: start + name.len() as u32, + kind: SymbolKind::MemberAccess { + subject_text: subject, + member_name: crate::atom::atom(name), + is_static, + is_method_call: true, + docblock_ref, + is_array_callable: true, + is_nullsafe: false, + }, + }); +} + +/// Whether `name` is a class or function name, its namespace included. +fn is_qualified_name(name: &str) -> bool { + name.split('\\').all(is_identifier) +} + /// The code `program` runs only when a module is installed (see /// [`ModuleGuard`]): the branch an `if` takes when a `moduleExists('m')` /// it requires holds, and the rest of a block after an `if` that leaves @@ -4079,4 +4340,83 @@ $build['more']['#theme'] = 'item_list'; ); assert!(map_of(php, false).twig_contexts.is_empty()); } + + #[test] + fn a_callback_key_is_one_a_quote_opens_and_closes() { + for (php, expected) in [ + ("$form['#submit'][] = 'x';", true), + ("['#ajax' => []]", true), + ("[\"#lazy_builder\" => []]", true), + ("$form['#value_callback'] = 'x';", true), + ("$form['#submitted'] = 1;", false), + ("# submit, '#type' => 'x'", false), + ("#[Hook('form_alter')]", false), + ] { + assert_eq!(has_callback_key(php), expected, "{php}"); + } + } + + /// The text each callback span of `php` covers, with what it names: + /// `subject::method` for a method and `function name` for a function. + fn callbacks(php: &str, drupal: bool) -> Vec<(String, String)> { + let map = map_of(php, drupal); + let source = map.source(php).expect("the map's own source"); + map.spans + .iter() + .filter_map(|span| { + let named = match &span.kind { + SymbolKind::MemberAccess { + subject_text, + member_name, + is_array_callable: true, + .. + } => format!("{}::{member_name}", subject_text.as_str(source)), + SymbolKind::FunctionCall { + name, + is_callback: true, + .. + } => format!("function {name}"), + _ => return None, + }; + Some(( + php[span.start as usize..span.end as usize].to_string(), + named, + )) + }) + .collect() + } + + #[test] + fn each_callback_shape_names_its_method_or_function() { + let php = r#" ['callback' => __CLASS__ . '::refresh'], 'callback' => '::nothing']; +$form['#lazy_builder'] = ['Acme\Builder::build', ['::argument']]; +$form['#value_callback'] = self::class . '::value'; +$form['#markup'] = '::nothing'; +$joined = static::class . '::nothing'; +"#; + let expected = [ + ("save", "$this::save"), + ("check", "\\Acme\\Helper::check"), + ("check", "Helper::check"), + ("acme_check", "function \\acme_check"), + ("refresh", "static::refresh"), + ("refresh", "self::refresh"), + ("build", "\\Acme\\Builder::build"), + ("value", "self::value"), + ]; + let found = callbacks(php, true); + assert_eq!( + found + .iter() + .map(|(text, named)| (text.as_str(), named.as_str())) + .collect::>(), + expected + ); + assert_eq!(callbacks(php, false), Vec::new()); + } } diff --git a/src/symbol_map/extraction/expressions/assignment.rs b/src/symbol_map/extraction/expressions/assignment.rs index 94b7e55f9..53f0ac059 100644 --- a/src/symbol_map/extraction/expressions/assignment.rs +++ b/src/symbol_map/extraction/expressions/assignment.rs @@ -18,6 +18,7 @@ pub(super) fn extract_assignment_expr<'a>( emit_drupal_render_element_assignment(assign, ctx); emit_drupal_render_array_assignment(assign, ctx); emit_drupal_attached_assignment_spans(assign, ctx); + emit_drupal_callback_assignment(assign, ctx); // The definition only becomes visible *after* the entire // assignment expression — the RHS still sees the previous diff --git a/src/symbol_map/extraction/expressions/calls.rs b/src/symbol_map/extraction/expressions/calls.rs index a258acab3..6538031fd 100644 --- a/src/symbol_map/extraction/expressions/calls.rs +++ b/src/symbol_map/extraction/expressions/calls.rs @@ -364,6 +364,7 @@ fn extract_function_call<'a>( name: crate::atom::atom(name_clean), is_definition: false, is_docblock_reference: false, + is_callback: false, }, }); // `@yield`/`@section`/`@stack`/`@push` and their @@ -729,6 +730,7 @@ pub(super) fn extract_partial_application_expr<'a>( name: crate::atom::atom(name_clean), is_definition: false, is_docblock_reference: false, + is_callback: false, }, }); } diff --git a/src/symbol_map/extraction/expressions/mod.rs b/src/symbol_map/extraction/expressions/mod.rs index c41f2c8e8..4dec6d88c 100644 --- a/src/symbol_map/extraction/expressions/mod.rs +++ b/src/symbol_map/extraction/expressions/mod.rs @@ -257,6 +257,7 @@ pub(super) fn extract_from_expression<'a>( emit_drupal_render_element_reads(&array.elements, ctx); emit_drupal_render_array_spans(&array.elements, ctx); emit_drupal_attached_array_spans(&array.elements, ctx); + emit_drupal_callback_spans(&array.elements, ctx); emit_yii_definition_spans(&array.elements, array.span().start.offset, ctx); extract_from_array_elements(&array.elements, ctx, scope_start); } @@ -266,6 +267,7 @@ pub(super) fn extract_from_expression<'a>( emit_drupal_render_element_reads(&array.elements, ctx); emit_drupal_render_array_spans(&array.elements, ctx); emit_drupal_attached_array_spans(&array.elements, ctx); + emit_drupal_callback_spans(&array.elements, ctx); emit_yii_definition_spans(&array.elements, array.span().start.offset, ctx); extract_from_array_elements(&array.elements, ctx, scope_start); } diff --git a/src/symbol_map/extraction/mod.rs b/src/symbol_map/extraction/mod.rs index 3dce6caa2..6255178bf 100644 --- a/src/symbol_map/extraction/mod.rs +++ b/src/symbol_map/extraction/mod.rs @@ -123,6 +123,9 @@ struct ExtractionCtx<'a> { /// Likewise for `#theme`, the key a render array names its theme hook /// under, which `#theme_wrappers` starts with. drupal_theme_keys: bool, + /// Likewise for the keys a form or render array holds its callbacks + /// under, such as `#submit` and `#pre_render`. + drupal_callback_keys: bool, drupal_route_patterns: Vec, drupal_route_aliases: Vec, /// The Drupal routes the file's `#[Route]` attributes declare. @@ -632,6 +635,7 @@ fn extract_symbol_map_inner( drupal_plugins: Vec::new(), drupal_type_keys: drupal && memchr::memmem::find(content.as_bytes(), b"#type").is_some(), drupal_theme_keys: drupal && memchr::memmem::find(content.as_bytes(), b"#theme").is_some(), + drupal_callback_keys: drupal && drupal::has_callback_key(content), drupal_route_patterns: Vec::new(), drupal_route_aliases: Vec::new(), drupal_routes: Vec::new(), diff --git a/src/symbol_map/extraction/phpunit.rs b/src/symbol_map/extraction/phpunit.rs index 7781d406d..22cc38842 100644 --- a/src/symbol_map/extraction/phpunit.rs +++ b/src/symbol_map/extraction/phpunit.rs @@ -131,6 +131,7 @@ pub(super) fn try_emit_phpunit_attribute_spans( name: crate::atom::atom(name.trim_start_matches('\\')), is_definition: false, is_docblock_reference: false, + is_callback: false, }, }); } diff --git a/src/symbol_map/span.rs b/src/symbol_map/span.rs index a3b601d64..38782e4c4 100644 --- a/src/symbol_map/span.rs +++ b/src/symbol_map/span.rs @@ -229,6 +229,16 @@ pub(crate) enum DocblockMemberRef { /// its classes (see [`crate::yii::forms::form_model_classes`]), and /// drops the span otherwise. YiiProperty { form_model: bool }, + + /// The method a Drupal form callback's `'::method'` names, with `$this` + /// as the subject. + /// + /// Drupal calls it on the form being built, which is the class the + /// string is written in only when that class is a form or a trait, so a + /// consumer that resolves the subject keeps only those (see + /// [`crate::drupal::forms::form_callback_classes`]), and drops the span + /// otherwise. + FormCallback, } impl DocblockMemberRef { @@ -506,6 +516,10 @@ pub(crate) enum SymbolKind { /// reading applies to it, so `retag_as_covers_target` clears this; /// see [`DocblockMemberRef`] for the member equivalent. is_docblock_reference: bool, + /// `true` when this span is a function name a Drupal form or render + /// callback key holds as a string, which PHP reads as a global name + /// (the span's `name` carries a leading `\`) rather than a call. + is_callback: bool, }, /// `self`, `static`, `parent`, or `$this` in a navigable context. diff --git a/tests/integration/drupal_callbacks.rs b/tests/integration/drupal_callbacks.rs new file mode 100644 index 000000000..831d9ddad --- /dev/null +++ b/tests/integration/drupal_callbacks.rs @@ -0,0 +1,992 @@ +//! Drupal's form and render callbacks: the methods and functions a callback +//! key of a form or render array names, as `'::method'`, `'Class::method'`, +//! a class name joined to `'::method'`, or a function name. + +use crate::common::{apply_edits, edits_for_uri, hover_text_at, prepare_rename, rename}; +use crate::drupal_services::{ + definitions_at, position_in, references_at, uri_for, workspace, workspace_in, +}; +use tower_lsp_server::gen_lsp_types::*; + +const FORM_INTERFACE_PATH: &str = "web/core/lib/Drupal/Core/Form/FormInterface.php"; + +const FORM_INTERFACE: &str = " [ + '::saveTitle', + 'Helper::shout', + '\Drupal\acme\Helper::whisper', + Helper::class . '::shout', + static::class . '::saveTitle', + 'acme_log_submit', + ], + '#ajax' => ['callback' => '::refresh'], + ]; + $form['title']['#ajax']['callback'] = __CLASS__ . '::refresh'; + $form['#process'] = [self::class . '::checkTitle']; + $form['#lazy_builder'] = ['Drupal\acme\Helper::whisper', []]; + $form['other'] = ['callback' => '::refresh']; + $label = '::refresh'; + return $form; + } + + public static function processTitle(array $element): array { + $element['#process'][] = '::checkTitle'; + return $element; + } + + public function checkTitle(): void {} + + public function saveTitle(): void {} + + public function refresh(): void {} +} +"#; + +/// A caller in another namespace that imports neither `Helper`. +const BUILDER_PATH: &str = "web/modules/custom/acme/src/Render/Builder.php"; + +const BUILDER: &str = r#" ['Helper::shout', 'Drupal\acme\Helper::shout'], + '#post_render' => ['acme_log_submit'], + ]; + } +} +"#; + +/// A hook class, which is no form: `'::validate'` names a method of a form +/// it does not know. +const HOOKS_PATH: &str = "web/modules/custom/acme/src/Hook/AcmeHooks.php"; + +const HOOKS: &str = r#" (phpantom_lsp::Backend, tempfile::TempDir) { + let (backend, dir) = workspace(&[ + (FORM_INTERFACE_PATH, FORM_INTERFACE), + (FORM_BASE_PATH, FORM_BASE), + (HELPER_PATH, HELPER), + (GLOBAL_HELPER_PATH, GLOBAL_HELPER), + (MODULE_PATH, MODULE), + (FORM_FUNCTIONS_PATH, FORM_FUNCTIONS), + (FORM_PATH, FORM), + (BUILDER_PATH, BUILDER), + (HOOKS_PATH, HOOKS), + (TRAIT_PATH, TRAIT), + ]) + .await; + backend.ensure_workspace_indexed(); + (backend, dir) +} + +/// The zero-based line of the first occurrence of `needle` in `content`. +fn line_of(content: &str, needle: &str) -> u32 { + content[..content.find(needle).expect("needle should exist")] + .matches('\n') + .count() as u32 +} + +/// The files and lines the definitions at `inside` bytes into the first +/// occurrence of `needle` in the file `path` point at. +async fn definition_lines( + backend: &phpantom_lsp::Backend, + dir: &tempfile::TempDir, + (path, content): (&str, &str), + needle: &str, + inside: usize, +) -> Vec<(Uri, u32)> { + definitions_at( + backend, + &uri_for(dir, path), + position_in(content, needle, inside), + ) + .await + .into_iter() + .map(|location| (location.uri, location.range.start.line)) + .collect() +} + +#[tokio::test] +async fn each_callback_shape_goes_to_what_it_names() { + let (backend, dir) = site().await; + let form = (FORM_PATH, FORM); + let form_uri = uri_for(&dir, FORM_PATH); + let helper = (uri_for(&dir, HELPER_PATH), line_of(HELPER, "shout")); + let whisper = (uri_for(&dir, HELPER_PATH), line_of(HELPER, "whisper")); + let global_shout = ( + uri_for(&dir, GLOBAL_HELPER_PATH), + line_of(GLOBAL_HELPER, "shout"), + ); + let global_function = (uri_for(&dir, MODULE_PATH), line_of(MODULE, "acme_log")); + let check_title = (form_uri.clone(), line_of(FORM, "function checkTitle")); + let save_title = (form_uri.clone(), line_of(FORM, "function saveTitle")); + let refresh = (form_uri.clone(), line_of(FORM, "function refresh")); + + for (needle, inside, expected) in [ + ("'::checkTitle'", 4, &check_title), + ("'::saveTitle'", 4, &save_title), + ("'::refresh'", 4, &refresh), + // A class name in a callback string is a runtime name: the import + // of `Drupal\acme\Helper` does not apply to it. + ("'Helper::shout'", 10, &global_shout), + ("'\\Drupal\\acme\\Helper::whisper'", 23, &whisper), + // A class name written in code does go through the imports. + ("Helper::class . '::shout'", 20, &helper), + ("static::class . '::saveTitle'", 21, &save_title), + ("__CLASS__ . '::refresh'", 16, &refresh), + ("self::class . '::checkTitle'", 19, &check_title), + ("'Drupal\\acme\\Helper::whisper', []", 22, &whisper), + // A function name in a callback string is a global name, never one + // of the file's namespace. + ("'acme_log_submit'", 3, &global_function), + // `'::checkTitle'` in a static method of the form still names a + // method of the form object. + ("$element['#process'][] = '::checkTitle'", 30, &check_title), + ] { + let found = definition_lines(&backend, &dir, form, needle, inside).await; + assert_eq!(found, vec![expected.clone()], "{needle}"); + } + + let builder = (BUILDER_PATH, BUILDER); + for (needle, inside, expected) in [ + ("'Helper::shout'", 10, &global_shout), + ("'Drupal\\acme\\Helper::shout'", 22, &helper), + ("'acme_log_submit'", 3, &global_function), + ] { + let found = definition_lines(&backend, &dir, builder, needle, inside).await; + assert_eq!(found, vec![expected.clone()], "{needle}"); + } + + let in_trait = (uri_for(&dir, TRAIT_PATH), line_of(TRAIT, "function press")); + for (needle, inside) in [ + ("'::pressButton'", 4), + ("static::class . '::pressButton'", 21), + ] { + let found = definition_lines(&backend, &dir, (TRAIT_PATH, TRAIT), needle, inside).await; + assert_eq!(found, vec![in_trait.clone()], "{needle}"); + } +} + +#[tokio::test] +async fn a_hover_on_a_callback_shows_what_it_names() { + let (backend, dir) = site().await; + let form_uri = uri_for(&dir, FORM_PATH); + for (needle, inside, expected, unexpected) in [ + ("'::saveTitle'", 4, "saveTitle", None), + // Only the global `Helper` declares a static `shout()`. + ("'Helper::shout'", 10, "static function shout", None), + ("static::class . '::saveTitle'", 21, "saveTitle", None), + ( + "'acme_log_submit'", + 3, + "acme_log_submit", + Some("Drupal\\acme\\Form"), + ), + ] { + let position = position_in(FORM, needle, inside); + let hover = hover_text_at(&backend, &form_uri, position.line, position.character) + .await + .unwrap_or_else(|| panic!("no hover on {needle}")); + assert!(hover.contains(expected), "{needle}: {hover}"); + if let Some(unexpected) = unexpected { + assert!(!hover.contains(unexpected), "{needle}: {hover}"); + } + } +} + +/// The references of the name `inside` bytes into `needle` in the file +/// `path`, declarations included. +async fn reference_lines( + backend: &phpantom_lsp::Backend, + dir: &tempfile::TempDir, + (path, content): (&str, &str), + needle: &str, + inside: usize, +) -> Vec<(Uri, u32)> { + references_at( + backend, + &uri_for(dir, path), + position_in(content, needle, inside), + ) + .await +} + +/// A file's path and content. +type File = (&'static str, &'static str); + +/// A place in a file: its path, its content, and the text found there. +type Place = (&'static str, &'static str, &'static str); + +/// `(file, line)` for the first occurrence of each place's text in its +/// file, sorted the way [`references_at`] sorts them. +fn lines(dir: &tempfile::TempDir, places: &[Place]) -> Vec<(Uri, u32)> { + let mut found: Vec<(Uri, u32)> = places + .iter() + .map(|(path, content, needle)| (uri_for(dir, path), line_of(content, needle))) + .collect(); + found.sort(); + found +} + +#[tokio::test] +async fn the_references_of_a_method_or_function_list_the_callbacks_naming_it() { + let (backend, dir) = site().await; + let form = (FORM_PATH, FORM); + let cases: [(File, &str, usize, Vec); 7] = [ + ( + form, + "function saveTitle", + 10, + vec![ + (FORM_PATH, FORM, "function saveTitle"), + (FORM_PATH, FORM, "'::saveTitle'"), + (FORM_PATH, FORM, "static::class . '::saveTitle'"), + ], + ), + ( + form, + "function checkTitle", + 10, + vec![ + (FORM_PATH, FORM, "function checkTitle"), + (FORM_PATH, FORM, "$form['#validate'][] = '::checkTitle'"), + (FORM_PATH, FORM, "self::class . '::checkTitle'"), + (FORM_PATH, FORM, "$element['#process'][] = '::checkTitle'"), + ], + ), + // Neither a bare `callback` key nor a string outside a callback key + // names anything. + ( + form, + "function refresh", + 10, + vec![ + (FORM_PATH, FORM, "function refresh"), + (FORM_PATH, FORM, "'#ajax' => ['callback' => '::refresh']"), + (FORM_PATH, FORM, "__CLASS__ . '::refresh'"), + ], + ), + ( + (HELPER_PATH, HELPER), + "function whisper", + 10, + vec![ + (HELPER_PATH, HELPER, "function whisper"), + (FORM_PATH, FORM, "'\\Drupal\\acme\\Helper::whisper'"), + (FORM_PATH, FORM, "'Drupal\\acme\\Helper::whisper', []"), + ], + ), + ( + (HELPER_PATH, HELPER), + "function shout", + 10, + vec![ + (HELPER_PATH, HELPER, "function shout"), + (FORM_PATH, FORM, "Helper::class . '::shout'"), + (BUILDER_PATH, BUILDER, "'Drupal\\acme\\Helper::shout'"), + ], + ), + ( + (GLOBAL_HELPER_PATH, GLOBAL_HELPER), + "function shout", + 10, + vec![ + (GLOBAL_HELPER_PATH, GLOBAL_HELPER, "function shout"), + (FORM_PATH, FORM, "'Helper::shout'"), + (BUILDER_PATH, BUILDER, "'Helper::shout'"), + ], + ), + ( + (MODULE_PATH, MODULE), + "function acme_log_submit", + 10, + vec![ + (MODULE_PATH, MODULE, "function acme_log_submit"), + (FORM_PATH, FORM, "'acme_log_submit'"), + (BUILDER_PATH, BUILDER, "'acme_log_submit'"), + ], + ), + ]; + for (file, needle, inside, expected) in cases { + let found = reference_lines(&backend, &dir, file, needle, inside).await; + assert_eq!(found, lines(&dir, &expected), "{} {needle}", file.0); + } + + for (file, needle, expected) in [ + ( + (FORM_FUNCTIONS_PATH, FORM_FUNCTIONS), + "function acme_log_submit", + ( + FORM_FUNCTIONS_PATH, + FORM_FUNCTIONS, + "function acme_log_submit", + ), + ), + ( + (HOOKS_PATH, HOOKS), + "function validate", + (HOOKS_PATH, HOOKS, "function validate"), + ), + ] { + let found = reference_lines(&backend, &dir, file, needle, 10).await; + assert_eq!(found, lines(&dir, &[expected]), "{} {needle}", file.0); + } + + let found = reference_lines(&backend, &dir, (TRAIT_PATH, TRAIT), "function press", 10).await; + assert_eq!( + found, + lines( + &dir, + &[ + (TRAIT_PATH, TRAIT, "function press"), + (TRAIT_PATH, TRAIT, "'::pressButton'"), + (TRAIT_PATH, TRAIT, "static::class . '::pressButton'"), + ] + ) + ); +} + +#[tokio::test] +async fn a_callback_outside_a_form_or_a_callback_key_names_nothing() { + let (backend, dir) = site().await; + let found = definition_lines(&backend, &dir, (HOOKS_PATH, HOOKS), "'::validate'", 4).await; + assert_eq!(found, Vec::new()); + let position = position_in(HOOKS, "'::validate'", 4); + let hover = hover_text_at( + &backend, + &uri_for(&dir, HOOKS_PATH), + position.line, + position.character, + ) + .await; + assert_eq!(hover, None); + for needle in [ + "$form['other'] = ['callback' => '::refresh']", + "$label = '::refresh'", + ] { + let inside = needle.find("::refresh").unwrap() + 2; + let found = definition_lines(&backend, &dir, (FORM_PATH, FORM), needle, inside).await; + assert_eq!(found, Vec::new(), "{needle}"); + } +} + +const HIGHLIGHT_PATH: &str = "web/modules/custom/acme/src/Form/highlighted.php"; + +/// A global function and a namespaced function that share a short name, and +/// callbacks that name the global one. +const HIGHLIGHT: &str = r#" = backend + .handle_document_highlight(uri.as_str(), HIGHLIGHT, position) + .unwrap_or_default() + .iter() + .map(|highlight| highlight.range.start.line) + .collect(); + lines.sort(); + lines + }; + let global = line_of(HIGHLIGHT, "function acme_highlight_submit"); + let namespaced = global + 4; + let callbacks = [ + line_of(HIGHLIGHT, "'acme_highlight_submit'"), + line_of(HIGHLIGHT, "'\\acme_highlight_submit'"), + ]; + let call = line_of(HIGHLIGHT, "acme_highlight_submit();"); + for (needle, inside) in [ + ("'acme_highlight_submit'", 3), + ("'\\acme_highlight_submit'", 3), + ] { + assert_eq!( + highlighted(needle, inside), + [global, callbacks[0], callbacks[1]], + "{needle}" + ); + } + let found = highlighted("function acme_highlight_submit", 10); + assert!( + [global, callbacks[0], callbacks[1]] + .iter() + .all(|line| found.contains(line)), + "{found:?}" + ); + // The namespaced function and the call that names it are no callback's. + for needle in [ + "acme_highlight_submit();", + " function acme_highlight_submit(): void {}\n\n function build", + ] { + let inside = needle.find("acme").unwrap() + 2; + let found = highlighted(needle, inside); + assert!(found.contains(&call), "{needle}: {found:?}"); + assert!(found.contains(&namespaced), "{needle}: {found:?}"); + assert!( + !callbacks.iter().any(|line| found.contains(line)), + "{needle}: {found:?}" + ); + } +} + +const ESCAPED_PATH: &str = "web/modules/custom/acme/src/Form/escaped.php"; + +/// Callbacks that spell a namespaced function's name with escaped +/// backslashes, in a single-quoted and a double-quoted string. +const ESCAPED: &str = r#" CallHierarchyItem { + let params = CallHierarchyPrepareParams { + text_document_position_params: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: uri_for(dir, path), + }, + position: position_in(content, needle, inside), + }, + work_done_progress_params: WorkDoneProgressParams::default(), + }; + tower_lsp_server::LanguageServer::prepare_call_hierarchy(backend, params) + .await + .unwrap() + .and_then(|items| items.into_iter().next()) + .unwrap_or_else(|| panic!("no callable at {needle}")) +} + +#[tokio::test] +async fn the_call_hierarchy_counts_a_form_callback_as_a_call() { + let (backend, dir) = site().await; + let form = (FORM_PATH, FORM); + let callback_lines = [ + line_of(FORM, "'::saveTitle'"), + line_of(FORM, "static::class . '::saveTitle'"), + ]; + + let save_title = hierarchy_item(&backend, &dir, form, "function saveTitle", 10).await; + let incoming = tower_lsp_server::LanguageServer::incoming_calls( + &backend, + CallHierarchyIncomingCallsParams { + item: save_title, + work_done_progress_params: WorkDoneProgressParams::default(), + partial_result_params: PartialResultParams::default(), + }, + ) + .await + .unwrap() + .unwrap_or_default(); + let calls: Vec<(String, Vec)> = incoming + .iter() + .map(|call| { + let mut lines: Vec = call.from_ranges.iter().map(|r| r.start.line).collect(); + lines.sort(); + (call.from.name.clone(), lines) + }) + .collect(); + assert_eq!(calls, [("buildForm".to_string(), callback_lines.to_vec())]); + + let build_form = hierarchy_item(&backend, &dir, form, "function buildForm", 10).await; + let outgoing = tower_lsp_server::LanguageServer::outgoing_calls( + &backend, + CallHierarchyOutgoingCallsParams { + item: build_form, + work_done_progress_params: WorkDoneProgressParams::default(), + partial_result_params: PartialResultParams::default(), + }, + ) + .await + .unwrap() + .unwrap_or_default(); + let to_save_title = outgoing + .iter() + .find(|call| call.to.name == "saveTitle") + .expect("a call to saveTitle"); + let mut lines: Vec = to_save_title + .from_ranges + .iter() + .map(|r| r.start.line) + .collect(); + lines.sort(); + assert_eq!(lines, callback_lines); + + // `'::validate'` outside a form names no method of it. + let validate = + hierarchy_item(&backend, &dir, (HOOKS_PATH, HOOKS), "function validate", 10).await; + let incoming = tower_lsp_server::LanguageServer::incoming_calls( + &backend, + CallHierarchyIncomingCallsParams { + item: validate, + work_done_progress_params: WorkDoneProgressParams::default(), + partial_result_params: PartialResultParams::default(), + }, + ) + .await + .unwrap() + .unwrap_or_default(); + assert!(incoming.is_empty(), "{incoming:?}"); +} + +const INVOKED_PATH: &str = "web/modules/custom/acme/src/Form/invoked.php"; + +/// A callback that names an invokable class and one that names a function. +const INVOKED: &str = r#" 0 { + character = 0; + } + line += token.delta_line; + character += token.delta_start; + if token.token_type == 9 { + functions.push(Position::new(line, character)); + } + } + for (needle, named) in [ + ("'Drupal\\acme\\Form\\Invoked'", false), + ("'Drupal\\acme\\Form\\acme_invoked_submit'", true), + ] { + let position = position_in(INVOKED, needle, 1); + assert_eq!( + functions.contains(&position), + named, + "{needle}: {functions:?}" + ); + let renameable = prepare_rename(&backend, &uri, position.line, position.character) + .await + .is_some(); + assert_eq!(renameable, named, "{needle}"); + let edit = rename( + &backend, + &uri, + position.line, + position.character, + "acme_other", + ) + .await; + assert_eq!(edit.is_some(), named, "{needle}"); + } +} + +/// The content of the file `path` once `edit` is applied to it. +fn renamed(edit: &WorkspaceEdit, dir: &tempfile::TempDir, (path, content): (&str, &str)) -> String { + apply_edits(content, &edits_for_uri(edit, &uri_for(dir, path))) +} + +#[tokio::test] +async fn renaming_a_method_or_function_rewrites_the_name_in_its_callbacks() { + let (backend, dir) = site().await; + + let position = position_in(FORM, "function saveTitle", 10); + let edit = rename( + &backend, + &uri_for(&dir, FORM_PATH), + position.line, + position.character, + "storeTitle", + ) + .await + .expect("an edit"); + assert_eq!( + renamed(&edit, &dir, (FORM_PATH, FORM)), + FORM.replace("saveTitle", "storeTitle") + ); + + let position = position_in(HELPER, "function whisper", 10); + let edit = rename( + &backend, + &uri_for(&dir, HELPER_PATH), + position.line, + position.character, + "murmur", + ) + .await + .expect("an edit"); + assert_eq!( + renamed(&edit, &dir, (FORM_PATH, FORM)), + FORM.replace("whisper", "murmur") + ); + + let position = position_in(MODULE, "function acme_log_submit", 10); + let edit = rename( + &backend, + &uri_for(&dir, MODULE_PATH), + position.line, + position.character, + "acme_note_submit", + ) + .await + .expect("an edit"); + for file in [ + (FORM_PATH, FORM), + (BUILDER_PATH, BUILDER), + (MODULE_PATH, MODULE), + ] { + assert_eq!( + renamed(&edit, &dir, file), + file.1.replace("acme_log_submit", "acme_note_submit"), + "{}", + file.0 + ); + } + assert!(edits_for_uri(&edit, &uri_for(&dir, FORM_FUNCTIONS_PATH)).is_empty()); + + let position = position_in(HOOKS, "function validate", 10); + let edit = rename( + &backend, + &uri_for(&dir, HOOKS_PATH), + position.line, + position.character, + "verify", + ) + .await + .expect("an edit"); + assert_eq!( + renamed(&edit, &dir, (HOOKS_PATH, HOOKS)), + HOOKS.replace("function validate", "function verify") + ); +} + +/// Callbacks that name nothing, or a method Drupal cannot call, which this +/// support reads without warning about, next to a call and a method call +/// that do get a warning. +const UNCHECKED_PATH: &str = "web/modules/custom/acme/src/Form/UncheckedForm.php"; + +const UNCHECKED: &str = r#"missingMethod(); + return $form; + } +} + +final class Guarded { + protected function hidden(): void {} +} +"#; + +#[tokio::test] +async fn reading_callbacks_adds_no_warning() { + let (backend, dir) = workspace(&[ + (FORM_INTERFACE_PATH, FORM_INTERFACE), + (FORM_BASE_PATH, FORM_BASE), + (HELPER_PATH, HELPER), + (UNCHECKED_PATH, UNCHECKED), + (HOOKS_PATH, HOOKS), + ]) + .await; + backend.ensure_workspace_indexed(); + for (path, content, expected) in [ + ( + UNCHECKED_PATH, + UNCHECKED, + &["acme_missing_function()", "missingMethod"][..], + ), + (HOOKS_PATH, HOOKS, &[][..]), + ] { + let uri = uri_for(&dir, path); + let mut diagnostics = Vec::new(); + backend.collect_slow_diagnostics(uri.as_str(), content, &mut diagnostics); + backend.collect_fast_diagnostics(uri.as_str(), content, &mut diagnostics); + let messages: Vec<&str> = diagnostics + .iter() + .map(|diagnostic| crate::common::message_text(&diagnostic.message)) + .collect(); + assert_eq!(messages.len(), expected.len(), "{path}: {messages:?}"); + for name in expected { + assert!( + messages.iter().any(|message| message.contains(name)), + "{path}: {messages:?}" + ); + } + } +} + +/// The site with [`BUILDER`] on disk but not open, so the searches reach it +/// through the index rather than an open buffer. +async fn site_with_closed_builder() -> (phpantom_lsp::Backend, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let full = dir.path().join(BUILDER_PATH); + std::fs::create_dir_all(full.parent().unwrap()).unwrap(); + std::fs::write(full, BUILDER).unwrap(); + let (backend, dir) = workspace_in( + dir, + &[ + (FORM_INTERFACE_PATH, FORM_INTERFACE), + (FORM_BASE_PATH, FORM_BASE), + (HELPER_PATH, HELPER), + (GLOBAL_HELPER_PATH, GLOBAL_HELPER), + (MODULE_PATH, MODULE), + (FORM_FUNCTIONS_PATH, FORM_FUNCTIONS), + (FORM_PATH, FORM), + ], + ) + .await; + backend.ensure_workspace_indexed(); + (backend, dir) +} + +#[tokio::test] +async fn references_and_rename_start_from_the_callback_string_too() { + let (backend, dir) = site_with_closed_builder().await; + let form = (FORM_PATH, FORM); + + let found = reference_lines(&backend, &dir, form, "'::saveTitle'", 4).await; + assert_eq!( + found, + lines( + &dir, + &[ + (FORM_PATH, FORM, "function saveTitle"), + (FORM_PATH, FORM, "'::saveTitle'"), + (FORM_PATH, FORM, "static::class . '::saveTitle'"), + ] + ) + ); + let found = reference_lines(&backend, &dir, form, "'acme_log_submit'", 3).await; + assert_eq!( + found, + lines( + &dir, + &[ + (MODULE_PATH, MODULE, "function acme_log_submit"), + (FORM_PATH, FORM, "'acme_log_submit'"), + (BUILDER_PATH, BUILDER, "'acme_log_submit'"), + ] + ) + ); + + let form_uri = uri_for(&dir, FORM_PATH); + let position = position_in(FORM, "'acme_log_submit'", 3); + match prepare_rename(&backend, &form_uri, position.line, position.character).await { + Some(PrepareRenameResult::PrepareRenamePlaceholder(PrepareRenamePlaceholder { + placeholder, + .. + })) => { + assert_eq!(placeholder, "acme_log_submit"); + } + other => panic!("expected a placeholder, got {other:?}"), + } + let edit = rename( + &backend, + &form_uri, + position.line, + position.character, + "acme_note_submit", + ) + .await + .expect("an edit"); + for file in [ + (FORM_PATH, FORM), + (BUILDER_PATH, BUILDER), + (MODULE_PATH, MODULE), + ] { + assert_eq!( + renamed(&edit, &dir, file), + file.1.replace("acme_log_submit", "acme_note_submit"), + "{}", + file.0 + ); + } + assert!(edits_for_uri(&edit, &uri_for(&dir, FORM_FUNCTIONS_PATH)).is_empty()); + + let position = position_in(FORM, "'Helper::shout'", 10); + let edit = rename( + &backend, + &form_uri, + position.line, + position.character, + "yell", + ) + .await + .expect("an edit"); + assert_eq!( + renamed(&edit, &dir, (FORM_PATH, FORM)), + FORM.replacen("'Helper::shout'", "'Helper::yell'", 1) + ); + assert_eq!( + renamed(&edit, &dir, (BUILDER_PATH, BUILDER)), + BUILDER.replacen("'Helper::shout'", "'Helper::yell'", 1) + ); + assert_eq!( + renamed(&edit, &dir, (GLOBAL_HELPER_PATH, GLOBAL_HELPER)), + GLOBAL_HELPER.replace("shout", "yell") + ); + assert!(edits_for_uri(&edit, &uri_for(&dir, HELPER_PATH)).is_empty()); +} diff --git a/tests/integration/main.rs b/tests/integration/main.rs index 76cb7840d..0fb1f38bb 100644 --- a/tests/integration/main.rs +++ b/tests/integration/main.rs @@ -217,6 +217,7 @@ mod document_highlight; mod document_links; mod document_symbols; mod document_symbols_blade; +mod drupal_callbacks; mod drupal_config; mod drupal_config_keys; mod drupal_directories; From d44d3f9a295b158dc2a1ce7f6ccd4b7437154bfb Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Tue, 10 Nov 2026 18:32:24 +0100 Subject: [PATCH 2/6] Navigate Drupal service callbacks In a Drupal project, a 'service:method' string in a form or render array's callback keys now leads to the method of the service's class: go-to-definition, hover, find references and rename, an alias leading to its target's class. The service part navigates to the service like any other service ID. The playground's greeting card has a lazy builder that names a method of the acme.greeter service. Assisted-by: claude-code/claude-opus-5-5 --- examples/drupal/README.md | 6 + examples/drupal/assertions.php | 14 + .../src/Controller/GreetingController.php | 9 + .../web/modules/custom/acme/src/Greeter.php | 18 +- src/drupal/routing.rs | 2 +- src/symbol_map/extraction/drupal.rs | 49 +++- tests/integration/drupal_callbacks.rs | 256 +++++++++++++++++- 7 files changed, 347 insertions(+), 7 deletions(-) diff --git a/examples/drupal/README.md b/examples/drupal/README.md index f4785d362..127bbe349 100644 --- a/examples/drupal/README.md +++ b/examples/drupal/README.md @@ -162,6 +162,12 @@ Run `composer install` here first. Composer puts core and contrib into `'Drupal\acme\Form\GreetingForm::addHint'` and of `'acme_greeting_form_submit'`, a function of `acme.module`. Find the references of a callback method, or rename it, and the strings follow. + A `'service:method'` callback leads to the method of the service's + class: in `card()` in + `web/modules/custom/acme/src/Controller/GreetingController.php`, go to + the definition of `buildGreeting` in `'acme.greeter:buildGreeting'`, + which lands on Greeter's method, or of `acme.greeter`, which lands on + its key in `acme.services.yml`. - Plugin IDs navigate to the plugin class that declares them, for every plugin type a plugin manager declares, core's and contributed modules' included. In `block()` in diff --git a/examples/drupal/assertions.php b/examples/drupal/assertions.php index b89443512..5dfc5466a 100644 --- a/examples/drupal/assertions.php +++ b/examples/drupal/assertions.php @@ -41,6 +41,7 @@ use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint; use Drupal\Core\Config\ConfigBase; use Drupal\Core\Controller\ControllerBase; +use Drupal\Core\DependencyInjection\ClassResolver; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\DependencyInjection\YamlFileLoader; @@ -58,6 +59,7 @@ use Drupal\Core\Form\FormState; use Drupal\Core\Hook\Attribute\Hook; use Drupal\Core\Language\LanguageManager; +use Drupal\Core\Security\TrustedCallbackInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\StringTranslation\TranslatableMarkup; use Drupal\Core\Link; @@ -67,6 +69,7 @@ use Drupal\Core\Render\Element\Details; use Drupal\Core\Render\Element\RenderElementBase; use Drupal\Core\Url; +use Drupal\Core\Utility\CallableResolver; use Drupal\language\ConfigurableLanguageManager; use Drupal\language\LanguageServiceProvider; @@ -458,6 +461,17 @@ protected function getDefaultLanguageValues() check("FormState rewrites '::validateName' as a call on the form object", $greetingFormState->prepareCallback('::validateName') === [$greetingForm, 'validateName']); check('GreetingForm is a form', $greetingForm instanceof FormInterface); +// The card's lazy builder names a method of the acme.greeter service, which +// Drupal's CallableResolver finds through the container. A lazy builder +// must be a trusted callback. +check("GreetingController::card() has the lazy builder 'acme.greeter:buildGreeting'", str_contains((string) file_get_contents("$module/src/Controller/GreetingController.php"), "'#lazy_builder' => ['acme.greeter:buildGreeting', [\$name]]")); +$lazyContainer = new ContainerBuilder(); +$lazyContainer->set('acme.greeter', (new ReflectionClass(Greeter::class))->newInstanceWithoutConstructor()); +$lazyCallable = (new CallableResolver(new ClassResolver($lazyContainer)))->getCallableFromDefinition('acme.greeter:buildGreeting'); +check("CallableResolver calls 'acme.greeter:buildGreeting' on the service", is_array($lazyCallable) && $lazyCallable[0] instanceof Greeter && $lazyCallable[1] === 'buildGreeting'); +check('acme.services.yml builds acme.greeter from Greeter, which declares buildGreeting()', $container->getDefinition('acme.greeter')->getClass() === Greeter::class && (new ReflectionMethod(Greeter::class, 'buildGreeting'))->isPublic()); +check('Greeter trusts buildGreeting() as a render callback', is_subclass_of(Greeter::class, TrustedCallbackInterface::class) && in_array('buildGreeting', Greeter::trustedCallbacks(), true)); + // ─── Summary ──────────────────────────────────────────────────────────────── echo "\n"; diff --git a/examples/drupal/web/modules/custom/acme/src/Controller/GreetingController.php b/examples/drupal/web/modules/custom/acme/src/Controller/GreetingController.php index 71d98b526..c7bed9484 100644 --- a/examples/drupal/web/modules/custom/acme/src/Controller/GreetingController.php +++ b/examples/drupal/web/modules/custom/acme/src/Controller/GreetingController.php @@ -100,6 +100,15 @@ public function card(string $name): array ]; $build['more']['#type'] = 'details'; $build['more']['#title'] = $this->t('More'); + // Try: go to the definition of buildGreeting, which lands on the + // method of Greeter, the class of the acme.greeter service, or of + // acme.greeter, which lands on its key in acme.services.yml. Find + // the references of Greeter::buildGreeting(), or rename it, and the + // string follows. + $build['later'] = [ + '#lazy_builder' => ['acme.greeter:buildGreeting', [$name]], + '#create_placeholder' => true, + ]; return $build; } diff --git a/examples/drupal/web/modules/custom/acme/src/Greeter.php b/examples/drupal/web/modules/custom/acme/src/Greeter.php index 4d457554f..bba88e051 100644 --- a/examples/drupal/web/modules/custom/acme/src/Greeter.php +++ b/examples/drupal/web/modules/custom/acme/src/Greeter.php @@ -5,12 +5,13 @@ namespace Drupal\acme; use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Security\TrustedCallbackInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; /** * Builds the greeting the demo route shows. */ -final class Greeter +final class Greeter implements TrustedCallbackInterface { use StringTranslationTrait; @@ -39,4 +40,19 @@ public function greet(string $name): string return $greeting; } + + /** + * The greeting as a render array, for the card's lazy builder. + * + * @return array + */ + public function buildGreeting(string $name): array + { + return ['#markup' => $this->greet($name)]; + } + + public static function trustedCallbacks(): array + { + return ['buildGreeting']; + } } diff --git a/src/drupal/routing.rs b/src/drupal/routing.rs index f202c6a63..b7abae18c 100644 --- a/src/drupal/routing.rs +++ b/src/drupal/routing.rs @@ -522,7 +522,7 @@ fn is_method_name(name: &str) -> bool { } /// Whether `name` can be an entity type ID or a service ID. -fn is_plain_name(name: &str) -> bool { +pub(crate) fn is_plain_name(name: &str) -> bool { !name.is_empty() && name .bytes() diff --git a/src/symbol_map/extraction/drupal.rs b/src/symbol_map/extraction/drupal.rs index 96fb8d8a1..6a74dcdba 100644 --- a/src/symbol_map/extraction/drupal.rs +++ b/src/symbol_map/extraction/drupal.rs @@ -2895,9 +2895,9 @@ fn push_keyed_callbacks(key: &str, value: &Expression<'_>, ctx: &mut ExtractionC /// Record what one callback names: a method of the form for `'::method'`, /// a method of the class for `'Class::method'` or a class name joined to -/// `'::method'`, and a function for a name without a colon. An array -/// callable is read wherever it is written, and `'service:method'` names a -/// service rather than a class. +/// `'::method'`, a service and a method of its class for +/// `'service:method'`, and a function for a name without a colon. An array +/// callable is read wherever it is written. fn push_callback(callback: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { if let Expression::Binary(binary) = callback && binary.operator.is_concatenation() @@ -2937,7 +2937,9 @@ fn push_callback(callback: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { ctx, ); } - } else if !value.contains(':') { + } else if let Some((service, method)) = value.split_once(':') { + push_service_callback(service, method, start, end, ctx); + } else { let name = value.strip_prefix('\\').unwrap_or(value); if is_qualified_name(name) { ctx.spans.push(SymbolSpan { @@ -2954,6 +2956,44 @@ fn push_callback(callback: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { } } +/// Record the service a `'service:method'` callback, its content running +/// from `start` to `end`, names, and the method of the service's class, +/// which the type engine finds through the container as it does for +/// `\Drupal::service('service')`. +fn push_service_callback( + service: &str, + method: &str, + start: usize, + end: usize, + ctx: &mut ExtractionCtx<'_>, +) { + if !crate::drupal::routing::is_plain_name(service) + || !is_identifier(method) + || !ctx.content[start..end].starts_with(service) + || !ctx.content[..end].ends_with(method) + { + return; + } + ctx.spans.push(SymbolSpan { + start: start as u32, + end: (start + service.len()) as u32, + kind: SymbolKind::StringKey { + kind: StringKeyKind::ServiceId, + key: service.to_string(), + is_write: false, + is_optional: false, + }, + }); + push_callback_method( + SubjectText::owned(crate::drupal::routing::service_subject(service)), + false, + DocblockMemberRef::No, + method, + (end - method.len()) as u32, + ctx, + ); +} + /// Record the method `X::class . '::method'`, `static::class . '::method'`, /// `self::class . '::method'` or `__CLASS__ . '::method'` names. The /// `'::method'` half is never read on its own. @@ -4404,6 +4444,7 @@ $joined = static::class . '::nothing'; ("check", "\\Acme\\Helper::check"), ("check", "Helper::check"), ("acme_check", "function \\acme_check"), + ("check", "\\Drupal::service('acme.checker')::check"), ("refresh", "static::refresh"), ("refresh", "self::refresh"), ("build", "\\Acme\\Builder::build"), diff --git a/tests/integration/drupal_callbacks.rs b/tests/integration/drupal_callbacks.rs index 831d9ddad..379e1289d 100644 --- a/tests/integration/drupal_callbacks.rs +++ b/tests/integration/drupal_callbacks.rs @@ -1,6 +1,7 @@ //! Drupal's form and render callbacks: the methods and functions a callback //! key of a form or render array names, as `'::method'`, `'Class::method'`, -//! a class name joined to `'::method'`, or a function name. +//! a class name joined to `'::method'`, `'service:method'`, or a function +//! name. use crate::common::{apply_edits, edits_for_uri, hover_text_at, prepare_rename, rename}; use crate::drupal_services::{ @@ -990,3 +991,256 @@ async fn references_and_rename_start_from_the_callback_string_too() { ); assert!(edits_for_uri(&edit, &uri_for(&dir, HELPER_PATH)).is_empty()); } + +const BUILDERS_PATH: &str = "web/modules/custom/acme/src/GreetingBuilders.php"; + +/// Two service classes that both declare `build()` and `preRender()`. +const BUILDERS: &str = r#" ['acme.greeting_builder:build', []], + '#pre_render' => ['acme.greeting_alias:preRender', 'acme.greeting_shorthand:preRender'], + ]; + $element['#pre_render'][] = 'acme.greeting_builder:preRender'; + $element['#markup'] = 'acme.farewell_builder:preRender'; + return $element; + } +} +"#; + +/// A site whose services file declares a service, an alias of it in each +/// spelling, and a second service, with [`CARD`] closed when `card_open` +/// is false. +async fn service_site(card_open: bool) -> (phpantom_lsp::Backend, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let mut files = vec![ + (BUILDERS_PATH, BUILDERS), + (BUILDER_SERVICES_PATH, BUILDER_SERVICES), + ]; + if card_open { + files.push((CARD_PATH, CARD)); + } else { + let full = dir.path().join(CARD_PATH); + std::fs::create_dir_all(full.parent().unwrap()).unwrap(); + std::fs::write(full, CARD).unwrap(); + } + let (backend, dir) = workspace_in(dir, &files).await; + backend.ensure_workspace_indexed(); + (backend, dir) +} + +#[tokio::test] +async fn a_service_callback_goes_to_the_method_of_the_service_class() { + let (backend, dir) = service_site(true).await; + let card = (CARD_PATH, CARD); + let builders_uri = uri_for(&dir, BUILDERS_PATH); + let build = (builders_uri.clone(), line_of(BUILDERS, "build()")); + let pre_render = (builders_uri.clone(), line_of(BUILDERS, "preRender")); + for (needle, inside, expected) in [ + ("'acme.greeting_builder:build'", 23, &build), + // An alias, written either way, leads to its target's class. + ("'acme.greeting_alias:preRender'", 22, &pre_render), + ("'acme.greeting_shorthand:preRender'", 26, &pre_render), + ("'acme.greeting_builder:preRender'", 24, &pre_render), + ] { + let found = definition_lines(&backend, &dir, card, needle, inside).await; + assert_eq!(found, vec![expected.clone()], "{needle}"); + } + + let services_uri = uri_for(&dir, BUILDER_SERVICES_PATH); + for (needle, declared) in [ + ("'acme.greeting_builder:build'", " acme.greeting_builder:"), + ("'acme.greeting_alias:preRender'", " acme.greeting_alias:"), + ] { + let found = definition_lines(&backend, &dir, card, needle, 3).await; + assert_eq!( + found, + vec![(services_uri.clone(), line_of(BUILDER_SERVICES, declared))], + "{needle}" + ); + } + + // A string outside a callback key names nothing. + let found = definition_lines(&backend, &dir, card, "'acme.farewell_builder:", 24).await; + assert_eq!(found, Vec::new()); +} + +#[tokio::test] +async fn a_hover_on_a_service_callback_shows_the_method_and_the_service() { + let (backend, dir) = service_site(true).await; + let card_uri = uri_for(&dir, CARD_PATH); + for (needle, inside, expected) in [ + ("'acme.greeting_alias:preRender'", 22, "GreetingBuilder"), + ( + "'acme.greeting_builder:build'", + 3, + "**Service** `acme.greeting_builder`", + ), + ] { + let position = position_in(CARD, needle, inside); + let hover = hover_text_at(&backend, &card_uri, position.line, position.character) + .await + .unwrap_or_else(|| panic!("no hover on {needle}")); + assert!(hover.contains(expected), "{needle}: {hover}"); + } +} + +#[tokio::test] +async fn the_references_of_a_service_method_list_its_callbacks() { + for card_open in [true, false] { + let (backend, dir) = service_site(card_open).await; + let expected = lines( + &dir, + &[ + (BUILDERS_PATH, BUILDERS, "public function preRender"), + (CARD_PATH, CARD, "'acme.greeting_alias:preRender'"), + (CARD_PATH, CARD, "'acme.greeting_shorthand:preRender'"), + (CARD_PATH, CARD, "$element['#pre_render'][]"), + ], + ); + let found = + reference_lines(&backend, &dir, (BUILDERS_PATH, BUILDERS), "preRender", 2).await; + assert_eq!(found, expected, "card open: {card_open}"); + if card_open { + let found = reference_lines( + &backend, + &dir, + (CARD_PATH, CARD), + "'acme.greeting_builder:preRender'", + 24, + ) + .await; + assert_eq!(found, expected); + } + + // The other service's `preRender()` has no callback naming it. + let farewell = BUILDERS.find("FarewellBuilder").unwrap(); + let farewell = farewell + BUILDERS[farewell..].find("preRender").unwrap(); + let found = references_at( + &backend, + &uri_for(&dir, BUILDERS_PATH), + crate::common::offset_position(BUILDERS, farewell + 2), + ) + .await; + assert_eq!( + found, + vec![( + uri_for(&dir, BUILDERS_PATH), + BUILDERS[..farewell].matches('\n').count() as u32 + )], + "card open: {card_open}" + ); + } +} + +#[tokio::test] +async fn renaming_a_service_method_rewrites_its_callbacks() { + let (backend, dir) = service_site(false).await; + let position = position_in(BUILDERS, "preRender", 2); + let edit = rename( + &backend, + &uri_for(&dir, BUILDERS_PATH), + position.line, + position.character, + "decorate", + ) + .await + .expect("an edit"); + assert_eq!( + renamed(&edit, &dir, (CARD_PATH, CARD)), + CARD.replace("greeting_alias:preRender", "greeting_alias:decorate") + .replace( + "greeting_shorthand:preRender", + "greeting_shorthand:decorate" + ) + .replace("greeting_builder:preRender", "greeting_builder:decorate") + ); + assert_eq!( + renamed(&edit, &dir, (BUILDERS_PATH, BUILDERS)), + BUILDERS.replacen("preRender", "decorate", 1) + ); +} + +#[tokio::test] +async fn the_references_of_a_service_list_its_callbacks() { + let (backend, dir) = service_site(true).await; + let found = references_at( + &backend, + &uri_for(&dir, BUILDER_SERVICES_PATH), + position_in(BUILDER_SERVICES, "acme.greeting_builder:", 3), + ) + .await; + let card_uri = uri_for(&dir, CARD_PATH); + for needle in ["'acme.greeting_builder:build'", "$element['#pre_render'][]"] { + assert!( + found.contains(&(card_uri.clone(), line_of(CARD, needle))), + "{needle}: {found:?}" + ); + } + assert!( + !found.contains(&(card_uri.clone(), line_of(CARD, "'#markup'"))), + "{found:?}" + ); +} + +const UNKNOWN_CARD_PATH: &str = "web/modules/custom/acme/src/Render/UnknownCard.php"; + +const UNKNOWN_CARD: &str = r#" ['acme.missing_builder:build', 'acme.greeting_builder:nope'], + ]; + } +} +"#; + +#[tokio::test] +async fn a_service_callback_checks_its_service_like_any_service_id() { + let (backend, dir) = workspace_in( + tempfile::tempdir().unwrap(), + &[ + (BUILDERS_PATH, BUILDERS), + (BUILDER_SERVICES_PATH, BUILDER_SERVICES), + (UNKNOWN_CARD_PATH, UNKNOWN_CARD), + ], + ) + .await; + backend.ensure_workspace_indexed(); + let uri = uri_for(&dir, UNKNOWN_CARD_PATH); + let mut diagnostics = Vec::new(); + backend.collect_slow_diagnostics(uri.as_str(), UNKNOWN_CARD, &mut diagnostics); + backend.collect_fast_diagnostics(uri.as_str(), UNKNOWN_CARD, &mut diagnostics); + let messages: Vec<&str> = diagnostics + .iter() + .map(|diagnostic| crate::common::message_text(&diagnostic.message)) + .collect(); + // The method a declared service's class lacks is not reported here. + assert_eq!(messages.len(), 1, "{messages:?}"); + assert!(messages[0].contains("acme.missing_builder"), "{messages:?}"); +} From 541d05175532e031bf71c5edafbaf3b2999276aa Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Tue, 10 Nov 2026 19:01:19 +0100 Subject: [PATCH 3/6] Complete Drupal form and render callbacks In a Drupal project, a string in a form or render array's callback keys now completes what it can name while it is typed: after '::', the public methods of the form it is written in, or of the trait; after 'Class::', the public methods of that class, the class name read as fully qualified; after 'service:', the public methods of the service's class; and before any colon, function names, written as their fully qualified names. A class name joined to '::' completes that class's methods. '::' completes nothing under the render callback keys, where Drupal does not call it on the form, and a value callback is offered only static methods and functions. The Drupal completion benchmark has a function and a method callback case. Assisted-by: claude-code/claude-opus-5-5 --- benches/drupal_completion.rs | 18 + examples/drupal/README.md | 3 + .../custom/acme/src/Form/GreetingForm.php | 4 +- src/completion/drupal_callbacks.rs | 323 ++++++++++++++ src/completion/drupal_libraries.rs | 27 +- src/completion/handler/string_arguments.rs | 12 + src/completion/mod.rs | 1 + src/completion/symfony_string_keys.rs | 51 ++- src/drupal/elements.rs | 25 ++ src/drupal/forms.rs | 39 +- src/symbol_map/extraction/drupal.rs | 23 +- tests/integration/drupal_callbacks.rs | 407 ++++++++++++++++++ 12 files changed, 873 insertions(+), 60 deletions(-) create mode 100644 src/completion/drupal_callbacks.rs diff --git a/benches/drupal_completion.rs b/benches/drupal_completion.rs index d582f3133..a4141c87e 100644 --- a/benches/drupal_completion.rs +++ b/benches/drupal_completion.rs @@ -126,8 +126,12 @@ final class Consumer $this->blocks->createInstance('mod1_'); $themed = ['#theme' => 'mod1_']; $build = ['#attached' => ['library' => ['mod1/']]]; + $build = ['#submit' => ['mod1_']]; + $build = ['#pre_render' => ['Drupal\acme\Consumer::r']]; } } + +function mod1_submit(): void {} "#; const MODULE_PATH: &str = "web/modules/custom/acme/acme.module"; @@ -445,6 +449,20 @@ fn bench_drupal_name_completion(c: &mut Criterion) { "['library' => ['mod1/'", "mod1/library7", ), + ( + "callback_function", + &consumer, + CONSUMER_PHP, + "['#submit' => ['mod1_'", + "Drupal\\acme\\mod1_submit", + ), + ( + "callback_method", + &consumer, + CONSUMER_PHP, + "['#pre_render' => ['Drupal\\acme\\Consumer::r'", + "run", + ), ( "hook_implementation", &module, diff --git a/examples/drupal/README.md b/examples/drupal/README.md index 127bbe349..0f84e984d 100644 --- a/examples/drupal/README.md +++ b/examples/drupal/README.md @@ -162,6 +162,9 @@ Run `composer install` here first. Composer puts core and contrib into `'Drupal\acme\Form\GreetingForm::addHint'` and of `'acme_greeting_form_submit'`, a function of `acme.module`. Find the references of a callback method, or rename it, and the strings follow. + Complete inside a callback string: after `'::` the form's public methods + are offered, after `'Class::` the class's, after `'service:` the service + class's, and before any colon the functions. A `'service:method'` callback leads to the method of the service's class: in `card()` in `web/modules/custom/acme/src/Controller/GreetingController.php`, go to diff --git a/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php b/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php index d310db17b..8328d2b0d 100644 --- a/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php +++ b/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php @@ -26,7 +26,9 @@ public function buildForm(array $form, FormStateInterface $form_state): array // Try: go to the definition of validateName after the `::`, which // lands on the method of this form: Drupal calls a '::method' // callback on the form object. Find the references of - // validateName(), or rename it, and the string follows. + // validateName(), or rename it, and the string follows. Delete + // validateName and complete after the `::`: the form's public + // methods are offered. $form['#validate'][] = '::validateName'; $form['name'] = [ '#type' => 'textfield', diff --git a/src/completion/drupal_callbacks.rs b/src/completion/drupal_callbacks.rs new file mode 100644 index 000000000..2d1d4a55f --- /dev/null +++ b/src/completion/drupal_callbacks.rs @@ -0,0 +1,323 @@ +//! Completion of the methods and functions a Drupal form or render +//! callback names. +//! +//! A string in one of the keys Drupal reads callbacks from (see +//! [`crate::drupal::forms`]) completes what it can name so far: after +//! `'::`, a public method of the form it is written in, or of the trait; +//! after `'Class::`, a public method of that class, the name read as fully +//! qualified; after `'service:`, a public method of the service's class; +//! and before any colon, a function. A class name joined to `'::` names +//! a method of that class. The buffer is mid-edit and usually does not +//! parse, so the key is recognised from the text before the string, in +//! the shapes the symbol map reads. + +use std::borrow::Cow; +use std::sync::Arc; + +use tower_lsp_server::gen_lsp_types::*; + +use crate::Backend; +use crate::class_lookup::Fqn; +use crate::completion::laravel_string_keys::string_key_response; +use crate::completion::source::code_context::{CodeContext, OpenBracket}; +use crate::completion::symfony_string_keys::OfferedMethods; +use crate::drupal::elements::{ + arrow_key, assignment_target, ends_with_keys, trailing_literal, value_key, +}; +use crate::drupal::forms::{ + AJAX, AJAX_CALLBACK, CALLBACK_KEYS, CALLBACK_LIST_KEYS, LAZY_BUILDER, RENDER_CALLBACK_KEYS, + VALUE_CALLBACK, +}; +use crate::text_position::{offset_to_position, position_to_offset}; +use crate::types::{ClassInfo, FileContext}; + +/// The callback string the cursor is typing in. +struct CallbackString<'a> { + /// The key Drupal reads the callback under. + key: &'a str, + /// The class a concatenation joins the string to. + joined: Option>, + /// Where the string's contents start. + start: usize, +} + +/// The class expression before `. '::method'`. +enum JoinedClass<'a> { + /// `Name::class`, a name written in code. + Named(&'a str), + /// `static::class`, `self::class`, or `__CLASS__`. + Own, +} + +impl Backend { + /// Complete the method or function a callback string names so far. + pub(crate) fn try_drupal_callback_completion( + &self, + uri: &str, + content: &str, + position: Position, + code: &CodeContext<'_>, + ctx: &FileContext, + ) -> Option { + let site = callback_string(content, code)?; + let cursor = position_to_offset(content, position) as usize; + let typed = content.get(site.start..cursor)?; + // Drupal calls a value callback only when it is a native callable, + // which a non-static method named by a string is not. + let native = site.key == VALUE_CALLBACK; + let offered = if native { + OfferedMethods::Static + } else { + OfferedMethods::Any + }; + let loader = self.resolved_class_loader(ctx); + let own_class = || { + crate::class_lookup::find_shared_class_at_offset(&ctx.classes, cursor as u32).cloned() + }; + + let (classes, method) = if let Some(joined) = site.joined { + let method = typed.strip_prefix("::")?; + let class = match joined { + JoinedClass::Own => own_class()?, + JoinedClass::Named(name) => loader(Fqn::new( + &super::array_callable::resolve_class_name_to_fqn(self, name, ctx), + ))?, + }; + (vec![class], method) + } else if let Some((class, method)) = typed.rsplit_once("::") { + let classes = if class.is_empty() { + if native || RENDER_CALLBACK_KEYS.contains(&site.key) { + return None; + } + crate::drupal::forms::form_callback_classes(vec![own_class()?], &loader) + } else { + // A class name in a string is a runtime name, which is fully + // qualified whether or not it says so. + let class = unescaped(class); + let class = class.strip_prefix('\\').unwrap_or(&class); + if !is_qualified_name(class) { + return None; + } + vec![loader(Fqn::new(class))?] + }; + (classes, method) + } else if let Some((service, method)) = typed.split_once(':') { + if native || !crate::drupal::routing::is_plain_name(service) { + return None; + } + let classes: Vec> = self + .symfony_service_classes(service) + .iter() + .filter_map(|class| loader(Fqn::new(class))) + .collect(); + (classes, method) + } else { + return self.callback_function_response(uri, content, site.start, typed, position); + }; + + if !is_identifier_prefix(method) { + return None; + } + let names = self.public_method_names(&classes, &loader, method, offered); + string_key_response( + names, + CompletionItemKind::Method, + content, + cursor - method.len(), + position, + ) + } + + /// The functions whose name contains the `typed` part of a callback + /// string that starts at `start`, each written as the fully qualified + /// name PHP reads a function name in a string as. + fn callback_function_response( + &self, + uri: &str, + content: &str, + start: usize, + typed: &str, + position: Position, + ) -> Option { + if !typed + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'\\')) + { + return None; + } + let name = typed.trim_start_matches('\\'); + let range = Range::new( + offset_to_position(content, start + typed.len() - name.len()), + position, + ); + // A double-quoted string reads some backslashes as escapes (`\n`, + // `\f`, …), so a namespace separator is written escaped there. + let double_quoted = content.as_bytes().get(start.wrapping_sub(1)) == Some(&b'"'); + let (mut items, is_incomplete) = + self.build_function_completions(&unescaped(name), true, None, &None, uri, position); + for item in &mut items { + let new_text = item + .insert_text + .take() + .unwrap_or_else(|| item.label.clone()); + let new_text = if double_quoted { + new_text.replace('\\', "\\\\") + } else { + new_text + }; + item.text_edit = Some(CompletionItemTextEdit::TextEdit(TextEdit { + range, + new_text, + })); + } + (!items.is_empty()).then_some(CompletionResponse::CompletionList(CompletionList { + is_incomplete, + items, + apply_kind: None, + item_defaults: None, + })) + } +} + +/// The callback string the cursor is in, when the key it is written under +/// is one Drupal reads a callback from. +fn callback_string<'a>(content: &'a str, code: &CodeContext<'_>) -> Option> { + let (quote, _) = code.open_string?; + let before = &content[..code.code_before.len()]; + let (before, joined) = match before.strip_suffix('.') { + Some(joined) => { + let (before, class) = joined_class(joined.trim_end())?; + (before, Some(class)) + } + None => (before, None), + }; + let key = callback_key(content, before, &code.open_brackets)?; + Some(CallbackString { + key, + joined, + start: quote + 1, + }) +} + +/// The code before the class expression `before` ends with, and the class +/// it names. +fn joined_class(before: &str) -> Option<(&str, JoinedClass<'_>)> { + if let Some(rest) = before.strip_suffix("__CLASS__") { + return Some((rest.trim_end(), JoinedClass::Own)); + } + let at = before.len().checked_sub("::class".len())?; + if !before.get(at..)?.eq_ignore_ascii_case("::class") { + return None; + } + let class = before[..at].trim_end(); + let name_start = class + .rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '\\')) + .map_or(0, |at| at + 1); + let (rest, name) = class.split_at(name_start); + if name.is_empty() || rest.ends_with(['$', '>', ':']) { + return None; + } + let joined = if name.eq_ignore_ascii_case("static") || name.eq_ignore_ascii_case("self") { + JoinedClass::Own + } else if name.eq_ignore_ascii_case("parent") { + return None; + } else { + JoinedClass::Named(name) + }; + Some((rest.trim_end(), joined)) +} + +/// The callback key a value that starts after `before` is written under: +/// `'#key' => …` or `$a['#key'] = …` for a key that holds one callback, +/// an item of the list under a key that holds a list (the first item for +/// `#lazy_builder`), `$a['#key'][] = …`, and the `callback` of an `#ajax` +/// array. +fn callback_key<'a>( + content: &'a str, + before: &'a str, + brackets: &[OpenBracket], +) -> Option<&'a str> { + match before.as_bytes().last()? { + b'>' | b'=' => { + if let Some(list) = + assignment_target(before).and_then(|target| target.trim_end().strip_suffix("[]")) + { + let key = trailing_literal(list.trim_end().strip_suffix(']')?)?; + return CALLBACK_LIST_KEYS.contains(&key).then_some(key); + } + if let Some(list) = keyed_list_entry(content, before, brackets) { + return Some(list); + } + let key = value_key(before)?; + if CALLBACK_KEYS.contains(&key) { + return Some(key); + } + let ajax = key == AJAX_CALLBACK + && if arrow_key(before).is_some() { + brackets.last().is_some_and(|array| { + array.byte == b'[' && value_key(&content[..array.code_before]) == Some(AJAX) + }) + } else { + assignment_target(before) + .is_some_and(|target| ends_with_keys(target, &[AJAX, AJAX_CALLBACK])) + }; + ajax.then_some(key) + } + b'[' | b',' => { + let list = brackets.last().filter(|list| list.byte == b'[')?; + let key = value_key(&content[..list.code_before])?; + (CALLBACK_LIST_KEYS.contains(&key) || (key == LAZY_BUILDER && list.commas == 0)) + .then_some(key) + } + _ => None, + } +} + +/// The list key whose keyed entry a value that starts after `before` is: +/// `'#submit' => ['name' => …]` or `$form['#entity_builders']['name'] = …`. +fn keyed_list_entry<'a>( + content: &'a str, + before: &'a str, + brackets: &[OpenBracket], +) -> Option<&'a str> { + let key = if arrow_key(before).is_some() { + let list = brackets.last().filter(|list| list.byte == b'[')?; + value_key(&content[..list.code_before])? + } else { + let entry = assignment_target(before)?.trim_end().strip_suffix(']')?; + let name = trailing_literal(entry)?; + let entry = entry.trim_end(); + let list = entry[..entry.len() - name.len() - 2] + .trim_end() + .strip_suffix('[')?; + trailing_literal(list.trim_end().strip_suffix(']')?)? + }; + CALLBACK_LIST_KEYS.contains(&key).then_some(key) +} + +/// `text` with the escaped backslashes of a string literal read. +fn unescaped(text: &str) -> Cow<'_, str> { + if text.contains("\\\\") { + Cow::Owned(text.replace("\\\\", "\\")) + } else { + Cow::Borrowed(text) + } +} + +/// Whether `name` is a class name, its namespace included. +fn is_qualified_name(name: &str) -> bool { + name.split('\\').all(|part| { + part.bytes() + .next() + .is_some_and(|first| first == b'_' || first.is_ascii_alphabetic()) + && part + .bytes() + .all(|byte| byte == b'_' || byte.is_ascii_alphanumeric()) + }) +} + +/// Whether `name` can start a method name, or is empty. +fn is_identifier_prefix(name: &str) -> bool { + name.bytes() + .all(|byte| byte == b'_' || byte.is_ascii_alphanumeric()) +} diff --git a/src/completion/drupal_libraries.rs b/src/completion/drupal_libraries.rs index 04445d8b7..bf86349fc 100644 --- a/src/completion/drupal_libraries.rs +++ b/src/completion/drupal_libraries.rs @@ -12,7 +12,7 @@ use tower_lsp_server::gen_lsp_types::{CompletionResponse, Position}; use crate::Backend; use crate::completion::source::code_context::CodeContext; -use crate::drupal::elements::{arrow_key, assignment_target}; +use crate::drupal::elements::{arrow_key, assignment_target, ends_with_keys}; use crate::symbol_map::StringKeyKind; use crate::text_position::position_to_offset; @@ -81,31 +81,6 @@ fn attached_library_start(content: &str, code: &CodeContext<'_>) -> Option bool { - for key in keys.iter().rev() { - let Some(rest) = target - .trim_end() - .strip_suffix(']') - .and_then(|rest| strip_quoted(rest.trim_end(), key)) - .and_then(|rest| rest.trim_end().strip_suffix('[')) - else { - return false; - }; - target = rest; - } - true -} - -/// `text` without the string literal `key` it ends with. -fn strip_quoted<'a>(text: &'a str, key: &str) -> Option<&'a str> { - ['\'', '"'].into_iter().find_map(|quote| { - text.strip_suffix(quote)? - .strip_suffix(key)? - .strip_suffix(quote) - }) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/completion/handler/string_arguments.rs b/src/completion/handler/string_arguments.rs index 5ab594935..33fb3e95c 100644 --- a/src/completion/handler/string_arguments.rs +++ b/src/completion/handler/string_arguments.rs @@ -196,6 +196,18 @@ impl Backend { return Some(response); } + // ── Drupal callbacks ──────────────────────────────────── + // `'#submit' => ['::|']`, `$form['#validate'][] = 'Class::|'`, and + // the other keys Drupal reads a callback from. + if matches!(string_ctx, StringContext::InStringLiteral) + && self.is_drupal_project() + && let Some(code) = code_ctx.as_ref() + && let Some(response) = + self.try_drupal_callback_completion(uri, content, position, code, ctx) + { + return Some(response); + } + // ── Symfony form options ──────────────────────────────── // `$builder->add('email', EmailType::class, ['|' => …])`, wherever // the form component is used. diff --git a/src/completion/mod.rs b/src/completion/mod.rs index 91c50b5e3..6386cda5b 100644 --- a/src/completion/mod.rs +++ b/src/completion/mod.rs @@ -79,6 +79,7 @@ pub mod array_shape; pub(crate) mod builder; pub(crate) mod command_params; mod doctrine_fields; +mod drupal_callbacks; mod drupal_config; pub(crate) mod drupal_hooks; mod drupal_libraries; diff --git a/src/completion/symfony_string_keys.rs b/src/completion/symfony_string_keys.rs index 4b62239c3..123980350 100644 --- a/src/completion/symfony_string_keys.rs +++ b/src/completion/symfony_string_keys.rs @@ -876,20 +876,44 @@ impl Backend { position: Position, ) -> Option { let loader = self.resolved_class_loader_with(&[]); - let prefix = content.get(start..cursor)?.as_bytes(); + let classes: Vec<_> = classes + .iter() + .filter_map(|class| loader(crate::class_lookup::Fqn::new(class))) + .collect(); + let names = self.public_method_names( + &classes, + &loader, + content.get(start..cursor)?, + OfferedMethods::Instance, + ); + string_key_response(names, CompletionItemKind::Method, content, start, position) + } + + /// The names of the public methods of `classes` that start with + /// `prefix`, ignoring case, leaving out magic methods. + pub(crate) fn public_method_names( + &self, + classes: &[std::sync::Arc], + loader: &crate::class_lookup::ResolvedClassLoader<'_>, + prefix: &str, + offered: OfferedMethods, + ) -> Vec { + let prefix = prefix.as_bytes(); let mut names: Vec = Vec::new(); for class in classes { - let Some(class) = loader(crate::class_lookup::Fqn::new(class)) else { - continue; - }; let class = crate::virtual_members::resolve_class_fully_cached( - &class, - &loader, + class, + loader, &self.resolved_class_cache, ); for method in &class.methods { - if method.visibility == Visibility::Public - && !method.is_static + let kept = match offered { + OfferedMethods::Instance => !method.is_static, + OfferedMethods::Any => true, + OfferedMethods::Static => method.is_static, + }; + if kept + && method.visibility == Visibility::Public && !method.name.starts_with("__") && method .name @@ -902,10 +926,19 @@ impl Backend { } } } - string_key_response(names, CompletionItemKind::Method, content, start, position) + names } } +/// Which of a class's public methods [`Backend::public_method_names`] +/// offers. +#[derive(Clone, Copy)] +pub(crate) enum OfferedMethods { + Instance, + Static, + Any, +} + /// What an `#[Autowire]`, `#[Template]`, `#[AsEventListener]`, or /// `#[AsMessageHandler]` string names, and where the name in it starts: /// `service:` a service, `param:` a parameter, and its value an `@id` diff --git a/src/drupal/elements.rs b/src/drupal/elements.rs index 82c80da3e..5ffce1b99 100644 --- a/src/drupal/elements.rs +++ b/src/drupal/elements.rs @@ -51,6 +51,31 @@ pub(crate) fn trailing_literal(text: &str) -> Option<&str> { Some(&inner[inner.rfind(quote)? + 1..]) } +/// Whether `target` ends with the offsets `['keys…']`, in order. +pub(crate) fn ends_with_keys(mut target: &str, keys: &[&str]) -> bool { + for key in keys.iter().rev() { + let Some(rest) = target + .trim_end() + .strip_suffix(']') + .and_then(|rest| strip_quoted(rest.trim_end(), key)) + .and_then(|rest| rest.trim_end().strip_suffix('[')) + else { + return false; + }; + target = rest; + } + true +} + +/// `text` without the string literal `key` it ends with. +fn strip_quoted<'a>(text: &'a str, key: &str) -> Option<&'a str> { + ['\'', '"'].into_iter().find_map(|quote| { + text.strip_suffix(quote)? + .strip_suffix(key)? + .strip_suffix(quote) + }) +} + impl Backend { /// The classes that declare the plugin `id` as a key of `kind`, in a /// stable order. diff --git a/src/drupal/forms.rs b/src/drupal/forms.rs index 94c354a38..41dd6d9df 100644 --- a/src/drupal/forms.rs +++ b/src/drupal/forms.rs @@ -1,5 +1,6 @@ -//! Drupal forms: the classes a form callback's `'::method'` can name a -//! method of. +//! Drupal forms: the keys a form or render array holds its callbacks +//! under, and the classes a form callback's `'::method'` can name a method +//! of. //! //! Drupal rewrites `'::method'` as `[$form_object, 'method']` before it //! calls it, so the string names a method of the form being built, which @@ -13,6 +14,40 @@ use std::sync::Arc; use crate::class_lookup::{Fqn, ResolvedClassLoader, is_subtype_of}; use crate::types::{ClassInfo, ClassLikeKind}; +/// The keys of a form or render array that hold a list of callbacks. +pub(crate) const CALLBACK_LIST_KEYS: [&str; 8] = [ + "#after_build", + "#element_validate", + "#entity_builders", + "#post_render", + "#pre_render", + "#process", + "#submit", + "#validate", +]; + +/// The keys that hold one callback. +pub(crate) const CALLBACK_KEYS: [&str; 2] = ["#access_callback", VALUE_CALLBACK]; + +/// The key whose callback Drupal calls only when it is a native callable. +pub(crate) const VALUE_CALLBACK: &str = "#value_callback"; + +/// The key whose list holds its callback first, then the arguments. +pub(crate) const LAZY_BUILDER: &str = "#lazy_builder"; + +/// The key whose array holds its callback under [`AJAX_CALLBACK`]. +pub(crate) const AJAX: &str = "#ajax"; +pub(crate) const AJAX_CALLBACK: &str = "callback"; + +/// The callback keys Drupal reads without rewriting `'::method'` for the +/// form, so `'::method'` names nothing under them. +pub(crate) const RENDER_CALLBACK_KEYS: [&str; 4] = [ + "#access_callback", + LAZY_BUILDER, + "#post_render", + "#pre_render", +]; + /// The interface every Drupal form implements. const FORM_INTERFACE: &str = "Drupal\\Core\\Form\\FormInterface"; diff --git a/src/symbol_map/extraction/drupal.rs b/src/symbol_map/extraction/drupal.rs index 6a74dcdba..15d6e74f2 100644 --- a/src/symbol_map/extraction/drupal.rs +++ b/src/symbol_map/extraction/drupal.rs @@ -5,6 +5,7 @@ //! [`crate::drupal`]). use super::*; +use crate::drupal::forms::{AJAX, AJAX_CALLBACK, CALLBACK_KEYS, CALLBACK_LIST_KEYS, LAZY_BUILDER}; use crate::symbol_map::extraction::symfony::{ RouteDeclaration, RouteName, is_route_attribute, push_route_spans, route_declarations, }; @@ -2770,28 +2771,6 @@ fn push_library(expression: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { // ─── Callbacks ────────────────────────────────────────────────────────────── -/// The keys of a form or render array that hold a list of callbacks. -const CALLBACK_LIST_KEYS: [&str; 8] = [ - "#after_build", - "#element_validate", - "#entity_builders", - "#post_render", - "#pre_render", - "#process", - "#submit", - "#validate", -]; - -/// The keys that hold one callback. -const CALLBACK_KEYS: [&str; 2] = ["#access_callback", "#value_callback"]; - -/// The key whose list holds its callback first, then the arguments. -const LAZY_BUILDER: &str = "#lazy_builder"; - -/// The key whose array holds its callback under [`AJAX_CALLBACK`]. -const AJAX: &str = "#ajax"; -const AJAX_CALLBACK: &str = "callback"; - /// Whether `content` quotes a key Drupal reads a callback under, found in /// one pass over its `#`s. pub(in crate::symbol_map::extraction) fn has_callback_key(content: &str) -> bool { diff --git a/tests/integration/drupal_callbacks.rs b/tests/integration/drupal_callbacks.rs index 379e1289d..dd8f8e3a2 100644 --- a/tests/integration/drupal_callbacks.rs +++ b/tests/integration/drupal_callbacks.rs @@ -1244,3 +1244,410 @@ async fn a_service_callback_checks_its_service_like_any_service_id() { assert_eq!(messages.len(), 1, "{messages:?}"); assert!(messages[0].contains("acme.missing_builder"), "{messages:?}"); } + +// ─── Completion ───────────────────────────────────────────────────────────── + +/// Where a completion test puts the cursor in a buffer. +const CURSOR: &str = "<|>"; + +/// What accepting each item offered at [`CURSOR`] in `buffer`, opened as +/// the file `path`, writes, and where the text it replaces starts, as the +/// byte offset into `buffer` without the marker. +async fn completed( + backend: &phpantom_lsp::Backend, + dir: &tempfile::TempDir, + path: &str, + buffer: &str, +) -> Vec<(String, usize)> { + let at = buffer + .find(CURSOR) + .expect("the buffer should mark the cursor"); + let content = buffer.replacen(CURSOR, "", 1); + let uri = uri_for(dir, path); + crate::common::open_document(backend, &uri, "php", &content).await; + let position = crate::common::offset_position(&content, at); + let items = crate::common::response_items( + crate::common::completion_response(backend, &uri, position.line, position.character, None) + .await, + ) + .unwrap_or_default(); + let mut written: Vec<(String, usize)> = items + .into_iter() + .map(|item| match item.text_edit { + Some(CompletionItemTextEdit::TextEdit(edit)) => { + assert_eq!(edit.range.end, position, "{}", item.label); + let line_start: usize = content + .split_inclusive('\n') + .take(edit.range.start.line as usize) + .map(str::len) + .sum(); + ( + edit.new_text, + line_start + edit.range.start.character as usize, + ) + } + _ => (item.insert_text.unwrap_or(item.label), usize::MAX), + }) + .collect(); + written.sort(); + written +} + +/// The names [`completed`] writes, each replacing the text from the +/// cursor's `typed` bytes back. +async fn completed_names( + backend: &phpantom_lsp::Backend, + dir: &tempfile::TempDir, + path: &str, + buffer: &str, + typed: usize, +) -> Vec { + let start = buffer.find(CURSOR).unwrap() - typed; + completed(backend, dir, path, buffer) + .await + .into_iter() + .map(|(name, at)| { + assert_eq!(at, start, "{name} should replace only what was typed"); + name + }) + .collect() +} + +const EDITED_FORM_PATH: &str = "web/modules/custom/acme/src/Form/EditedForm.php"; + +/// A form being edited, its methods declared above the method that builds +/// it so that an unclosed string leaves them in place. +fn edited_form(line: &str) -> String { + format!( + r#"", + "$form['#submit'][] = '::<|>'", + "$form['actions']['submit'] = ['#submit' => ['::saveTitle', '::<|>", + "$form['#validate'] = ['::<|>'];", + "$form['x']['#ajax']['callback'] = '::<|>';", + "$form['x'] = ['#ajax' => ['callback' => '::<|>']];", + "$form['x'] = ['#process' => [\n '::<|>',\n ]];", + "$form['#submit'] = ['acme_save' => '::<|>'];", + "$form['#entity_builders']['acme_entity'] = '::<|>';", + ] { + let names = completed_names(&backend, &dir, EDITED_FORM_PATH, &edited_form(line), 0).await; + assert_eq!(names, ["buildForm", "processTitle", "saveTitle"], "{line}"); + } + let names = completed_names( + &backend, + &dir, + EDITED_FORM_PATH, + &edited_form("$form['#submit'][] = '::sa<|>"), + 2, + ) + .await; + assert_eq!(names, ["saveTitle"]); +} + +#[tokio::test] +async fn a_form_callback_reads_the_methods_declared_after_the_cursor() { + let (backend, dir) = site().await; + let buffer = FORM.replacen("'::checkTitle';", "'::<|>'", 1); + let names = completed_names(&backend, &dir, FORM_PATH, &buffer, 0).await; + assert_eq!( + names, + [ + "buildForm", + "checkTitle", + "processTitle", + "refresh", + "saveTitle" + ] + ); +} + +#[tokio::test] +async fn a_form_callback_completes_a_traits_methods_and_nothing_outside_a_form() { + let (backend, dir) = site().await; + let buffer = TRAIT.replacen("'::pressButton';", "'::<|>", 1); + let names = completed_names(&backend, &dir, TRAIT_PATH, &buffer, 0).await; + assert_eq!(names, ["addButtons", "pressButton"]); + + let buffer = HOOKS.replacen("'::validate';", "'::<|>", 1); + assert_eq!(completed(&backend, &dir, HOOKS_PATH, &buffer).await, []); +} + +#[tokio::test] +async fn a_form_callback_completes_nothing_where_drupal_does_not_rewrite_it() { + let (backend, dir) = site().await; + for line in [ + "$form['#pre_render'][] = '::<|>", + "$form['x'] = ['#post_render' => ['::<|>", + "$form['x'] = ['#lazy_builder' => ['::<|>", + "$form['#access_callback'] = '::<|>", + "$form['#value_callback'] = '::<|>", + "$form['#markup'] = '::<|>", + "$form['x'] = ['callback' => '::<|>", + "$label = '::<|>", + "$form['#submit'][] .= '::<|>", + "$form['#ajax']['wrapper'] = '::<|>", + "$form['x']['acme_entity'] = '::<|>", + "$form['x'] = ['#lazy_builder' => ['acme_builder' => '::<|>", + "$form['x'] = ['#ajax' => ['wrapper' => '::<|>", + ] { + let found = completed(&backend, &dir, EDITED_FORM_PATH, &edited_form(line)).await; + assert_eq!(found, [], "{line}"); + } +} + +/// A caller in another namespace than [`HELPER`], which imports no +/// `Helper`. +const RENDER_EDIT_PATH: &str = "web/modules/custom/acme/src/Render/Edited.php"; + +fn edited_render(line: &str) -> String { + format!(""), + &["shout"][..], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['#submit'][] = 'Drupal\\acme\\Helper::<|>"), + &["shout", "whisper"], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['#submit'] = ['\\Drupal\\acme\\Helper::<|>"), + &["shout", "whisper"], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['#submit'][] = \"Drupal\\\\acme\\\\Helper::<|>"), + &["shout", "whisper"], + ), + ( + RENDER_EDIT_PATH, + edited_render("return ['#pre_render' => ['Helper::<|>"), + &["shout"], + ), + ( + RENDER_EDIT_PATH, + edited_render("return ['#lazy_builder' => ['Drupal\\acme\\Helper::<|>"), + &["shout", "whisper"], + ), + // A value callback must be a native callable: a static method. + ( + RENDER_EDIT_PATH, + edited_render("return ['#value_callback' => 'Drupal\\acme\\Helper::<|>"), + &[], + ), + ( + RENDER_EDIT_PATH, + edited_render("return ['#value_callback' => 'Helper::<|>"), + &["shout"], + ), + ( + RENDER_EDIT_PATH, + edited_render("return ['#pre_render' => ['Drupal\\acme\\Missing::<|>"), + &[], + ), + ] { + let names = completed_names(&backend, &dir, path, &buffer, 0).await; + assert_eq!(names, expected, "{buffer}"); + } + let names = completed_names( + &backend, + &dir, + RENDER_EDIT_PATH, + &edited_render("return ['#pre_render' => ['Drupal\\acme\\Helper::WH<|>"), + 2, + ) + .await; + assert_eq!(names, ["whisper"]); +} + +#[tokio::test] +async fn a_class_joined_to_a_callback_string_completes_its_methods() { + let (backend, dir) = site().await; + for (path, buffer, expected) in [ + // A class name in code follows the file's imports. + ( + EDITED_FORM_PATH, + edited_form("$form['#submit'][] = Helper::class . '::<|>"), + &["shout", "whisper"][..], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['#submit'] = [static::class . '::<|>"), + &["buildForm", "processTitle", "saveTitle"], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['x']['#ajax']['callback'] = __CLASS__ . '::<|>"), + &["buildForm", "processTitle", "saveTitle"], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['#value_callback'] = self::class . '::<|>"), + &["processTitle"], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['#markup'] = static::class . '::<|>"), + &[], + ), + ( + EDITED_FORM_PATH, + edited_form("$form['#submit'][] = $form_state::class . '::<|>"), + &[], + ), + // Joined to its class, a method of a class that is no form is named + // directly. + ( + HOOKS_PATH, + HOOKS.replacen("'::validate';", "static::class . '::<|>';", 1), + &["formAlter", "validate"], + ), + ] { + let names = completed_names(&backend, &dir, path, &buffer, 0).await; + assert_eq!(names, expected, "{buffer}"); + } +} + +#[tokio::test] +async fn a_function_callback_completes_function_names_as_written_in_a_string() { + let (backend, dir) = site().await; + for (line, typed) in [ + ("$form['#submit'][] = 'acme_log<|>", 8), + ("$form['#submit'] = ['::saveTitle', 'acme_log<|>", 8), + ("$form['#submit'][] = '\\acme_log<|>", 8), + ("$form['x'] = ['#lazy_builder' => ['acme_log<|>", 8), + ("$form['#value_callback'] = 'acme_log<|>", 8), + ] { + let names = + completed_names(&backend, &dir, EDITED_FORM_PATH, &edited_form(line), typed).await; + assert_eq!( + names, + ["Drupal\\acme\\Form\\acme_log_submit", "acme_log_submit"], + "{line}" + ); + } + + // A double-quoted string spells a backslash escaped, both in what it + // inserts and in what was typed. + for (line, typed, expected) in [ + ( + "$form['#submit'][] = \"acme_log<|>", + 8, + &[ + "Drupal\\\\acme\\\\Form\\\\acme_log_submit", + "acme_log_submit", + ][..], + ), + ( + "$form['#submit'][] = \"Drupal\\\\acme\\\\Form\\\\acme_log<|>", + 28, + &["Drupal\\\\acme\\\\Form\\\\acme_log_submit"], + ), + ] { + let names = + completed_names(&backend, &dir, EDITED_FORM_PATH, &edited_form(line), typed).await; + assert_eq!(names, expected, "{line}"); + } + + // A namespaced function is listed by its full name. + let content = edited_form("$form['#submit'][] = 'acme_log"); + let uri = uri_for(&dir, EDITED_FORM_PATH); + crate::common::open_document(&backend, &uri, "php", &content).await; + let position = crate::common::offset_position(&content, content.len() - 1); + let labels = crate::common::response_labels( + crate::common::completion_response(&backend, &uri, position.line, position.character, None) + .await, + ); + assert!( + labels + .iter() + .any(|label| label == "Drupal\\acme\\Form\\acme_log_submit"), + "{labels:?}" + ); +} + +#[tokio::test] +async fn only_the_callback_itself_completes() { + let (backend, dir) = site().await; + for line in [ + "$form['x'] = ['#lazy_builder' => ['acme_log_submit', ['acme_log<|>", + "$form['x'] = ['#lazy_builder' => ['acme_log_submit', 'acme_log<|>", + "$form['x'] = ['#markup' => 'acme_log<|>", + "$form['x'] = ['callback' => 'acme_log<|>", + "$form['#submit'] = 'acme_log<|>", + ] { + let found = completed(&backend, &dir, EDITED_FORM_PATH, &edited_form(line)).await; + assert_eq!(found, [], "{line}"); + } + + // The method string of an array callable is left to the array callable. + let found = completed( + &backend, + &dir, + EDITED_FORM_PATH, + &edited_form("$form['#submit'] = [[$this, '<|>"), + ) + .await; + let names: Vec<&str> = found.iter().map(|(name, _)| name.as_str()).collect(); + assert!(names.contains(&"saveTitle"), "{names:?}"); + assert!(!names.contains(&"acme_log_submit"), "{names:?}"); +} + +const SERVICE_EDIT_PATH: &str = "web/modules/custom/acme/src/Render/EditedCard.php"; + +#[tokio::test] +async fn a_service_callback_completes_the_public_methods_of_the_service_class() { + let (backend, dir) = service_site(false).await; + let card = |line: &str| { + format!(" ['acme.greeting_builder:<|>", + &["build", "preRender"][..], + ), + ( + "return ['#pre_render' => ['acme.greeting_alias:pre<|>", + &["preRender"], + ), + ( + "return ['#value_callback' => 'acme.greeting_builder:<|>", + &[], + ), + ("return ['#pre_render' => ['acme.missing:<|>", &[]), + ] { + let typed = line.len() - line.find(':').unwrap() - 1 - CURSOR.len(); + let names = completed_names(&backend, &dir, SERVICE_EDIT_PATH, &card(line), typed).await; + assert_eq!(names, expected, "{line}"); + } +} From b1691ea54900046e42d70e574aef9bc588bbe42b Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Tue, 10 Nov 2026 19:46:13 +0100 Subject: [PATCH 4/6] Warn on Drupal callbacks that cannot work In a Drupal project, a callback in a form or render array's callback keys that cannot work is now reported. A callback naming an unknown method, function or class gets the usual unknown-member, unknown-function or unknown-class warning, array callables included, while array callables outside callback keys stay unchecked. A callback naming a private or protected method is reported as one Drupal cannot call from outside the class. '::method' in a render callback, which Drupal cannot resolve, and a value callback that is not a native callable, which Drupal ignores, get the new invalid_drupal_callback warning. '::method' outside a form, a method a trait lacks, and a name that is a class or a service stay silent. The playground's greeting form says how to see the warnings. Assisted-by: claude-code/claude-opus-5-5 --- docs/diagnostics.md | 1 + examples/drupal/README.md | 5 +- examples/drupal/assertions.php | 10 + .../custom/acme/src/Form/GreetingForm.php | 11 +- src/diagnostics/collect.rs | 4 + src/diagnostics/deprecated.rs | 11 +- src/diagnostics/drupal_callbacks.rs | 185 +++++ src/diagnostics/existence_guards.rs | 6 +- src/diagnostics/mod.rs | 1 + src/diagnostics/unknown_functions.rs | 39 +- src/diagnostics/unknown_members/access.rs | 26 +- .../unknown_members/member_check.rs | 10 +- src/diagnostics/unknown_members/mod.rs | 15 +- src/drupal/forms.rs | 25 +- src/drupal/services.rs | 52 ++ src/mem_audit.rs | 3 + src/symbol_map/extraction/drupal.rs | 104 ++- src/symbol_map/extraction/mod.rs | 6 + src/symbol_map/map.rs | 4 + src/symbol_map/string_keys.rs | 39 + tests/integration/drupal_callbacks.rs | 689 ++++++++++++++++-- 21 files changed, 1156 insertions(+), 90 deletions(-) create mode 100644 src/diagnostics/drupal_callbacks.rs diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 61393fe7c..054e14c64 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -188,6 +188,7 @@ These are shown dimmed rather than underlined, except `unwritten_property`. | `invalid_drupal_service` | Warning | A service ID no services file declares and no PHP code may define. | | `invalid_drupal_plugin` | Warning | A plugin ID no plugin of its type declares and no PHP code may add. | | `invalid_drupal_render_element` | Warning | A render element `#type` no element class declares. | +| `invalid_drupal_callback` | Warning | A form or render callback Drupal cannot call: `'::method'` in a render callback, an array callable that names a non-static method by its class, or a value callback that is not a native callable. | ## External tools diff --git a/examples/drupal/README.md b/examples/drupal/README.md index 0f84e984d..a419e89b5 100644 --- a/examples/drupal/README.md +++ b/examples/drupal/README.md @@ -164,7 +164,10 @@ Run `composer install` here first. Composer puts core and contrib into references of a callback method, or rename it, and the strings follow. Complete inside a callback string: after `'::` the form's public methods are offered, after `'Class::` the class's, after `'service:` the service - class's, and before any colon the functions. + class's, and before any colon the functions. A callback Drupal cannot + call is reported: misspell `'::validateName'`, make `validateName` + private, or make `trimName` non-static, which Drupal ignores as a value + callback. A `'service:method'` callback leads to the method of the service's class: in `card()` in `web/modules/custom/acme/src/Controller/GreetingController.php`, go to diff --git a/examples/drupal/assertions.php b/examples/drupal/assertions.php index 5dfc5466a..2bc978e56 100644 --- a/examples/drupal/assertions.php +++ b/examples/drupal/assertions.php @@ -459,6 +459,16 @@ protected function getDefaultLanguageValues() check("Drupal can call GreetingForm's $callback", is_callable($greetingFormState->prepareCallback($callback))); } check("FormState rewrites '::validateName' as a call on the form object", $greetingFormState->prepareCallback('::validateName') === [$greetingForm, 'validateName']); +// A value callback must be a native callable: a static method named by its +// class is one, and an instance method named by its class or '::method' is +// not. +check('the value callback trimName is a native callable', is_callable(GreetingForm::class . '::trimName')); +check('an instance method named by its class is no native callable', !is_callable(GreetingForm::class . '::validateName')); +check("'::trimName' is no native callable", !is_callable('::trimName')); +// Drupal calls a callback from outside the form, where only a public +// method is callable. +check('validateName is public', (new ReflectionMethod(GreetingForm::class, 'validateName'))->isPublic()); +check('a private method is not callable from outside its class', !is_callable([new class { public function run(): void { $this->hidden(); } private function hidden(): void {} }, 'hidden'])); check('GreetingForm is a form', $greetingForm instanceof FormInterface); // The card's lazy builder names a method of the acme.greeter service, which diff --git a/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php b/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php index 8328d2b0d..8b06a01e2 100644 --- a/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php +++ b/examples/drupal/web/modules/custom/acme/src/Form/GreetingForm.php @@ -28,13 +28,17 @@ public function buildForm(array $form, FormStateInterface $form_state): array // callback on the form object. Find the references of // validateName(), or rename it, and the string follows. Delete // validateName and complete after the `::`: the form's public - // methods are offered. + // methods are offered. Misspell validateName, or make the method + // private, and the callback is reported: Drupal calls it from + // outside the form. $form['#validate'][] = '::validateName'; $form['name'] = [ '#type' => 'textfield', '#title' => 'Name', // Try: hover trimName. A class name joined to '::method' reads - // as one 'Class::method'. + // as one 'Class::method'. Make trimName non-static, or write + // '::trimName': Drupal ignores a value callback that is not a + // native callable, and the callback is reported. '#value_callback' => static::class . '::trimName', // Try: go to the definition of refreshGreeting, the callback // the `#ajax` array holds. @@ -49,7 +53,8 @@ public function buildForm(array $form, FormStateInterface $form_state): array '#value' => 'Greet', // Try: go to the definition of acme_greeting_form_submit, a // function of acme.module. A function name in a callback string - // is global, whatever namespace the file is in. + // is global, whatever namespace the file is in. Misspell it, and + // it is reported. '#submit' => ['::submitForm', 'acme_greeting_form_submit'], ]; diff --git a/src/diagnostics/collect.rs b/src/diagnostics/collect.rs index 729bb44ff..874b5cb01 100644 --- a/src/diagnostics/collect.rs +++ b/src/diagnostics/collect.rs @@ -232,6 +232,10 @@ static SLOW_COLLECTORS: &[SlowCollector] = &[ "invalid_drupal_route_parameter", Backend::collect_drupal_route_parameter_diagnostics, ), + always( + "invalid_drupal_callback", + Backend::collect_drupal_callback_diagnostics, + ), SlowCollector { name: "framework string keys", collect: Backend::collect_invalid_laravel_string_key_diagnostics, diff --git a/src/diagnostics/deprecated.rs b/src/diagnostics/deprecated.rs index 90c6b0251..0d7efd369 100644 --- a/src/diagnostics/deprecated.rs +++ b/src/diagnostics/deprecated.rs @@ -250,13 +250,16 @@ impl Backend { continue; } // A form callback's `'::method'` names a method only of a - // form. + // form, and only under a key Drupal looks it up for. if *docblock_ref == crate::symbol_map::DocblockMemberRef::FormCallback - && crate::drupal::forms::form_callback_classes( - vec![Arc::clone(&base_class)], + && (!crate::drupal::forms::names_own_method( + &base_class, resolved_class_loader, + ) || crate::drupal::forms::callback_at( + &symbol_map.drupal_callbacks, + span.start, ) - .is_empty() + .is_some_and(|site| !crate::drupal::forms::looks_up_method(site))) { continue; } diff --git a/src/diagnostics/drupal_callbacks.rs b/src/diagnostics/drupal_callbacks.rs new file mode 100644 index 000000000..1a2d01d07 --- /dev/null +++ b/src/diagnostics/drupal_callbacks.rs @@ -0,0 +1,185 @@ +//! Drupal form and render callbacks Drupal cannot call (see +//! [`crate::drupal::forms`]). +//! +//! Drupal resolves `'::method'` for the form only in a form callback: in a +//! render callback it names no class and throws. It calls a +//! `#value_callback` only when it is a native callable, and otherwise +//! ignores it for the element's default value callback, so `'::method'`, +//! `'service:method'` and a non-static method named by its class do +//! nothing there. An array callable that names its class rather than an +//! object calls its method statically, under every key, so it must name a +//! static method. The class a `'Class::method'` string names has no class +//! span of its own, so a missing one is reported here; a class name +//! written in code (`X::class . '::method'`) is reported where it is +//! written. The methods and functions a callback names are checked by +//! the unknown-member and unknown-function checks. + +use tower_lsp_server::gen_lsp_types::{Diagnostic, DiagnosticSeverity}; + +use crate::Backend; +use crate::symbol_map::{CallbackKey, CallbackShape, SymbolKind}; +use crate::type_engine::resolver::{SubjectOutcome, resolve_subject_outcome}; +use crate::types::AccessKind; +use crate::virtual_members::resolve_class_fully_cached; + +use super::helpers::{FileDiagnosticContext, make_diagnostic}; +use super::unknown_classes::UNKNOWN_CLASS_CODE; + +/// Diagnostic code for a callback Drupal cannot resolve or ignores. +pub(crate) const INVALID_DRUPAL_CALLBACK_CODE: &str = "invalid_drupal_callback"; + +impl Backend { + /// Report the callbacks the file's form and render arrays name that + /// Drupal cannot resolve under their key, ignores, or whose class does + /// not exist. + pub(crate) fn collect_drupal_callback_diagnostics( + &self, + ctx: &FileDiagnosticContext, + uri: &str, + content: &str, + out: &mut Vec, + ) { + let map = &ctx.symbol_map; + if map.drupal_callbacks.is_empty() { + return; + } + let Some(source) = map.source(content) else { + return; + }; + let loaders = self.file_loaders(&ctx.file); + let push = |out: &mut Vec, start: u32, end: u32, code: &str, message| { + if let Some(range) = + self.offset_range_to_lsp_range(uri, content, start as usize, end as usize) + { + out.push(make_diagnostic( + range, + DiagnosticSeverity::Warning, + code, + message, + )); + } + }; + let services = std::cell::OnceCell::new(); + // The method `subject::method` names, written at `at`, when it is + // not static. + let instance_method = |subject: &str, method: &str, at: u32| { + let rctx = loaders.resolution_ctx_at(content, at); + let SubjectOutcome::Resolved { classes, .. } = + resolve_subject_outcome(subject, AccessKind::DoubleColon, &rctx) + else { + return None; + }; + classes.iter().find_map(|class| { + let merged = resolve_class_fully_cached( + class, + loaders.resolved_class_loader(), + &self.resolved_class_cache, + ); + let found = merged + .methods + .iter() + .find(|m| m.name.eq_ignore_ascii_case(method))?; + (!found.is_static).then(|| format!("{}::{}()", merged.fqn(), found.name)) + }) + }; + for site in &map.drupal_callbacks { + if !super::incremental::reports_site(site.start) { + continue; + } + let at = map.spans.partition_point(|span| span.start < site.start); + let Some((span, subject, method, is_static)) = map.spans[at..] + .iter() + .take_while(|span| span.start == site.start) + .find_map(|span| match &span.kind { + SymbolKind::MemberAccess { + subject_text, + member_name, + is_static, + .. + } => Some((span, subject_text.as_str(source), member_name, *is_static)), + _ => None, + }) + else { + continue; + }; + match site.shape { + CallbackShape::FormMethod if site.key == CallbackKey::Render => push( + out, + span.start, + span.end, + INVALID_DRUPAL_CALLBACK_CODE, + format!( + "Drupal cannot resolve '::{method}' in a render callback, only in a form callback" + ), + ), + CallbackShape::FormMethod | CallbackShape::ServiceMethod + if site.key == CallbackKey::Value => + { + push( + out, + span.start, + span.end, + INVALID_DRUPAL_CALLBACK_CODE, + ignored_value_callback(None), + ); + } + CallbackShape::ClassMethod { class } + if !self.drupal_callback_names_invokable(subject, &services) => + { + let (start, end) = class.unwrap_or((span.start, span.end)); + push( + out, + start, + end, + UNKNOWN_CLASS_CODE, + format!("Class {} not found", subject.trim_start_matches('\\')), + ); + } + CallbackShape::ClassMethod { .. } | CallbackShape::JoinedMethod + if site.key == CallbackKey::Value => + { + if let Some(instance_method) = instance_method(subject, method, span.start) { + push( + out, + span.start, + span.end, + INVALID_DRUPAL_CALLBACK_CODE, + ignored_value_callback(Some(&instance_method)), + ); + } + } + // An array callable that names its class calls the method + // statically under every key. + CallbackShape::ArrayCallable if is_static => { + if let Some(instance_method) = instance_method(subject, method, span.start) { + let message = if site.key == CallbackKey::Value { + ignored_value_callback(Some(&instance_method)) + } else { + format!( + "Drupal cannot call this callback: {instance_method} is not static" + ) + }; + push( + out, + span.start, + span.end, + INVALID_DRUPAL_CALLBACK_CODE, + message, + ); + } + } + _ => {} + } + } + } +} + +/// The message for a value callback Drupal ignores, naming the method when +/// it is ignored for not being static. +fn ignored_value_callback(instance_method: Option<&str>) -> String { + let reason = match instance_method { + Some(method) => format!(", and {method} is not static"), + None => String::new(), + }; + format!("This value callback is ignored: Drupal calls only a native callable there{reason}") +} diff --git a/src/diagnostics/existence_guards.rs b/src/diagnostics/existence_guards.rs index 0fdec7aa1..0d3c86216 100644 --- a/src/diagnostics/existence_guards.rs +++ b/src/diagnostics/existence_guards.rs @@ -123,7 +123,11 @@ pub(crate) fn compute_existence_guards(content: &str) -> ExistenceGuards { return; }; let (map, key) = match kind { - ExistenceKind::Function => (&mut guards.function_guards, name.to_lowercase()), + // `function_exists()` ignores a leading `\`. + ExistenceKind::Function => ( + &mut guards.function_guards, + name.strip_prefix('\\').unwrap_or(&name).to_lowercase(), + ), ExistenceKind::Class => (&mut guards.class_guards, name), ExistenceKind::Method => (&mut guards.method_guards, name.to_lowercase()), }; diff --git a/src/diagnostics/mod.rs b/src/diagnostics/mod.rs index df734a379..5c977e172 100644 --- a/src/diagnostics/mod.rs +++ b/src/diagnostics/mod.rs @@ -286,6 +286,7 @@ mod destructuring_offsets; mod discarded_results; mod docblock_native_mismatch; pub(crate) mod dql_syntax; +mod drupal_callbacks; mod drupal_route_parameters; mod dynamic_member_names; mod enum_errors; diff --git a/src/diagnostics/unknown_functions.rs b/src/diagnostics/unknown_functions.rs index 7b5c68479..d48c532cd 100644 --- a/src/diagnostics/unknown_functions.rs +++ b/src/diagnostics/unknown_functions.rs @@ -20,6 +20,7 @@ use tower_lsp_server::gen_lsp_types::*; use crate::Backend; use crate::symbol_map::SymbolKind; +use crate::util::strip_fqn_prefix; use super::existence_guards::compute_existence_guards; use super::helpers::{FileDiagnosticContext, is_offset_in_ranges, make_diagnostic}; @@ -93,8 +94,8 @@ impl Backend { // ── Collect local function definition names ───────────────────── // Functions defined in the same file are always resolvable even // before they appear in global_functions (hoisting). Collect - // both short names and FQN forms. - let local_function_names: Vec = symbol_map + // both short names and FQN forms, the FQN last. + let local_function_names: Vec> = symbol_map .spans .iter() .filter_map(|span| match &span.kind { @@ -111,21 +112,24 @@ impl Backend { } _ => None, }) - .flatten() .collect(); + // The Drupal site's service IDs, read when a callback first needs + // them. + let drupal_services = std::cell::OnceCell::new(); + // ── Walk every symbol span ────────────────────────────────────── for span in &symbol_map.spans { if !super::incremental::reports_site(span.start) { continue; } - let (name, is_docblock_reference) = match &span.kind { + let (name, is_docblock_reference, is_callback) = match &span.kind { SymbolKind::FunctionCall { name, is_definition: false, is_docblock_reference, - is_callback: false, - } => (name, *is_docblock_reference), + is_callback, + } => (name, *is_docblock_reference, *is_callback), _ => continue, }; @@ -150,8 +154,17 @@ impl Backend { continue; } - // Skip names that match a local function definition. - if local_function_names.iter().any(|n| n == name) { + // Skip names that match a local function definition. A + // callback's name is fully qualified, so only an FQN matches it. + if local_function_names.iter().any(|names| { + if is_callback { + names + .last() + .is_some_and(|fqn| fqn == name.trim_start_matches('\\')) + } else { + names.iter().any(|n| n == name) + } + }) { continue; } @@ -174,7 +187,15 @@ impl Backend { } // ── Skip functions guarded by function_exists() ────────────── - if existence_guards.is_function_guarded(name, span.start) { + // A callback's name keeps the leading `\` that makes it global, + // which the guarded name does not spell. + if existence_guards.is_function_guarded(strip_fqn_prefix(name), span.start) { + continue; + } + + // A Drupal callback that names a class or a service rather than + // a function names an invokable. + if is_callback && self.drupal_callback_names_invokable(name, &drupal_services) { continue; } diff --git a/src/diagnostics/unknown_members/access.rs b/src/diagnostics/unknown_members/access.rs index 6d7c5ee11..b00ef0b54 100644 --- a/src/diagnostics/unknown_members/access.rs +++ b/src/diagnostics/unknown_members/access.rs @@ -23,6 +23,8 @@ pub(super) struct AccessFilters<'a> { /// Where the method names of the array callables known to be called /// start, in order: the listeners of a Yii events file. pub(super) called_array_callables: Vec, + /// The callbacks the file's Drupal form and render arrays name. + pub(super) drupal_callbacks: &'a [crate::symbol_map::DrupalCallbackSite], } /// One member access the check judges. @@ -63,6 +65,13 @@ pub(super) struct MemberAccessSite<'a> { /// only when it resolves to something other than the trait: a member /// the chain lands back on the trait for is one the host provides. pub(super) trait_self_chain: bool, + /// Whether the member is the method a Drupal callback names, which + /// Drupal calls from outside every class. + pub(super) drupal_callback: bool, + /// Whether the member is the method a Drupal form callback's + /// `'::method'` names, which is checked only when the class it is + /// written in is a form (see [`crate::drupal::forms`]). + pub(super) form_callback: bool, } impl<'a> MemberAccessSite<'a> { @@ -87,10 +96,15 @@ impl<'a> MemberAccessSite<'a> { // Without type-flow analysis we cannot tell such an array apart // from a plain data pair like `return [[Foo::class, 'name'], ...]`, // so we do not validate its second element as a method, unless the - // file is known to call it. The span still drives navigation, + // file is known to call it, as Drupal calls the callbacks its form + // and render arrays name. The span still drives navigation, // hover, and semantic tokens, which only surface information when // the member actually resolves. + let drupal_callback = *is_array_callable + && crate::drupal::forms::callback_at(filters.drupal_callbacks, span.start) + .is_some_and(crate::drupal::forms::looks_up_method); if *is_array_callable + && !drupal_callback && filters .called_array_callables .binary_search(&span.start) @@ -159,6 +173,10 @@ impl<'a> MemberAccessSite<'a> { return None; } let trait_self_chain = in_trait && subject_text_is_rooted_in_self(subject_text); + // A form callback's `'::method'` is a call Drupal makes on the form, + // not a name a docblock gives. + let form_callback = *docblock_ref == DocblockMemberRef::FormCallback; + let is_docblock_ref = docblock_ref.is_reference() && !form_callback; Some(Self { start: span.start, @@ -178,11 +196,11 @@ impl<'a> MemberAccessSite<'a> { .as_bytes() .get(span.start.saturating_sub(1) as usize..=span.start as usize) .is_some_and(|bytes| bytes.contains(&b'$')), - is_docblock_ref: docblock_ref.is_reference(), + is_docblock_ref, // A Yii form field or hydration map reads or writes a property // by reflection, which a method or a constant cannot stand in // for, though its visibility does not matter. - relaxed_lookup: docblock_ref.is_reference() + relaxed_lookup: is_docblock_ref && !matches!(docblock_ref, DocblockMemberRef::YiiProperty { .. }), is_nullsafe: *is_nullsafe, mock_expectation: *docblock_ref == DocblockMemberRef::MockedMethod, @@ -192,6 +210,8 @@ impl<'a> MemberAccessSite<'a> { == DocblockMemberRef::YiiProperty { form_model: true }, current_class, trait_self_chain, + drupal_callback, + form_callback, }) } diff --git a/src/diagnostics/unknown_members/member_check.rs b/src/diagnostics/unknown_members/member_check.rs index f7aad5ea0..171ace51d 100644 --- a/src/diagnostics/unknown_members/member_check.rs +++ b/src/diagnostics/unknown_members/member_check.rs @@ -229,13 +229,19 @@ impl UnknownMemberPass<'_> { if access.is_docblock_ref { return false; } + // Drupal calls a callback from outside every class. + let (current_class, binds_scope) = if access.drupal_callback { + (None, false) + } else { + (access.current_class, access.subject_binds_scope()) + }; let Some(message) = inaccessible_member_message( classes, access.member_name, access.is_static, access.is_method_call, - access.current_class, - access.subject_binds_scope(), + current_class, + binds_scope, self.class_loader(), ) else { return false; diff --git a/src/diagnostics/unknown_members/mod.rs b/src/diagnostics/unknown_members/mod.rs index 078bcb0c8..e5ed136a1 100644 --- a/src/diagnostics/unknown_members/mod.rs +++ b/src/diagnostics/unknown_members/mod.rs @@ -212,6 +212,7 @@ impl Backend { existence_guards: compute_existence_guards(content), isset_empty_ranges: compute_isset_empty_argument_ranges(content), called_array_callables: self.yii_listener_method_offsets(uri, content), + drupal_callbacks: &ctx.symbol_map.drupal_callbacks, }; // ── Parse cache for this diagnostic pass ──────────────────────── @@ -237,6 +238,17 @@ impl Backend { let Some(access) = MemberAccessSite::of_span(span, &filters) else { continue; }; + // `'::method'` names a method of the form object, even in a static + // method, and outside a form a method of a form the code does + // not know. + if access.form_callback { + if access.current_class.is_some_and(|class| { + crate::drupal::forms::names_own_method(class, pass.class_loader()) + }) { + pass.report(&access, &pass.resolve_subject(&access), out); + } + continue; + } // ── Look up or populate the subject cache ─────────────────── let cache_key = SubjectCacheKey::build( @@ -284,7 +296,8 @@ impl UnknownMemberPass<'_> { /// Resolve the access's subject at the access's own position. fn resolve_subject(&self, access: &MemberAccessSite) -> SubjectOutcome { let rctx = ResolutionCtx { - is_in_static_method: self.ctx.symbol_map.is_in_static_method(access.start), + is_in_static_method: !access.form_callback + && self.ctx.symbol_map.is_in_static_method(access.start), ..self.loaders.resolution_ctx_at(self.content, access.start) }; resolve_subject_outcome(access.subject_text, access.access_kind(), &rctx) diff --git a/src/drupal/forms.rs b/src/drupal/forms.rs index 41dd6d9df..30fcea646 100644 --- a/src/drupal/forms.rs +++ b/src/drupal/forms.rs @@ -12,6 +12,7 @@ use std::sync::Arc; use crate::class_lookup::{Fqn, ResolvedClassLoader, is_subtype_of}; +use crate::symbol_map::{CallbackKey, CallbackShape, DrupalCallbackSite}; use crate::types::{ClassInfo, ClassLikeKind}; /// The keys of a form or render array that hold a list of callbacks. @@ -52,7 +53,7 @@ pub(crate) const RENDER_CALLBACK_KEYS: [&str; 4] = [ const FORM_INTERFACE: &str = "Drupal\\Core\\Form\\FormInterface"; /// Whether `'::method'` written in `class` names a method of it. -fn names_own_method(class: &ClassInfo, class_loader: &ResolvedClassLoader<'_>) -> bool { +pub(crate) fn names_own_method(class: &ClassInfo, class_loader: &ResolvedClassLoader<'_>) -> bool { class.kind == ClassLikeKind::Trait || is_subtype_of(class, FORM_INTERFACE, class_loader) } @@ -66,6 +67,28 @@ pub(crate) fn form_callback_classes( classes } +/// Whether Drupal looks up the method the callback `site` names: +/// `'::method'` only under a form callback key, and a service's method +/// anywhere but under `#value_callback`. +pub(crate) fn looks_up_method(site: &DrupalCallbackSite) -> bool { + match site.shape { + CallbackShape::FormMethod => site.key == CallbackKey::Form, + CallbackShape::ServiceMethod => site.key != CallbackKey::Value, + CallbackShape::ClassMethod { .. } + | CallbackShape::JoinedMethod + | CallbackShape::ArrayCallable => true, + } +} + +/// The callback among `sites`, sorted by start, whose method span starts +/// at `start`. +pub(crate) fn callback_at(sites: &[DrupalCallbackSite], start: u32) -> Option<&DrupalCallbackSite> { + sites + .binary_search_by_key(&start, |site| site.start) + .ok() + .map(|at| &sites[at]) +} + /// [`form_callback_classes`] for classes known by name. pub(crate) fn form_callback_class_names( mut fqns: Vec, diff --git a/src/drupal/services.rs b/src/drupal/services.rs index b76784db0..00c3b2a79 100644 --- a/src/drupal/services.rs +++ b/src/drupal/services.rs @@ -385,6 +385,29 @@ impl PhpServiceIds { } } +/// The service IDs a Drupal site's services files declare, sorted, and what +/// its PHP code may declare (see [`Backend::drupal_service_ids`]). +pub(crate) struct DrupalServiceIds { + declared: Vec, + php: Arc, +} + +impl DrupalServiceIds { + /// Whether the site may declare the service `id`, or `None` when its + /// services files were not read. + fn may_declare(&self, id: &str) -> Option { + if self.declared.is_empty() { + return None; + } + Some( + self.declared + .binary_search_by(|name| name.as_str().cmp(id)) + .is_ok() + || self.php.declares(id), + ) + } +} + /// What a file the web-root walk found may define: a test module's /// services file declares the IDs it lists, a PHP file what /// [`defined_service_ids`] reads. @@ -420,6 +443,35 @@ impl Backend { known.extend(files.iter().map(|path| crate::util::path_to_uri(path))); } + /// The service IDs the Drupal site declares. Core's and contributed + /// modules' services files are only read once the workspace index has + /// walked the folders `.gitignore` leaves out. + pub(crate) fn drupal_service_ids(&self) -> DrupalServiceIds { + self.ensure_workspace_index_ready_for_request(); + DrupalServiceIds { + declared: self.symfony_declared_names(crate::symbol_map::StringKeyKind::ServiceId), + php: self.drupal_php_service_ids(), + } + } + + /// Whether the name `name` a callback gives, which names no function, + /// names a class or a service, which Drupal calls as an invokable, or + /// may name one the site's unread services files declare. `services` + /// holds the site's service IDs once a name needs them, so a diagnostic + /// pass reads them at most once. + pub(crate) fn drupal_callback_names_invokable( + &self, + name: &str, + services: &std::cell::OnceCell, + ) -> bool { + let name = name.trim_start_matches('\\'); + self.find_or_load_class(name).is_some() + || services + .get_or_init(|| self.drupal_service_ids()) + .may_declare(name) + != Some(false) + } + /// What the files that may define services define, read on first use. pub(crate) fn drupal_php_service_ids(&self) -> Arc { if let Some(ids) = self.drupal.php_service_ids.read().as_ref() { diff --git a/src/mem_audit.rs b/src/mem_audit.rs index 44f28cd6b..9d654f90a 100644 --- a/src/mem_audit.rs +++ b/src/mem_audit.rs @@ -1437,6 +1437,9 @@ pub(crate) fn report(backend: &Backend, runner_content_bytes: usize) { for site in &sm.drupal_computed_hooks { sym.add(site.shape.capacity()); } + sym.add( + sm.drupal_callbacks.capacity() * size_of::(), + ); for name in sm .drupal_route_patterns .iter() diff --git a/src/symbol_map/extraction/drupal.rs b/src/symbol_map/extraction/drupal.rs index 15d6e74f2..5ce9b8b27 100644 --- a/src/symbol_map/extraction/drupal.rs +++ b/src/symbol_map/extraction/drupal.rs @@ -5,14 +5,17 @@ //! [`crate::drupal`]). use super::*; -use crate::drupal::forms::{AJAX, AJAX_CALLBACK, CALLBACK_KEYS, CALLBACK_LIST_KEYS, LAZY_BUILDER}; +use crate::drupal::forms::{ + AJAX, AJAX_CALLBACK, CALLBACK_KEYS, CALLBACK_LIST_KEYS, LAZY_BUILDER, RENDER_CALLBACK_KEYS, + VALUE_CALLBACK, +}; use crate::symbol_map::extraction::symfony::{ RouteDeclaration, RouteName, is_route_attribute, push_route_spans, route_declarations, }; use crate::symbol_map::{ - DeclaredParameter, DrupalRouteSite, EntityTypeSite, ModuleGuard, PluginClassSite, - PluginDeclarationSite, PluginManagerSite, ReceiverClass, StaticPluginSite, StringKeyKind, - TypedReceiverSite, + CallbackKey, CallbackShape, DeclaredParameter, DrupalCallbackSite, DrupalRouteSite, + EntityTypeSite, ModuleGuard, PluginClassSite, PluginDeclarationSite, PluginManagerSite, + ReceiverClass, StaticPluginSite, StringKeyKind, TypedReceiverSite, }; use crate::virtual_members::laravel::helpers::resolved_string_literal; use mago_syntax::cst::sequence::TokenSeparatedSequence; @@ -2824,17 +2827,21 @@ pub(in crate::symbol_map::extraction) fn emit_drupal_callback_assignment( && let Some((key, _, _)) = resolved_string_literal(access.index, ctx.content) && CALLBACK_LIST_KEYS.contains(&key) { - push_callback(assign.rhs, ctx); + push_callback(assign.rhs, callback_key(key), ctx); } } Expression::ArrayAccess(access) => { let Some((key, _, _)) = resolved_string_literal(access.index, ctx.content) else { return; }; - if key == AJAX_CALLBACK { - if accesses_keys(access.array, &[AJAX], ctx.content) { - push_callback(assign.rhs, ctx); - } + if key == AJAX_CALLBACK && accesses_keys(access.array, &[AJAX], ctx.content) { + push_callback(assign.rhs, CallbackKey::Form, ctx); + } else if let Expression::ArrayAccess(list) = access.array + && let Some((list_key, _, _)) = resolved_string_literal(list.index, ctx.content) + && CALLBACK_LIST_KEYS.contains(&list_key) + { + // `$form['#entity_builders']['name'] = …`, a keyed entry. + push_callback(assign.rhs, callback_key(list_key), ctx); } else { push_keyed_callbacks(key, assign.rhs, ctx); } @@ -2843,10 +2850,21 @@ pub(in crate::symbol_map::extraction) fn emit_drupal_callback_assignment( } } +/// How Drupal calls the callbacks under the callback key `key`. +fn callback_key(key: &str) -> CallbackKey { + if key == VALUE_CALLBACK { + CallbackKey::Value + } else if RENDER_CALLBACK_KEYS.contains(&key) { + CallbackKey::Render + } else { + CallbackKey::Form + } +} + /// Record the callbacks `value`, written under `key`, names. fn push_keyed_callbacks(key: &str, value: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { if CALLBACK_KEYS.contains(&key) { - push_callback(value, ctx); + push_callback(value, callback_key(key), ctx); return; } let lazy_builder = key == LAZY_BUILDER; @@ -2858,11 +2876,16 @@ fn push_keyed_callbacks(key: &str, value: &Expression<'_>, ctx: &mut ExtractionC }; for entry in entries.iter() { match entry { - ArrayElement::Value(item) if key != AJAX => push_callback(item.value, ctx), + ArrayElement::Value(item) if key != AJAX => { + push_callback(item.value, callback_key(key), ctx); + } + ArrayElement::KeyValue(entry) if !lazy_builder && key != AJAX => { + push_callback(entry.value, callback_key(key), ctx); + } ArrayElement::KeyValue(entry) if key == AJAX && is_literal_key(entry.key, AJAX_CALLBACK, ctx.content) => { - push_callback(entry.value, ctx); + push_callback(entry.value, CallbackKey::Form, ctx); } _ => {} } @@ -2875,13 +2898,24 @@ fn push_keyed_callbacks(key: &str, value: &Expression<'_>, ctx: &mut ExtractionC /// Record what one callback names: a method of the form for `'::method'`, /// a method of the class for `'Class::method'` or a class name joined to /// `'::method'`, a service and a method of its class for -/// `'service:method'`, and a function for a name without a colon. An array -/// callable is read wherever it is written. -fn push_callback(callback: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { +/// `'service:method'`, and a function for a name without a colon, each +/// method under `key`. An array callable is read wherever it is written, +/// so only its key is recorded here. +fn push_callback(callback: &Expression<'_>, key: CallbackKey, ctx: &mut ExtractionCtx<'_>) { if let Expression::Binary(binary) = callback && binary.operator.is_concatenation() { - push_joined_callback(binary.lhs, binary.rhs, ctx); + push_joined_callback(binary.lhs, binary.rhs, key, ctx); + return; + } + if let Some(elements) = crate::parser::array_literal_elements(callback) { + let mut items = elements.iter(); + if let (Some(ArrayElement::Value(_)), Some(ArrayElement::Value(method)), None) = + (items.next(), items.next(), items.next()) + && let Some((_, start, _)) = resolved_string_literal(method.value, ctx.content) + { + push_callback_site(start as u32, key, CallbackShape::ArrayCallable, ctx); + } return; } let Some((value, start, end)) = resolved_string_literal(callback, ctx.content) else { @@ -2901,23 +2935,31 @@ fn push_callback(callback: &Expression<'_>, ctx: &mut ExtractionCtx<'_>) { method_start, ctx, ); + push_callback_site(method_start, key, CallbackShape::FormMethod, ctx); return; } // A class name in a string is a runtime name, which is fully - // qualified whether or not it says so. + // qualified whether or not it says so. Drupal calls the method of + // an instance of the class unless the string is a native callable, + // which only `#value_callback` requires. let class = class.strip_prefix('\\').unwrap_or(class); if is_qualified_name(class) { push_callback_method( SubjectText::owned(format!("\\{class}")), - true, + false, DocblockMemberRef::No, method, method_start, ctx, ); + let class_end = method_start as usize - 2; + let class_start = class_end.saturating_sub(class.len()); + let spelled = ctx.content.get(class_start..class_end) == Some(class); + let class = spelled.then_some((class_start as u32, class_end as u32)); + push_callback_site(method_start, key, CallbackShape::ClassMethod { class }, ctx); } } else if let Some((service, method)) = value.split_once(':') { - push_service_callback(service, method, start, end, ctx); + push_service_callback(service, method, start, end, key, ctx); } else { let name = value.strip_prefix('\\').unwrap_or(value); if is_qualified_name(name) { @@ -2944,6 +2986,7 @@ fn push_service_callback( method: &str, start: usize, end: usize, + key: CallbackKey, ctx: &mut ExtractionCtx<'_>, ) { if !crate::drupal::routing::is_plain_name(service) @@ -2963,14 +3006,16 @@ fn push_service_callback( is_optional: false, }, }); + let method_start = (end - method.len()) as u32; push_callback_method( SubjectText::owned(crate::drupal::routing::service_subject(service)), false, DocblockMemberRef::No, method, - (end - method.len()) as u32, + method_start, ctx, ); + push_callback_site(method_start, key, CallbackShape::ServiceMethod, ctx); } /// Record the method `X::class . '::method'`, `static::class . '::method'`, @@ -2979,6 +3024,7 @@ fn push_service_callback( fn push_joined_callback( class: &Expression<'_>, method: &Expression<'_>, + key: CallbackKey, ctx: &mut ExtractionCtx<'_>, ) { let Some((value, _, end)) = resolved_string_literal(method, ctx.content) else { @@ -3007,14 +3053,28 @@ fn push_joined_callback( } _ => return, }; + let method_start = (end - name.len()) as u32; + // Read as `'Class::method'`, which Drupal calls on an instance. push_callback_method( subject, - true, + false, DocblockMemberRef::No, name, - (end - name.len()) as u32, + method_start, ctx, ); + push_callback_site(method_start, key, CallbackShape::JoinedMethod, ctx); +} + +/// Record that the method span at `start` is a callback under `key`. +fn push_callback_site( + start: u32, + key: CallbackKey, + shape: CallbackShape, + ctx: &mut ExtractionCtx<'_>, +) { + ctx.drupal_callbacks + .push(DrupalCallbackSite { start, key, shape }); } /// Record the method `name`, at `start`, of `subject` that a callback diff --git a/src/symbol_map/extraction/mod.rs b/src/symbol_map/extraction/mod.rs index 6255178bf..67d43222f 100644 --- a/src/symbol_map/extraction/mod.rs +++ b/src/symbol_map/extraction/mod.rs @@ -132,6 +132,7 @@ struct ExtractionCtx<'a> { drupal_routes: Vec, drupal_hooks: Vec, drupal_computed_hooks: Vec, + drupal_callbacks: Vec, /// What the file holds of Drupal hooks, which its path says. drupal_file: crate::drupal::hooks::DrupalFile, /// A procedural function with `#[ProceduralHookScanStop]` was read: @@ -641,6 +642,7 @@ fn extract_symbol_map_inner( drupal_routes: Vec::new(), drupal_hooks: Vec::new(), drupal_computed_hooks: Vec::new(), + drupal_callbacks: Vec::new(), drupal_file, drupal_hook_scan_stopped: false, cond_nesting_depth: 0, @@ -831,6 +833,9 @@ fn extract_symbol_map_inner( ctx.drupal_hooks.sort_by_key(|s| s.start); ctx.tempest_uri_calls.sort_unstable(); ctx.drupal_hooks.dedup_by_key(|s| s.start); + ctx.drupal_callbacks.sort_by_key(|s| s.start); + ctx.drupal_callbacks.dedup_by_key(|s| s.start); + ctx.drupal_callbacks.shrink_to_fit(); ctx.routes.shrink_to_fit(); let mut member_access_indices: crate::atom::AtomMap> = @@ -883,6 +888,7 @@ fn extract_symbol_map_inner( drupal_routes: ctx.drupal_routes, drupal_hooks: ctx.drupal_hooks, drupal_computed_hooks: ctx.drupal_computed_hooks, + drupal_callbacks: ctx.drupal_callbacks, routes: ctx.routes, tempest_routes: ctx.tempest_routes.into_boxed_slice(), tempest_uri_calls: ctx.tempest_uri_calls.into_boxed_slice(), diff --git a/src/symbol_map/map.rs b/src/symbol_map/map.rs index 67ff95453..80df9717c 100644 --- a/src/symbol_map/map.rs +++ b/src/symbol_map/map.rs @@ -350,6 +350,10 @@ pub(crate) struct SymbolMap { /// The invoking calls of the core methods that fire hooks under /// computed names. Empty for every other file. pub drupal_computed_hooks: Vec, + /// The callbacks the file's form and render arrays name under their + /// callback keys, sorted by `start`. Empty for every file that names + /// none. + pub drupal_callbacks: Vec, /// The routes the file declares, in source order. Empty for every file /// that declares none. pub routes: Vec, diff --git a/src/symbol_map/string_keys.rs b/src/symbol_map/string_keys.rs index cce748019..3a8105c0a 100644 --- a/src/symbol_map/string_keys.rs +++ b/src/symbol_map/string_keys.rs @@ -890,6 +890,45 @@ pub(crate) struct PluginManagerSite { pub static_plugins: Vec, } +/// A callback a Drupal form or render array names under one of its callback +/// keys, keyed back by `start` to the span of the method it names. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct DrupalCallbackSite { + pub start: u32, + pub key: CallbackKey, + pub shape: CallbackShape, +} + +/// How Drupal calls the callbacks under a key. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum CallbackKey { + /// A form callback, which Drupal rewrites `'::method'` in for the form + /// before it calls it. + Form, + /// A render callback (`#pre_render`, `#lazy_builder`, …), which Drupal + /// calls without that rewrite. + Render, + /// `#value_callback`, which Drupal calls only when it is a native + /// callable and ignores otherwise. + Value, +} + +/// How a callback names its method. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum CallbackShape { + /// `'::method'`. + FormMethod, + /// `'service:method'`. + ServiceMethod, + /// `'Class::method'`, with where the class name runs in the string when + /// the source spells it as it reads. + ClassMethod { class: Option<(u32, u32)> }, + /// A class name joined to `'::method'`. + JoinedMethod, + /// An array callable. + ArrayCallable, +} + /// A byte range a Drupal file runs only when the module `module` is /// installed: the branch of an `if (…moduleExists('m'))`, or the rest of a /// block after `if (!…moduleExists('m')) { return; }`. diff --git a/tests/integration/drupal_callbacks.rs b/tests/integration/drupal_callbacks.rs index dd8f8e3a2..122f16ffa 100644 --- a/tests/integration/drupal_callbacks.rs +++ b/tests/integration/drupal_callbacks.rs @@ -811,72 +811,663 @@ async fn renaming_a_method_or_function_rewrites_the_name_in_its_callbacks() { ); } -/// Callbacks that name nothing, or a method Drupal cannot call, which this -/// support reads without warning about, next to a call and a method call -/// that do get a warning. -const UNCHECKED_PATH: &str = "web/modules/custom/acme/src/Form/UncheckedForm.php"; +/// The zero-based line, code and text of each diagnostic of the open file +/// `path`. +fn diagnostics_of( + backend: &phpantom_lsp::Backend, + dir: &tempfile::TempDir, + path: &str, + content: &str, +) -> Vec<(u32, String, String)> { + let uri = uri_for(dir, path); + let mut diagnostics = Vec::new(); + backend.collect_slow_diagnostics(uri.as_str(), content, &mut diagnostics); + backend.collect_fast_diagnostics(uri.as_str(), content, &mut diagnostics); + let mut found: Vec<(u32, String, String)> = diagnostics + .iter() + .map(|diagnostic| { + let code = match &diagnostic.code { + Some(Code::String(code)) => code.clone(), + _ => String::new(), + }; + ( + diagnostic.range.start.line, + code, + crate::common::message_text(&diagnostic.message).to_string(), + ) + }) + .collect(); + found.sort(); + found +} + +/// Whether `found` holds exactly one diagnostic on the line of `needle` in +/// `content`, under `code`, whose text contains `text`. +#[track_caller] +fn assert_reported( + found: &[(u32, String, String)], + content: &str, + needle: &str, + code: &str, + text: &str, +) { + let line = line_of(content, needle); + let on_line: Vec<_> = found.iter().filter(|(at, _, _)| *at == line).collect(); + assert!( + on_line.len() == 1 && on_line[0].1 == code && on_line[0].2.contains(text), + "{needle}: {found:?}" + ); +} + +const WARNED_PATH: &str = "web/modules/custom/acme/src/Form/WarnedForm.php"; + +const WARNED: &str = r#" ['callback' => [$this, 'missingAjax']]]; + $form['#process'] = ['Drupal\acme\Helper::missingProcess', '\Drupal\acme\Helper::shout']; + $form['#markup'] = [$this, 'notACallback']; + $form['z']['#ajax']['callback'] = '::save'; + $form['#after_build'][] = '::save'; + $form['#entity_builders'] = ['::save']; + $form['#submit'][] = $callback; + $form['#submit'][] = $prefix . '::notRead'; + return $form; + } + + public static function processTitle(array $element): array { + $element['#process'][] = '::missingInStatic'; + return $element; + } + + public function save(): void {} +} +"#; + +#[tokio::test] +async fn a_callback_naming_a_missing_method_is_reported() { + let (backend, dir) = workspace(&[ + (FORM_INTERFACE_PATH, FORM_INTERFACE), + (FORM_BASE_PATH, FORM_BASE), + (HELPER_PATH, HELPER), + (WARNED_PATH, WARNED), + (HOOKS_PATH, HOOKS), + (TRAIT_PATH, MISSING_TRAIT), + ]) + .await; + backend.ensure_workspace_indexed(); + let found = diagnostics_of(&backend, &dir, WARNED_PATH, WARNED); + for needle in [ + "missingCheck", + "missingSave", + "missingRefresh", + "missingAjax", + "missingProcess", + "missingInStatic", + ] { + assert_reported(&found, WARNED, needle, "unknown_member", needle); + } + // Drupal calls an array callable that names its class only when the + // method is static, and instantiates the class a string names. + assert_reported( + &found, + WARNED, + "[static::class, 'save']", + "invalid_drupal_callback", + "WarnedForm::save() is not static", + ); + assert_eq!(found.len(), 7, "{found:?}"); + + // `'::method'` outside a form names a method of a form the code does + // not know, and in a trait one the using form may declare. + assert_eq!( + diagnostics_of(&backend, &dir, HOOKS_PATH, HOOKS), + Vec::new() + ); + assert_eq!( + diagnostics_of(&backend, &dir, TRAIT_PATH, MISSING_TRAIT), + Vec::new() + ); +} + +const KEYED_PATH: &str = "web/modules/custom/acme/src/Form/KeyedForm.php"; + +/// A form whose callback lists hold keyed entries, as core's entity forms +/// key their entity builders. +const KEYED: &str = r#" ['acme_save' => '::saveKeyed']]; + $form['#validate']['acme_missing'] = '::missingKeyed'; + $form['#ajax']['wrapper'] = '::buildEntity'; + $form['other']['acme_other'] = '::buildEntity'; + $form['#lazy_builder'] = ['acme_builder' => '::buildEntity', []]; + return $form; + } + + public function buildEntity(): void {} + + public function saveKeyed(): void {} +} +"#; + +#[tokio::test] +async fn a_keyed_entry_of_a_callback_list_is_a_callback() { + let (backend, dir) = workspace(&[ + (FORM_INTERFACE_PATH, FORM_INTERFACE), + (FORM_BASE_PATH, FORM_BASE), + (KEYED_PATH, KEYED), + ]) + .await; + backend.ensure_workspace_indexed(); + let keyed = (KEYED_PATH, KEYED); + let keyed_uri = uri_for(&dir, KEYED_PATH); + let build_entity = (keyed_uri.clone(), line_of(KEYED, "function buildEntity")); + let save_keyed = (keyed_uri.clone(), line_of(KEYED, "function saveKeyed")); + for (needle, inside, expected) in [ + ("'::buildEntity'", 4, vec![build_entity]), + ("'::saveKeyed'", 4, vec![save_keyed]), + // Only a list key's entries are callbacks, and only the first item + // of `#lazy_builder`. + ("['wrapper'] = '::buildEntity'", 18, Vec::new()), + ("['acme_other'] = '::buildEntity'", 21, Vec::new()), + ("'acme_builder' => '::buildEntity'", 23, Vec::new()), + ] { + let found = definition_lines(&backend, &dir, keyed, needle, inside).await; + assert_eq!(found, expected, "{needle}"); + } + + let found = reference_lines(&backend, &dir, keyed, "function buildEntity", 10).await; + assert_eq!( + found, + lines( + &dir, + &[ + (KEYED_PATH, KEYED, "function buildEntity"), + (KEYED_PATH, KEYED, "$form['#entity_builders']"), + ] + ) + ); + + let position = position_in(KEYED, "function saveKeyed", 10); + let edit = rename( + &backend, + &keyed_uri, + position.line, + position.character, + "storeKeyed", + ) + .await + .expect("an edit"); + assert_eq!( + renamed(&edit, &dir, keyed), + KEYED.replace("saveKeyed", "storeKeyed") + ); + + let found = diagnostics_of(&backend, &dir, KEYED_PATH, KEYED); + assert_reported( + &found, + KEYED, + "missingKeyed", + "unknown_member", + "missingKeyed", + ); + assert_eq!(found.len(), 1, "{found:?}"); +} -const UNCHECKED: &str = r#"privateCheck(); + $this->protectedSave(); + static::privateProcess(); + return $form; + } + + private function privateCheck(): void {} + + protected function protectedSave(): void {} + + private static function privateProcess(): void {} +} + +final class Hidden { + protected function secret(): void {} +} +"#; + +#[tokio::test] +async fn a_callback_naming_a_method_drupal_cannot_call_is_reported() { + let (backend, dir) = workspace(&[ + (FORM_INTERFACE_PATH, FORM_INTERFACE), + (FORM_BASE_PATH, FORM_BASE), + (HIDDEN_PATH, HIDDEN), + ]) + .await; + backend.ensure_workspace_indexed(); + let found = diagnostics_of(&backend, &dir, HIDDEN_PATH, HIDDEN); + for (needle, text) in [ + ("'::privateCheck'", "Cannot call private method"), + ("'protectedSave'", "Cannot call protected method"), + ("'::privateProcess'", "Cannot call private method"), + ("Hidden::secret", "Cannot call protected method"), + ] { + assert_reported(&found, HIDDEN, needle, "inaccessible_member", text); + } + assert_eq!(found.len(), 4, "{found:?}"); +} + +const NAMESPACED_FUNCTION_PATH: &str = "web/modules/custom/acme/src/Form/namespaced.php"; + +/// A function only the form's namespace declares. +const NAMESPACED_FUNCTION: &str = + "missingMethod(); + $form['#markup'] = 'acme_missing_markup'; + return $form; + } +} + +function acme_same_file_submit(): void {} +"#; + +#[tokio::test] +async fn a_callback_naming_a_missing_function_is_reported() { + let (backend, dir) = workspace(&[ + (FORM_INTERFACE_PATH, FORM_INTERFACE), + (FORM_BASE_PATH, FORM_BASE), + (MODULE_PATH, MODULE), + (NAMESPACED_FUNCTION_PATH, NAMESPACED_FUNCTION), + (INVOKABLE_PATH, INVOKABLE), + (INVOKABLE_SERVICES_PATH, INVOKABLE_SERVICES), + (FUNCTIONS_FORM_PATH, FUNCTIONS_FORM), + ]) + .await; + backend.ensure_workspace_indexed(); + let found = diagnostics_of(&backend, &dir, FUNCTIONS_FORM_PATH, FUNCTIONS_FORM); + // A function name is global: the form's namespace does not apply. A + // name that is a class or a service names an invokable. + for needle in [ + "'acme_missing_submit'", + "'acme_namespaced_submit'", + "'acme_same_file_submit'", + ] { + assert_reported( + &found, + FUNCTIONS_FORM, + needle, + "unknown_function", + "not found", + ); + } + assert_eq!(found.len(), 3, "{found:?}"); +} + +const GUARDED_PATH: &str = "web/modules/custom/acme/src/Form/GuardedForm.php"; + +/// A form that adds a callback only when its function exists. +const GUARDED: &str = r#" = diagnostics - .iter() - .map(|diagnostic| crate::common::message_text(&diagnostic.message)) - .collect(); - assert_eq!(messages.len(), expected.len(), "{path}: {messages:?}"); - for name in expected { - assert!( - messages.iter().any(|message| message.contains(name)), - "{path}: {messages:?}" - ); - } + assert_reported(&found, DEPRECATED_FORM, needle, code, text); + } + assert_eq!(found.len(), 4, "{found:?}"); +} + +const MAGIC_PATH: &str = "web/modules/custom/acme/src/Magic.php"; + +/// A class whose instances answer any method, which its class does not. +const MAGIC: &str = " [ + '::preRender', + static::class . '::preRender', + 'Drupal\acme\Missing::build', + 'acme_invokable::__invoke', + ], + '#lazy_builder' => ['::build', []], + '#access_callback' => '::access', + ]; + $info['#post_render'][] = '::postRender'; + $info['#value_callback'] = '::staticValue'; + $info['a']['#value_callback'] = 'acme_invokable:__invoke'; + $info['b']['#value_callback'] = 'Drupal\acme\Element\Widget::value'; + $info['c']['#value_callback'] = static::class . '::value'; + $info['d']['#value_callback'] = [static::class, 'value']; + $info['e']['#value_callback'] = [static::class, 'staticValue']; + $info['f']['#value_callback'] = 'Drupal\acme\Element\Widget::staticValue'; + $info['g']['#value_callback'] = [$this, 'value']; + $info['h']['#value_callback'] = 'acme_log_submit'; + return $info; + } + + public function preRender(): void {} + + public function postRender(): void {} + + public function build(): void {} + + public function access(): void {} + + public function value(): void {} + + public static function staticValue(): void {} +} +"#; + +#[tokio::test] +async fn a_callback_drupal_cannot_resolve_or_ignores_is_reported() { + let (backend, dir) = workspace(&[ + (MODULE_PATH, MODULE), + (INVOKABLE_PATH, INVOKABLE), + (INVOKABLE_SERVICES_PATH, INVOKABLE_SERVICES), + (ELEMENT_PATH, ELEMENT), + ]) + .await; + backend.ensure_workspace_indexed(); + let found = diagnostics_of(&backend, &dir, ELEMENT_PATH, ELEMENT); + for needle in ["'::preRender'", "'::build'", "'::access'", "'::postRender'"] { + assert_reported( + &found, + ELEMENT, + needle, + "invalid_drupal_callback", + "only in a form callback", + ); + } + for needle in [ + "'::staticValue'", + "'acme_invokable:__invoke'", + "'Drupal\\acme\\Element\\Widget::value'", + "static::class . '::value'", + "[static::class, 'value']", + ] { + assert_reported( + &found, + ELEMENT, + needle, + "invalid_drupal_callback", + "ignored", + ); } + // The class part of `'Class::method'` names a class, or a service. + assert_reported( + &found, + ELEMENT, + "Missing::build", + "unknown_class", + "Class Drupal\\acme\\Missing not found", + ); + assert_eq!(found.len(), 10, "{found:?}"); +} + +const IMPORTING_PATH: &str = "web/modules/custom/acme/src/Render/Importing.php"; + +/// A caller in another namespace that imports the namespaced `Helper`: +/// the class name in a callback string is read as fully qualified all the +/// same. +const IMPORTING: &str = r#" [ + 'Helper::shout', + 'Helper::whisper', + 'Drupal\acme\Helper::whisper', + Helper::class . '::whisper', + ], + ]; + } +} +"#; + +#[tokio::test] +async fn the_class_of_a_callback_string_is_read_as_fully_qualified() { + // Without a global `Helper`, the short name names no class. + let (backend, dir) = workspace(&[ + (HELPER_PATH, HELPER), + (INVOKABLE_SERVICES_PATH, INVOKABLE_SERVICES), + (IMPORTING_PATH, IMPORTING), + ]) + .await; + backend.ensure_workspace_indexed(); + let found = diagnostics_of(&backend, &dir, IMPORTING_PATH, IMPORTING); + for needle in ["'Helper::shout'", "'Helper::whisper'"] { + assert_reported( + &found, + IMPORTING, + needle, + "unknown_class", + "Class Helper not found", + ); + } + assert_eq!(found.len(), 2, "{found:?}"); + + // With one, the short name names it, whatever the file imports. + let (backend, dir) = workspace(&[ + (HELPER_PATH, HELPER), + (GLOBAL_HELPER_PATH, GLOBAL_HELPER), + (INVOKABLE_SERVICES_PATH, INVOKABLE_SERVICES), + (IMPORTING_PATH, IMPORTING), + ]) + .await; + backend.ensure_workspace_indexed(); + let found = diagnostics_of(&backend, &dir, IMPORTING_PATH, IMPORTING); + assert_reported( + &found, + IMPORTING, + "'Helper::whisper'", + "unknown_member", + "Method Helper::whisper() not found", + ); + assert_eq!(found.len(), 1, "{found:?}"); } /// The site with [`BUILDER`] on disk but not open, so the searches reach it @@ -1240,9 +1831,21 @@ async fn a_service_callback_checks_its_service_like_any_service_id() { .iter() .map(|diagnostic| crate::common::message_text(&diagnostic.message)) .collect(); - // The method a declared service's class lacks is not reported here. - assert_eq!(messages.len(), 1, "{messages:?}"); - assert!(messages[0].contains("acme.missing_builder"), "{messages:?}"); + // An unknown service is reported as a service, and the method a + // declared service's class lacks as a method. + assert_eq!(messages.len(), 2, "{messages:?}"); + assert!( + messages + .iter() + .any(|m| m.contains("'acme.missing_builder'")), + "{messages:?}" + ); + assert!( + messages + .iter() + .any(|m| m.contains("GreetingBuilder::nope()")), + "{messages:?}" + ); } // ─── Completion ───────────────────────────────────────────────────────────── From c2056c981134c1941230418f24ae70313310ffaf Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Tue, 10 Nov 2026 19:54:47 +0100 Subject: [PATCH 5/6] Update the changelog and roadmap for Drupal callbacks Assisted-by: claude-code/claude-sonnet-5-5 --- docs/CHANGELOG.md | 1 + docs/todo.md | 6 ++- docs/todo/drupal.md | 99 ++++++++++++++++++++++++++++++++++++--------- 3 files changed, 87 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ac281c4a5..430cba4fb 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -148,6 +148,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Unknown Drupal services.** In a Drupal project, a service ID that `\Drupal::service()` or a container's `get()` looks up is reported when no services file declares it and no service provider, compiler pass, or other PHP code could define it. A lookup the code checks with `has()` first, one that runs only when `moduleExists()` finds a module the site lacks, or one in a file that may catch the exception a missing service throws, is left alone, and so is test code. - **Drupal annotations without imports.** In a Drupal project, an annotation on a plugin class that no `use` imports, such as `@Block` or `@Translation`, jumps to its class, shows it on hover, and is found by Find References, wherever Drupal's plugin discovery would find it. - **Controller methods of a Drupal service.** In a routing file, the method of a `_controller` or `_title_callback` written as `service:method` jumps to the method of the service's class, completes from its public methods, and is listed among the method's references. +- **Drupal form and render callbacks.** In a Drupal project, a callback named in a form or render array, such as a `#submit`, `#validate`, `#pre_render`, or `#ajax` callback, jumps to its method or function, completes, shows it on hover, is renamed with it, and lists its references. A callback that names nothing, or that cannot be called, is reported. Contributed by @giuseppe-esposito-87. #### WordPress diff --git a/docs/todo.md b/docs/todo.md index 7d86b1cbd..f5cebe55e 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -130,7 +130,6 @@ ships, remove every row that names it. | # | Item | Impact | Complexity | | --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------- | | F59 | [Send Twig, YAML, and XML documents to the server from Zed](todo/lsp-features.md#f59-send-twig-yaml-and-xml-documents-to-the-server-from-zed) (Zed PR) | Medium | Low | -| DR11 | [Form and render callbacks](todo/drupal.md#dr11-form-and-render-callbacks) | Low-Medium | Low-Medium | | DR12 | [Translation placeholders](todo/drupal.md#dr12-translation-placeholders) | Low-Medium | Low-Medium | | DR13 | [Module names and `*.info.yml`](todo/drupal.md#dr13-module-names-and-infoyml) | Low-Medium | Low-Medium | | DR14 | [Port PHPStan's Drupal extension tests](todo/drupal.md#dr14-port-phpstans-drupal-extension-tests) | Medium | Medium | @@ -145,6 +144,11 @@ ships, remove every row that names it. | DR24 | [Warn on unknown theme hook names](todo/drupal.md#dr24-warn-on-unknown-theme-hook-names) | Low-Medium | Medium-High | | DR28 | [Plugin types a manager builds at run time](todo/drupal.md#dr28-plugin-types-a-manager-builds-at-run-time) | Medium | Medium | | DR27 | [Plugin IDs in YAML](todo/drupal.md#dr27-plugin-ids-in-yaml) | Low-Medium | Medium | +| DR32 | [`'::method'` callbacks in a form alter hook](todo/drupal.md#dr32-method-callbacks-in-a-form-alter-hook) | Low-Medium | Low-Medium | +| DR33 | [Render callbacks that are not trusted](todo/drupal.md#dr33-render-callbacks-that-are-not-trusted) | Low-Medium | Low | +| DR34 | [Callback parameter checks](todo/drupal.md#dr34-callback-parameter-checks) | Low | Low-Medium | +| DR35 | [Invokable classes and services as callbacks](todo/drupal.md#dr35-invokable-classes-and-services-as-callbacks) | Low | Low-Medium | +| DR36 | [Array callables that name their class in a string](todo/drupal.md#dr36-array-callables-that-name-their-class-in-a-string) | Low | Low | ## Yii diff --git a/docs/todo/drupal.md b/docs/todo/drupal.md index 8d7c316be..95007cc21 100644 --- a/docs/todo/drupal.md +++ b/docs/todo/drupal.md @@ -12,8 +12,8 @@ the plugins of each, the permissions the `*.permissions.yml` files declare, the configuration objects and keys the default configuration and the configuration schema declare, the theme hooks `hook_theme()` implementations declare, the render elements element -classes declare, and the libraries the `*.libraries.yml` files declare -are read. Nothing reads fields yet. +classes declare, the libraries the `*.libraries.yml` files declare, and +the callbacks form and render arrays name are read. Nothing reads fields yet. The requests in [#48](https://github.com/PHPantom-dev/phpantom_lsp/issues/48) are the @@ -70,22 +70,6 @@ names and report a misspelt one. --- -## DR11. Form and render callbacks - -**Impact: Low-Medium · Complexity: Low-Medium** - -```php -$form['actions']['submit']['#submit'][] = '::submitOrder'; -$form['country']['#ajax'] = ['callback' => '::updateRegions']; -``` - -`#submit`, `#validate`, `#element_validate`, `#pre_render`, -`#after_build`, and an `#ajax` `callback` name methods of the form class -as `'::method'`, or a function or `Class::method`. Navigate, rename, and -complete them, and report one that names nothing. - ---- - ## DR12. Translation placeholders **Impact: Low-Medium · Complexity: Low-Medium** @@ -365,3 +349,82 @@ argument, which each service in `views.services.yml` and sources and processes) neither complete nor navigate. Read the argument each such service passes, and type the service by the plugin type it builds. + +--- + +## DR32. `'::method'` callbacks in a form alter hook + +**Impact: Low-Medium · Complexity: Low-Medium** + +```php +function acme_form_node_article_form_alter(array &$form, FormStateInterface $form_state) { + $form['actions']['submit']['#submit'][] = '::saveDraft'; +} +``` + +In `hook_form_FORM_ID_alter()`, or `#[Hook('form_FORM_ID_alter')]`, a +`'::method'` names a method of the form class that `FORM_ID` belongs to, +not of the module's own class. Resolve the form ID to its form class, so +the callback navigates, completes, renames, and is reported when the +class has no such method. + +--- + +## DR33. Render callbacks that are not trusted + +**Impact: Low-Medium · Complexity: Low** + +```php +$build['#pre_render'][] = [Formatter::class, 'prepare']; +``` + +Drupal refuses to run a `#pre_render`, `#post_render`, `#lazy_builder`, or +`#access_callback` callback that is not trusted. Report a callback whose +class implements neither `TrustedCallbackInterface` nor +`RenderCallbackInterface`, and one whose method `trustedCallbacks()` does +not list. + +--- + +## DR34. Callback parameter checks + +**Impact: Low · Complexity: Low-Medium** + +```php +public function submitOrder(array $form) {} +``` + +A submit or validate handler takes `array &$form, FormStateInterface +$form_state`, and an `#ajax` callback takes the same two parameters. +Report a callback that takes a different list, such as one that lacks the +form state or types it as something else. + +--- + +## DR35. Invokable classes and services as callbacks + +**Impact: Low · Complexity: Low-Medium** + +```php +$form['#validate'][] = [OrderValidator::class, '__invoke']; +$form['#submit'][] = 'order_handler:submit'; +``` + +A class with `__invoke()` named as a callback, and a class name written +as the service part of `'Class:method'`, are not read as callbacks. +Navigate, rename, and report them like any other callback. + +--- + +## DR36. Array callables that name their class in a string + +**Impact: Low · Complexity: Low** + +```php +$form['#submit'][] = ['Drupal\acme\Form\OrderForm', 'submitOrder']; +``` + +An array callable whose class is a string rather than `OrderForm::class` +names no method, so it neither navigates nor renames, and a method the +class lacks is not reported. Read the string as the fully qualified class +name PHP reads it as, wherever an array callable is read. From 2291b701f0dde9e9b72c7cf194a8d7e201ad76db Mon Sep 17 00:00:00 2001 From: Anders Jenbo Date: Thu, 12 Nov 2026 09:26:22 +0100 Subject: [PATCH 6/6] Share the Drupal service ID check The unknown-service check and the Drupal callback checks now ask the same DrupalServiceIds whether a site may declare a service, instead of each reading the declared IDs and the PHP-defined ones separately. Co-Authored-By: Claude Opus 5.5 --- src/diagnostics/laravel_string_keys.rs | 26 +++++--------------------- src/drupal/services.rs | 2 +- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/src/diagnostics/laravel_string_keys.rs b/src/diagnostics/laravel_string_keys.rs index d35a55de4..95736f787 100644 --- a/src/diagnostics/laravel_string_keys.rs +++ b/src/diagnostics/laravel_string_keys.rs @@ -203,9 +203,9 @@ struct DeclaredKeys<'a> { middleware_known: bool, /// The service IDs the project's configuration declares, sorted. services: Vec, - /// The service IDs a Drupal site's services files declare, sorted, and - /// those its PHP code may define. - drupal_services: Option<(Vec, Arc)>, + /// The service IDs a Drupal site's services files declare, and those + /// its PHP code may define. + drupal_services: Option, /// The plugin types and their plugins, and the plugin IDs PHP code may /// add definitions for. drupal_plugins: Option<( @@ -414,16 +414,7 @@ impl<'a> DeclaredKeys<'a> { } else { Vec::new() }; - // Core's and contributed modules' services files are only read once - // the workspace index has walked the folders `.gitignore` leaves - // out. - let drupal_services = (has_service && in_drupal_site).then(|| { - backend.ensure_workspace_index_ready_for_request(); - ( - backend.symfony_declared_names(crate::symbol_map::StringKeyKind::ServiceId), - backend.drupal_php_service_ids(), - ) - }); + let drupal_services = (has_service && in_drupal_site).then(|| backend.drupal_service_ids()); // Core's and contributed modules' plugins are only read once the // workspace index has walked them. let drupal_plugins = names(|kind| kind == CheckedStringKind::DrupalPlugin).then(|| { @@ -758,14 +749,7 @@ impl<'a> DeclaredKeys<'a> { /// service ID, so only a class that does not exist is told missing. A /// site whose services files were not read declares none at all. fn judge_drupal_service(&self, key: &str) -> Verdict { - let (declared, php) = self.drupal_services.as_ref()?; - if declared.is_empty() { - return None; - } - let valid = declared - .binary_search_by(|name| name.as_str().cmp(key)) - .is_ok() - || php.declares(key) + let valid = self.drupal_services.as_ref()?.may_declare(key)? || (key.contains('\\') && self .backend diff --git a/src/drupal/services.rs b/src/drupal/services.rs index 00c3b2a79..5d70e2289 100644 --- a/src/drupal/services.rs +++ b/src/drupal/services.rs @@ -395,7 +395,7 @@ pub(crate) struct DrupalServiceIds { impl DrupalServiceIds { /// Whether the site may declare the service `id`, or `None` when its /// services files were not read. - fn may_declare(&self, id: &str) -> Option { + pub(crate) fn may_declare(&self, id: &str) -> Option { if self.declared.is_empty() { return None; }