ISSUE DESCRIPTION unused-class-members FP: methods called only from Svelte <template>…
- User
ISSUE DESCRIPTION
unused-class-members FP: methods called only from Svelte member expressions False positive on 2.84.0. Class methods called only from a Svelte
<template>via a member expression (for exampleresultState.pin(...)in markup) are reported asunused-class-member. Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.Repro (2.84.0): asciimoo/hister.
ResultState.onOpen,.pin,.updateLabel, and.addSkipRuleare each invoked from.sveltetemplates (resultState.pin(...)inResultActionsMenu.svelte) yet reported unused. The repo currently setsrules.unused-class-members: "off"to work around it.Expected: credit a method called as
<local>.<method>(...)inside a Svelte<template>when<local>resolves to an instance of the class, parallel to the existing Vue/Angular template member-access tracking.Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /fallow, current file: none) bash-$
Assistant
Let me start by understanding the issue. The problem is about Fallow (a static analysis tool) reporting false positives for
unused-class-memberwhen class methods are called from Svelte templates via member expressions likeresultState.pin(...).Let me first explore the repository structure to understand the codebase.
Assistant
This is a Rust project. Let me explore the crates directory to understand the structure better.
Assistant
Now let me look for how Svelte templates are handled and how member expression calls are tracked. Let me search for Svelte-related code:
Assistant
Let me look at the
unused_members.rsfile which seems to be the core of the unused class member analysis:Assistant
Now let me look for how Vue and Svelte template member accesses are tracked. Let me search for SFC (Single File Component) handling:
Assistant
Let me look at the Svelte test fixture and understand what's currently being tested:
Assistant
Now I can see the current test setup. The
Counterclass hasbump()called from the Svelte template viacounter.bump()andvalueaccessed viacounter.value. Let me now look at how the SFC parsing and template member access tracking works:Assistant
Let me look at the Svelte template parsing code:
Assistant
The file is quite long. Let me look at the key part - the
merge_expression_usage_allow_dollar_refs_with_bound_targetsfunction and theTemplateUsagestructure to understand how expressions are being tracked and whatbound_targetsare. Let me also look at how the member access chain tracking works.Assistant
Now I understand the structure. Let me look at the
shared.rsfile to understand themerge_expression_usage_allow_dollar_refs_with_bound_targetsfunction:Assistant
Now let me look at the
unused_members.rsfile more closely to understand how member accesses from templates are resolved to class members:Assistant
Now I need to understand how Svelte/Vue template member accesses are handled. Let me search for how SFC template member_accesses are used:
Assistant
Let me look at how the
resolve_bound_member_accessesworks, as mentioned around line 1714:Assistant
key = format!("{}{callee_object}:{callee_method}", crate::FACTORY_CALL_SENTINEL,); self.binding_target_names.insert(local_name, key); } } }
The
resolve_bound_member_accessesfunction takesmember_accesses(e.g.x.bar) and maps them throughbinding_target_names(e.g.x -> Foo) to produceFoo.baraccesses. This is for normal JavaScript code.Now let me look at how Svelte template member accesses are collected and if they flow through this resolution. Let me look at how the SFC template usage is processed:
<tool_call> <function=bash_terminal> <parameter=command> grep -rn "bound_targets|bound_member" /fallow/crates/extract/src --include="*.rs" | head -40 </tool_call>
Assistant
Let me continue investigating the codebase to understand how Svelte template member accesses are handled.
Assistant
Now let me look at how
bound_targetsis built insfc.rs:Assistant
Let me look at the
apply_template_usagefunction to see how template member accesses are merged:Assistant
Let me understand how
binding_target_namesis built - this maps local variable names to their target class export names:Assistant
Now I understand the architecture. Let me trace the flow:
-
In SFC parsing (
sfc.rs),merge_script_into_modulecollectsbinding_target_namesfrom the script block and adds them totemplate_visible_bound_targets. -
binding_target_namesmaps local variable names (likeresultStateorcounter) to their target class/export names (likeResultStateorCounter). -
The template is then scanned with
collect_template_usage_with_bound_targets, which usesbound_targetsto resolve member accesses from the template. -
The template usage's
member_accessesare merged intocombined.member_accesses. -
In
unused_members.rs, themember_accessesare processed to credit class members.
The issue is: when we have
resultState.pin(...)in a Svelte template, andresultStateis a local instance ofResultState, the template scanning should:- Recognize
resultStateas a bound target (viatemplate_visible_bound_targets) - Resolve
resultState.pintoResultState.pin
Let me check if
binding_target_namesis being populated correctly for Svelte. Let me look at whatbinding_target_namescontains:Looking at line 376-381:
template_visible_bound_targets.extend( extractor .binding_target_names() .iter() .filter(|(local, _)| !local.starts_with("this.")) .map(|(local, target)| (local.clone(), target.clone())), );So
template_visible_bound_targetsgets thebinding_target_namesfrom the script extractor. This mapslocal_name -> target_namewheretarget_nameis the class name for instances (likecounter -> Counter).Now in
template_usage.rs, theanalyze_template_snippet_with_bound_targetsfunction usesbound_targetsto resolve member accesses:remap_object_name( &access.object, &unresolved_targets, bound_targets, allow_dollar_prefixed_refs, ) .map(|object| MemberAccess { object, member: access.member, })And
remap_object_namedoes:if unresolved_names.contains(name) { if let Some(target) = bound_targets.get(name) { return Some(target.clone()); } return Some(name.to_string()); }So this should work! If
resultStateis inbound_targetsmapping toResultState, andresultStateis an unresolved name in the template expression, thenresultState.pinshould becomeResultState.pin.Wait, but there's a condition:
if snippet.is_empty() || (imported_bindings.is_empty() && bound_targets.is_empty()). Let me check...In
collect_template_usage_with_bound_targetsinsvelte.rs:pub(super) fn collect_template_usage_with_bound_targets( source: &str, imported_bindings: &FxHashSet<String>, bound_targets: &FxHashMap<String, String>, ) -> TemplateUsage { if imported_bindings.is_empty() && bound_targets.is_empty() { return TemplateUsage::default(); }So if both are empty, we return early. But if
bound_targetsis populated, we should be fine.Let me look at how Vue handles this - the test
vue_template_event_handlers_mark_class_members_usedpasses, meaning it works for Vue. Let me check if there's a difference in how Vue and Svelte handle bound targets...Actually wait, let me look more carefully at the Vue test to see what fixture it's using. Let me also check how the current Svelte test fixture works vs what the issue describes.
The current Svelte test fixture has
const counter = new Counter()and then uses{counter.bump()}and{counter.value}in the template. The testsvelte_template_event_handlers_mark_class_members_usedconfirms this works.But the issue says that when a class instance is used with member expressions in Svelte templates (like
resultState.pin(...)), it's NOT being tracked. This sounds like it might be a specific scenario.Let me check if
binding_target_namesactually capturesconst resultState = new ResultState()type bindings...Looking at the code,
binding_target_namesis populated fromresolve_object_binding_candidateswhich tracks things like:const x = new Foo()→x→Fooconst x: Service(typed binding) →x→Service
Wait, let me check what
resolve_object_binding_candidatesdoes...Actually, let me re-read the issue more carefully:
Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.
So the issue is that the template-visible identifiers (like
resultState) ARE tracked, but the member expression calls (likeresultState.pin(...)) are NOT tracked properly.Let me look at what's happening. When
resultStateis an imported binding vs when it's a locally declared instance...If
resultStateis declared in the<script>block (likeconst resultState = new ResultState()), then:binding_target_nameswould haveresultState -> ResultStatetemplate_visible_bound_targetswould haveresultState -> ResultState- The template scanner would see
resultState.pin(...)and remap it toResultState.pin
But if
resultStateis an imported binding (likeimport { resultState } from './store'), then:resultStatewould be intemplate_visible_imports, nottemplate_visible_bound_targets- The template scanner would track
resultStateas a used binding (clearing the unused import) - But the member access
resultState.pinwould haveresultStateas the object...
Let me look at the
remap_object_namefunction more carefully:fn remap_object_name( name: &str, unresolved_names: &FxHashSet<String>, bound_targets: &FxHashMap<String, String>, allow_dollar_prefixed_refs: bool, ) -> Option<String> { if unresolved_names.contains(name) { if let Some(target) = bound_targets.get(name) { return Some(target.clone()); } return Some(name.to_string()); } ... }Wait,
unresolved_namescontains names that are unresolved references in the parsed template snippet. IfresultStateis inimported_bindings, it would be resolved by the parser (because it was declared as a local), so it wouldn't be inunresolved_names!Let me look at how
unresolved_targetsis computed:for name in semantic_ret .semantic .scoping() .root_unresolved_references() .keys() { let name = name.as_str(); if imported_bindings.contains(name) { used_bindings.insert(name.to_string()); unresolved_targets.insert(name.to_string()); continue; } if bound_targets.contains_key(name) { unresolved_targets.insert(name.to_string()); continue; } ... }So
unresolved_targetsis populated from:- Unresolved references that are in
imported_bindings - Unresolved references that are keys in
bound_targets
But wait, the snippet is wrapped like:
let wrapped = wrap_snippet(snippet, kind, locals);And
wrap_snippetdoes:fn wrap_snippet(snippet: &str, kind: TemplateSnippetKind, locals: &[String]) -> String { let mut wrapped = String::new(); if !locals.is_empty() { wrapped.push_str("const __fallow_local = undefined;\n"); for local in locals { wrapped.push_str("const "); wrapped.push_str(local); wrapped.push_str(" = __fallow_local;\n"); } } ... }So only
localsare declared in the wrapper, notimported_bindings!Let me look at where the locals come from when analyzing template expressions...
In the Svelte template scanner,
apply_tagcalls:merge_expression_usage_allow_dollar_refs_with_bound_targets( usage, expr.trim(), imported_bindings, bound_targets, ¤t_locals(scopes), );And
current_localsreturns the locals from the scope stack (like#each item in items).So when analyzing
resultState.pin(...), ifresultStateis NOT inlocals(which it wouldn't be unless it's an#eachbinding), then it would be an unresolved reference in the wrapper... but wait, let me re-check.The issue says the problem is with imported instances - where
resultStatemight be declared in the script block but imported from elsewhere, or whereresultStateis astorethat's imported.Actually, let me re-read the issue:
ResultState.onOpen,.pin,.updateLabel, and.addSkipRuleare each invoked from.sveltetemplates (resultState.pin(...)inResultActionsMenu.svelte) yet reported unused.So
resultStateis an instance ofResultStateclass that's used in the Svelte template. The methodspin,updateLabel, etc. are on theResultStateclass. The issue is that Fallow reports these methods as unused because it doesn't track thatresultState.pin(...)in the template callsResultState.pin.OK so the key question is: how does
resultStaterelate toResultState? In the hister repo,resultStateis likely:- Either a local
const resultState = new ResultState(...)or similar - Or some kind of state/store that's an instance of
ResultState
For case 1,
binding_target_namesshould captureresultState -> ResultState, and the template scanning should remapresultState.pintoResultState.pin.Let me look at the actual code that populates
binding_target_namesmore carefully...Actually, let me check the
resolve_object_binding_candidatesfunction:<tool_call> <function=bash_terminal> <parameter=command> sed -n '720,810p' /fallow/crates/extract/src/visitor/mod.rs </tool_call>
-
Assistant
The bash command failed because of some formatting issue. Let me try again with the proper tool call format.
Assistant
I can see that
into_module_infocalls:resolve_object_binding_candidates()resolve_factory_call_candidates()resolve_bound_member_accesses()
Let me look at
resolve_object_binding_candidateto understand how instance bindings are tracked.Assistant
Let me look at the
ObjectBindingCandidatestruct and how they're collected to understand what's being tracked.Assistant
I need to find how
ObjectBindingCandidateentries are collected - these are what populatebinding_target_namesfor things likeconst counter = new Counter().Assistant
The user is asking me to continue my work. Let me look at what's happening around line 1350 in visit_impl.rs to understand how object binding candidates are collected.
Assistant
Let me search for where
newexpressions are tracked for binding target names:Assistant
Let me look at how
instance_bindingsare populated - these trackconst x = new SomeClass()patterns.Assistant
Let me find where
instance_bindingsis populated (likely in the NewExpression visitor):Assistant
Let me look at the
visit_new_expressionfunction to understand how instance bindings are captured:Assistant
Let me look for where
binding_target_namesis populated forconst x = new SomeClass()patterns:Assistant
Let me look at line 2475 and around to see where binding_target_names is populated for new expressions:
Assistant
Now let me look for where
const x = new SomeClass()bindings are captured - this would be in variable declarators:Assistant
Let me search more specifically for where
const x = new SomeClass()patterns are tracked to populatebinding_target_names.Assistant
Let me check line 981 - this seems to be where type annotation bindings are tracked:
Assistant
Let me look for where
const x = new SomeClass()patterns are tracked:Assistant
Let me check line 2052 - this seems like where variable declarators with
newexpressions might be handled:Assistant
Now I understand! The key code is at lines 2052-2061:
if let Expression::NewExpression(new_expr) = init && let Expression::Identifier(callee) = &new_expr.callee && let BindingPattern::BindingIdentifier(id) = &declarator.id && !super::helpers::is_builtin_constructor(callee.name.as_str()) { self.binding_target_names .insert(id.name.to_string(), callee.name.to_string()); }So when we have
const counter = new Counter(), this insertscounter -> Counterintobinding_target_names.Now in the SFC code (
sfc.rs), the script block is parsed andbinding_target_namesis collected. Then for template-visible scripts, it's added totemplate_visible_bound_targets:template_visible_bound_targets.extend( extractor .binding_target_names() .iter() .filter(|(local, _)| !local.starts_with("this.")) .map(|(local, target)| (local.clone(), target.clone())), );So
counter -> Countershould be intemplate_visible_bound_targets.Now when the template is scanned,
collect_template_usage_with_bound_targetsuses this to resolvecounter.bumptoCounter.bump.But here's the thing - the
analyze_template_snippet_with_bound_targetsfunction intemplate_usage.rsonly remaps accesses if the object name is inunresolved_targets(line 138-146):remap_object_name( &access.object, &unresolved_targets, bound_targets, allow_dollar_prefixed_refs, )And
remap_object_name(line 224-241) checks:fn remap_object_name(...) -> Option<String> { if unresolved_names.contains(name) { if let Some(target) = bound_targets.get(name) { return Some(target.clone()); } return Some(name.to_string()); } ... }So the object name must be in
unresolved_names(which comes fromunresolved_targets). Andunresolved_targetsis populated from unresolved references in the template snippet that are inimported_bindingsorbound_targets.Let me check: when the template snippet
counter.bump()is parsed, iscounteran unresolved reference?The
wrap_snippetfunction only declareslocals(like#eachbindings), NOT theimported_bindingsorbound_targets. Socounterwould indeed be unresolved!And then
unresolved_targetsis populated (lines 102-122):for name in semantic_ret .semantic .scoping() .root_unresolved_references() .keys() { let name = name.as_str(); if imported_bindings.contains(name) { used_bindings.insert(name.to_string()); unresolved_targets.insert(name.to_string()); continue; } if bound_targets.contains_key(name) { unresolved_targets.insert(name.to_string()); continue; } ... }So if
counteris inbound_targets, it should be inunresolved_targets, and thencounter.bumpshould be remapped toCounter.bump.Wait, but then why doesn't this work? Let me check the condition for early return at line 88:
if snippet.is_empty() || (imported_bindings.is_empty() && bound_targets.is_empty()) { return TemplateUsage::default(); }And there's also:
if unresolved_targets.is_empty() { return TemplateUsage::default(); }at line 131.
OK so the logic seems correct. Let me actually create a test case to reproduce the issue and see what's happening.
Let me first look at the existing Svelte test to see what passes:
Assistant
Let me run the existing Svelte tests to confirm the current behavior:
Assistant
The test is running and downloading dependencies. Let me wait for it to complete.
Assistant
The test passes! So
counter.bump()andcounter.valueARE being tracked correctly in Svelte templates whencounteris a localnew Counter().The issue description says:
ResultState.onOpen,.pin,.updateLabel, and.addSkipRuleare each invoked from.sveltetemplates (resultState.pin(...)inResultActionsMenu.svelte) yet reported unused.So what's the difference between
counterin the test fixture andresultStatein the hister repo?The key difference might be how
resultStateis declared. In the test fixture,counteris created directly withconst counter = new Counter(). ButresultStatein the hister repo might be:- An imported instance (like from a store)
- Created differently (like through a factory function)
- Or maybe it's not directly
new ResultState()but something more complex
Wait, let me re-read the issue more carefully:
Class methods called only from a Svelte
<template>via a member expression (for exampleresultState.pin(...)in markup) are reported asunused-class-member. Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.So the issue is that Fallow tracks the template-visible identifiers (so
resultStateis marked as used), but NOT the member expression method calls on those bound instances.So if
resultStateis inbinding_target_names(mapped toResultState), the member accessresultState.pinshould be remapped toResultState.pin. But apparently this isn't happening.Wait, let me look at the existing test more carefully. The test
svelte_template_event_handlers_mark_class_members_usedDOES pass forCounter.bumpandCounter.value. So what's different?Let me look at the test assertion:
#[test] fn svelte_template_event_handlers_mark_class_members_used() { ... assert!( !unused_members.contains(&"Counter.bump".to_string()), "Counter.bump should be used from a Vue @click handler, found: {unused_members:?}" );Wait, that says "Vue @click handler" but the test is for Svelte! Let me re-read the test file...
Actually looking at the test name
svelte_template_event_handlers_mark_class_members_usedand checking the fixture:<button onclick={() => counter.bump()}>{counter.value}</button>This works! So
counter.bump()is tracked.Now the question is: what's different about
resultState.pin()in the hister repo?Possible differences:
resultStateis NOT declared asnew ResultState()but through some other mechanismresultStateis an imported binding, not a local instance- There's a difference in how the template expression is parsed
Let me think about case 2 - if
resultStateis imported (likeimport { resultState } from './store'), then:resultStatewould be intemplate_visible_imports, NOT intemplate_visible_bound_targets- In
analyze_template_snippet_with_bound_targets,resultStatewould be inimported_bindings - When the snippet is parsed,
resultStateis unresolved - It would be found in
imported_bindings, soused_bindingswould includeresultStateandunresolved_targetswould includeresultState - But
remap_object_namewould only remap ifresultStateis inbound_targets- it wouldn't be, because it's an import, not a local instance binding
So for imported bindings, the member access
resultState.pinwould NOT be remapped to anything meaningful - it would stay asresultState.pin.But wait, the current test shows
Counter.bumpbeing tracked! AndCounteris imported in the Svelte file:import { myAttach, Counter, inTernary, inCallback, inSpread } from './utils';But
counter(lowercase) is the local instance:const counter = new Counter();So
counteris a local instance, andcounter.bumpgets remapped toCounter.bumpbecausecounter -> Counteris inbinding_target_names.Now if
resultStateis an imported instance (not a localnew ResultState()), then:resultStatewould be intemplate_visible_imports(as an import binding)resultStatewould NOT be intemplate_visible_bound_targetsresultState.pinwould stay asresultState.pinand NOT be remapped
This is the bug! The issue is that when you have an imported instance (like
import { resultState } from './store'whereresultStateis already an instance ofResultState), the member accessresultState.pinin the Svelte template is not being tracked.But wait, the issue says
resultStateis an instance ofResultState. How would Fallow know thatresultStatefrom the import is an instance ofResultState?Actually, looking at the issue again:
ResultState.onOpen,.pin,.updateLabel, and.addSkipRuleare each invoked from.sveltetemplates (resultState.pin(...)inResultActionsMenu.svelte)The
ResultStateis the class, andresultStateis the instance. IfresultStateis a localnew ResultState(), it should work. IfresultStateis an imported instance, we'd need type information to know it's aResultState.Hmm, let me re-check the issue description once more:
Class methods called only from a Svelte
<template>via a member expression (for exampleresultState.pin(...)in markup) are reported asunused-class-member. Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.OK so it says "bound instance" which suggests it's a local binding like
const resultState = new ResultState(). Let me look at what the hister repo actually has.Actually, I can't access the hister repo from here. But the issue clearly states that:
ResultStateclass has methods like.pin,.updateLabel,.addSkipRule- These methods are called in Svelte templates via
resultState.pin(...)etc. resultStateis an instance ofResultState- Fallow reports these methods as unused
The question is: why doesn't it work for hister when the test fixture works?
One possibility: maybe in hister,
resultStateis awritablestore or similar Svelte store pattern, not a directnew ResultState()call.Let me check if there's any specific handling for store patterns...
Actually, let me look at what the
binding_target_namesfunction returns. Looking at the SFC extraction code:template_visible_bound_targets.extend( extractor .binding_target_names() .iter() .filter(|(local, _)| !local.starts_with("this.")) .map(|(local, target)| (local.clone(), target.clone())), );So
binding_target_names()is called on the extractor, which returns&self.binding_target_names. This HashMap is populated during the AST walk.Wait, let me check if the script block parsing correctly runs the
into_module_infomethod which callsresolve_object_binding_candidates():Looking at
merge_script_into_moduleinsfc.rs:let mut extractor = ModuleInfoExtractor::new(); extractor.visit_program(&parser_return.program);So it only calls
visit_program, NOTinto_module_info. Theinto_module_infomethod (which callsresolve_object_binding_candidates,resolve_factory_call_candidates,resolve_bound_member_accesses) is called on normal JS/TS files but NOT on SFC script blocks!Let me check:
<tool_call> <function=bash_terminal> <parameter=command> grep -n "into_module_info|resolve_object_binding" /fallow/crates/extract/src/sfc.rs </tool_call>
Assistant
Let me search for
into_module_infoin the SFC file to understand the flow.Assistant
So
into_module_infois NOT called for SFC script blocks. This meansresolve_object_binding_candidates()is never called for SFC scripts! Let me verify this:Assistant
Now I see the issue! In
merge_script_into_module, onlyextractor.visit_program()is called, but NOTinto_module_info()which would callresolve_object_binding_candidates().However, the key thing is that
binding_target_namesis populated directly during the AST walk (invisit_variable_declarationetc.), not in the finalize step. Soconst counter = new Counter()should still populatebinding_target_namesduringvisit_program.Let me verify by looking at how
binding_target_namesis populated - it happens invisit_variable_declarationwhich IS called duringvisit_program.Wait, but let me check again. In the visitor,
binding_target_names.insertis called at line 2052-2061 forconst x = new ClassName(...). This is invisit_variable_declaration, which IS called duringvisit_program.So
binding_target_namesSHOULD be populated even withoutinto_module_info().But then why doesn't the test work? The test DOES pass for
Counter.bump. Socounter -> CounterIS being tracked.Let me re-read the issue more carefully...
Oh wait, I see! The test fixture has:
const counter = new Counter();But the hister repo might have a DIFFERENT pattern. Let me think about what patterns might not work:
const resultState = new ResultState(...)- this should work (same as test)let resultState = new ResultState(...)- this should work tooresultStateimported from another module - this might not work becauseresultStatewould be intemplate_visible_imports, nottemplate_visible_bound_targets
Actually, let me look at the issue description again:
ResultState.onOpen,.pin,.updateLabel, and.addSkipRuleare each invoked from.sveltetemplates (resultState.pin(...)inResultActionsMenu.svelte)Hmm, the issue mentions
ResultState.onOpenwhich looks like a static method call pattern. But then it also mentionsresultState.pin(...)which is an instance method call.Let me think about this differently. The test passes because
counteris bound toCounterviaconst counter = new Counter(). This populatesbinding_target_nameswithcounter -> Counter.But what if
resultStateis bound differently? For example:const resultState = store.get()- not anewexpressionconst resultState = createResultState()- a factory call, not anewexpression- Some other pattern
The key insight is:
binding_target_namesis populated for:const x = new ClassName(...)- direct new expressionconst [x] = useState(() => new ClassName(...))- factory patternconst x = SomeClass.staticFactory()- factory call candidates (resolved later)- Type annotations like
const x: ClassName- viaresolve_object_binding_candidates this.field = new ClassName(...)- instance member assignment
If
resultStateis created through a pattern that's not captured by any of these, thenbinding_target_nameswon't haveresultState -> ResultState, andresultState.pinwon't be remapped.But wait, let me re-read the issue description:
Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.
So the identifier
resultStateIS tracked as used (so the import/export isn't flagged), but the member callresultState.pin()is NOT tracked.This could mean:
resultStateis intemplate_visible_imports(so it's tracked as used), but NOT intemplate_visible_bound_targets- When
resultState.pin()is scanned,resultStateis inimported_bindingsbut NOT inbound_targets resultStateis added toused_bindingsandunresolved_targets(because it's inimported_bindings)- But when remapping,
remap_object_namechecksbound_targetsfirst, which doesn't haveresultState, so it returnsresultState(the original name) - The member access becomes
resultState.pin, which doesn't match the classResultState
So the fix should be: when
resultStateis an imported binding that is an instance of a class, we need to know what class it's an instance of and remap accordingly.But how would we know that an imported binding is an instance of a class? We'd need type information, which is expensive.
Alternatively, there might be a simpler fix. Let me look at what the
resolve_bound_member_accessesfunction does for regular JS files - it resolves member accesses on bound objects to their target class. Maybe we need to do something similar for SFC templates when the bound object is an import.Actually, wait. Let me look more carefully at how Vue handles this. The Vue test
vue_template_event_handlers_mark_class_members_usedpasses too. Let me check if Vue has any special handling...Actually, I think the issue might be simpler. Let me look at how
binding_target_namesis populated whenconst x = new SomeClass()is used in SFC scripts.The key is that
extractor.visit_program()is called on the script block, and during the visit,binding_target_namesis populated. Thenextractor.binding_target_names()returns the populated map.But wait, let me check if
resolve_object_binding_candidatesis called... it's NOT called because we don't callinto_module_info(). So type annotation bindings likeconst x: ClassName = ...might not be tracked.Hmm, but the issue says the methods ARE called in templates but NOT tracked. If
const resultState = new ResultState()were used, it SHOULD be tracked (as the test shows). So either:resultStateis not created withnew ResultState()- Or there's a bug somewhere in the template scanning for this specific case
Let me look at the test fixture again to see what patterns work:
<script lang="ts"> import { Counter } from './utils'; const counter = new Counter(); </script> <button onclick={() => counter.bump()}>{counter.value}</button>And
counter.bump()andcounter.valueare tracked. This works!So what's different in hister? Let me think...
Actually, I just realized something. The issue says:
The repo currently sets
rules.unused-class-members: "off"to work around it.So the whole rule is disabled in hister. This means ALL class members would be affected, not just specific ones. So the issue might be broader than I thought.
Let me re-read the expected behavior:
Expected: credit a method called as
<local>.<method>(...)inside a Svelte<template>when<local>resolves to an instance of the class, parallel to the existing Vue/Angular template member-access tracking.So the expectation is that when
<local>resolves to an instance of the class, the method should be credited. The test fixture already tests this withcounter.bump()and it works.Wait, let me check the test fixture more carefully. In
utils.ts:export class Counter { value = 0; bump() { this.value += 1; } unused() { return this.value; } }And in
App.svelte:const counter = new Counter();And the template uses
counter.bump()andcounter.value.The test confirms
Counter.bumpandCounter.valueare NOT unused, andCounter.unusedIS unused.So the basic case works! What's different about hister?
Hmm, let me look for any differences in how member accesses are collected from templates. Maybe the issue is with a specific Svelte syntax pattern?
Actually, wait. Let me re-read the issue description one more time:
ResultState.onOpen,.pin,.updateLabel, and.addSkipRuleare each invoked from.sveltetemplates (resultState.pin(...)inResultActionsMenu.svelte)So
resultState.pin(...)is the pattern. This should work ifresultStateis created asnew ResultState().But what if
resultStateis created differently? Like:const resultState = new ResultState(data, options);Or maybe it's a reactive statement:
$: resultState = createResultState();Or maybe it's an import:
import { resultState } from './store';Without seeing the actual hister code, I can only guess. But the issue says "bound instance" which suggests it's a local binding.
OK let me approach this differently. Let me look at what might be broken by examining the code flow more carefully.
When
const counter = new Counter()is in the Svelte script:visit_variable_declarationruns and populatesbinding_target_nameswithcounter -> Counterbinding_target_names()returns this maptemplate_visible_bound_targetsgetscounter -> Counter- Template scanning uses
collect_template_usage_with_bound_targetswithbound_targets = {counter: Counter} - When
counter.bump()is parsed,counteris unresolved (not declared in the wrapper) counteris found inbound_targets, so it's added tounresolved_targetscounter.bumpis remapped toCounter.bumpviaremap_object_name- The
MemberAccess { object: "Counter", member: "bump" }is added tomember_accesses
This should work! And the test confirms it does.
So what's different? Let me check if there's a specific pattern in hister that doesn't work...
Actually, I think I should just create a test case that reproduces the issue and debug from there. But since I don't have access to hister, let me think about what patterns might not work:
- Type annotation without
new:const resultState: ResultState = someFactory();binding_target_nameswouldn't have this becauseresolve_object_binding_candidates()is not called- But wait, there's code to handle type annotations in
visit_impl.rs...
Actually, wait! Let me check if
resolve_object_binding_candidatesis needed. Looking at the code:<tool_call> <function=bash_terminal> <parameter=command> sed -n '713,730p' /fallow/crates/extract/src/visitor/mod.rs </tool_call>
Assistant
Let me try the command again.
Assistant
I need to understand what
resolve_object_binding_candidatesdoes. It resolvesObjectBindingCandidateentries which are collected for patterns likeconst { foo } = someObject. This is for namespace destructuring, not fornewexpressions.The
newexpression case is handled directly invisit_variable_declarationat line 2052-2061, which should work for SFC scripts sincevisit_programis called.Let me think about what else could be different. The issue mentions that Fallow "tracks template-visible identifiers but not member-expression method calls on a bound instance". This suggests that the identifier IS being tracked but the member access on it is NOT.
Wait, let me re-read the issue more carefully:
Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.
So
resultState(the identifier) IS tracked as used, butresultState.pin(...)(the member expression call) is NOT tracked to creditResultState.pin.This could happen if:
resultStateis NOT inbound_targets(so it's not remapped toResultState)- But
resultStateIS inimported_bindings(so the import is kept used)
In this case,
resultState.pinwould become a member access with objectresultStateand memberpin. When the analyzer processes this, it looks for an export namedresultStatewith memberpin- but there isn't one, because the class is namedResultState.So the bug might be that
resultStateis an imported instance, not a localnewexpression.Actually, let me look at this from a different angle. The test fixture has:
import { Counter } from './utils'; const counter = new Counter();The class
Counteris imported, andcounteris a local instance. This works.What if in hister, the pattern is:
import { resultState } from './store'; // resultState is already an instanceThen
resultStateis intemplate_visible_importsbut NOT intemplate_visible_bound_targets. SoresultState.pinwould NOT be remapped.This is the likely scenario. The fix would be to track imported instances that are known to be of a certain type.
But how do we know that an imported binding is an instance of a class? We'd need type information.
Actually, wait. Let me look at what the analyze layer does with
member_accesses. If the template producesresultState.pin, andresultStateis an import from./store, then:- The import has
resultStateas the local name - The source module (
./store) exportsresultStateas something (maybe a named export) - The analyze layer needs to figure out that
resultStateis an instance ofResultState
This is complex because it requires type information.
But wait, let me re-read the issue:
parallel to the existing Vue/Angular template member-access tracking.
Let me look at how Vue handles this... Actually, the Vue test fixture also uses
const counter = new Counter()pattern, so it's the same.Hmm, let me look at Angular template handling since the issue specifically mentions it's similar to Vue/Angular.
Actually, I think I need to look at the code more carefully. Let me check if there's something specific about how member accesses from templates are processed in the unused_members analyzer.
Let me look at the test file again and trace through exactly what happens...
Actually, wait. Let me look at this more carefully. The test file says
svelte_template_event_handlers_mark_class_members_usedand it passes. So the basic case works.What if the issue is with a SPECIFIC pattern in Svelte templates? Like:
resultState.pin()inside a#eachblockresultState.pin()as an event handler attribute (likeonclick={resultState.pin})resultState.pin()inside a reactive statement
Let me look at what patterns are tested in the fixture and make sure they all work...
Actually, I just noticed something. The test fixture has:
<button onclick={() => counter.bump()}>{counter.value}</button>This is:
counter.bump()inside an arrow function inonclickattributecounter.valueinside a mustache expression{}
Both of these work. So what's different in hister?
Let me think about what might NOT work:
- Direct method binding:
onclick={resultState.pin}- this is a property access, not a call - Method in attribute:
class={resultState.pin()}- should work same ascounter.value - Method in
#each:{#each items as item}<p>{resultState.pin()}</p>{/each}- should work
Wait, let me check if property access (like
onclick={resultState.pin}) is tracked differently from method calls (onclick={() => resultState.pin()})...In the template scanner, both would be parsed as expressions.
resultState.pinis a member access, andresultState.pin()is a call expression that contains a member access.Let me look at how member accesses are extracted from expressions...
Actually, I think I need to look at the
ModuleInfoExtractorto see how member accesses are collected.Actually wait, I think I may have been overthinking this. Let me re-read the issue description more carefully:
False positive on 2.84.0. Class methods called only from a Svelte
<template>via a member expression (for exampleresultState.pin(...)in markup) are reported asunused-class-member.Expected: credit a method called as
<local>.<method>(...)inside a Svelte<template>when<local>resolves to an instance of the class, parallel to the existing Vue/Angular template member-access tracking.So the expected behavior is: when
<local>.<method>(...)is used in a Svelte template, and<local>resolves to an instance of a class, the method should be credited as used.The test fixture shows this works for
counter.bump(). So what's different?Let me actually look at the Vue test more carefully to see if there's something special about how Vue handles this...
Wait, I just realized something important. Let me check the test fixture path. The Vue tests use
vue-projectfixture and the Svelte tests usesvelte-projectfixture. Let me make sure I'm looking at the right files...Actually, let me look at the Vue fixture to compare:
I should check the Vue fixture to see what pattern is used there. But actually, the Svelte test already passes, so the basic case works.
Let me think about what could be different. The issue says "Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance". This suggests:
- Template-visible identifiers ARE tracked (the import/binding is marked as used)
- But member-expression method calls on those bound instances are NOT tracked (the class method is not credited)
So the gap is: when you have
const counter = new Counter()and{counter.bump()}:counteris tracked as used ✓Counter.bumpshould be credited as used
The test shows this works. So what's different in hister?
Hmm, actually let me re-read the test:
#[test] fn svelte_template_event_handlers_mark_class_members_used() { let root = fixture_path("svelte-project"); let config = create_config(root); let results = fallow_core::analyze(&config).expect("analysis should succeed"); let unused_members: Vec<String> = results .unused_class_members .iter() .map(|member| { format!( "{}.{}", member.member.parent_name, member.member.member_name ) }) .collect(); assert!( !unused_members.contains(&"Counter.bump".to_string()), "Counter.bump should be used from a Vue @click handler, found: {unused_members:?}" );Wait, the assertion says "Vue @click handler" but it's testing Svelte. That's just a copy-paste bug in the test message.
OK so this test passes. So
Counter.bumpis NOT inunused_members. The basic case works.Let me now think about what specific scenario in hister might not work...
Actually, I wonder if the issue is that the class and the instance are in DIFFERENT files. In the test:
Counteris defined inutils.tsApp.svelteimportsCounterand createscounter = new Counter()counter.bump()is used in the template
What if in hister:
ResultStateis defined inResultState.tsResultActionsMenu.svelteimportsResultStateAND createsresultState = new ResultState()resultState.pin()is used in the template
That should work the same way...
OR what if:
ResultStateis defined inResultState.ts- Some OTHER file imports
ResultStateand createsresultState = new ResultState() - That file exports
resultState ResultActionsMenu.svelteimportsresultStatefrom that fileresultState.pin()is used in the template
In this case,
resultStateis an IMPORTED instance, not a localnewexpression. The binding targetresultState -> ResultStatewould be in the OTHER file, not inResultActionsMenu.svelte.This is likely the scenario! When
resultStateis imported (not created locally), the SFC extractor doesn't know thatresultStateis an instance ofResultState.The fix would be to track this relationship. But how?
One approach: in the imported file, when
resultState = new ResultState()is used andresultStateis exported, we need to record this type information. Then inResultActionsMenu.svelte, whenresultStateis imported, we need to know it's an instance ofResultState.Actually, let me look at how Angular handles this. The issue says "parallel to the existing Vue/Angular template member-access tracking."
Looking at the Angular code around line 1622:
// Bridge Angular template member refs to their owning components. // // Sentinel member accesses come from two sources: // 1. External templates: HTML files scanned for Angular syntax, with sentinel // accesses stored on the HTML file's ModuleInfo. Bridged to the component // via the SideEffect import edge from @Component({ templateUrl }).Angular uses a different mechanism (sentinel member accesses). Let me look at how this works...
Actually, I think the key is the
INSTANCE_EXPORT_SENTINEL. Looking atrecord_exported_instance_bindings:fn record_exported_instance_bindings(&mut self) { if self.binding_target_names.is_empty() { return; } let additional_accesses: Vec<MemberAccess> = self .exports .iter() .filter_map(|export| { let local_name = export.local_name.as_deref()?; let target_name = self.binding_target_names.get(local_name)?; Some(MemberAccess { object: format!("{}{}", crate::INSTANCE_EXPORT_SENTINEL, export.name), member: target_name.clone(), }) }) .collect(); self.member_accesses.extend(additional_accesses); }This creates a sentinel access for exported instances. So if
const resultState = new ResultState()andexport { resultState }, thenINSTANCE_EXPORT_SENTINEL:resultStateis associated withResultState.Then when
ResultActionsMenu.svelteimportsresultState, the analyzer can use this sentinel to know thatresultStateis an instance ofResultState.But wait,
record_exported_instance_bindingsis called ininto_module_info(), which is NOT called for SFC script blocks! Let me verify...Actually, for the file that exports
resultState(a regular .ts file),into_module_info()WOULD be called. So the sentinel WOULD be created.But for the SFC file that imports
resultState, we need to resolve the import and check if the imported binding has an instance sentinel.Hmm, this is getting complex. Let me focus on a simpler approach.
The issue says "Class methods called only from a Svelte
<template>via a member expression". The key insight is that the template uses a member expression on a bound instance.Let me look at the
analyze_template_snippet_with_bound_targetsfunction again. It remaps member accesses based onbound_targets. Butbound_targetsonly contains LOCAL bindings (fromtemplate_visible_bound_targets), not imported bindings.So when
resultStateis imported, it's NOT inbound_targets. The member accessresultState.pinstays as-is and doesn't get remapped toResultState.pin.The fix could be:
- When processing the SFC template, also check imported bindings for instance type information
- If an imported binding is known to be an instance of a class (via
INSTANCE_EXPORT_SENTINELor similar), add it to the remapping
But this requires access to the import resolution information during template scanning.
Actually, wait. Let me look at the existing code more carefully. In
analyze_template_snippet_with_bound_targets:fn remap_object_name( name: &str, unresolved_names: &FxHashSet<String>, bound_targets: &FxHashMap<String, String>, allow_dollar_prefixed_refs: bool, ) -> Option<String> { if unresolved_names.contains(name) { if let Some(target) = bound_targets.get(name) { return Some(target.clone()); } return Some(name.to_string()); } ... }If
nameis inunresolved_namesbut NOT inbound_targets, it returnsname.to_string(). So for an imported bindingresultState, the member access would becomeresultState.pin.Then in the analyzer, when processing
member_accesses, it looks for an export namedresultStatewith memberpin. But the export isresultState(the instance) in the Svelte file, not theResultStateclass in its source file.Wait, but the Svelte file doesn't EXPORT
resultState. It imports it. So the member accessresultState.pinis against an imported identifier, not a local class.Hmm, but the current test works because
counteris a LOCAL instance.counter -> Counteris inbound_targets, socounter.bumpbecomesCounter.bump, which is the local import binding.For the imported instance case:
resultStateis imported from./storeresultState.pin()is used in the templateresultStateis inimported_bindingsbut NOT inbound_targetsresultState.pinis NOT remapped- The member access
resultState.pindoesn't credit anything useful
The fix needs to:
- Know that
resultStateis an instance ofResultState - Remap
resultState.pintoResultState.pin - The analyzer then credits
ResultState.pinas used
One approach: use the
INSTANCE_EXPORT_SENTINELmechanism. WhenresultStateis exported from./store, it creates a sentinelINSTANCE_EXPORT_SENTINEL:resultState -> ResultState. WhenResultActionsMenu.svelteimportsresultState, we need to resolve this and add it to the bound targets for template scanning.Let me look at how the analyzer handles
INSTANCE_EXPORT_SENTINEL:<tool_call> <function=bash_terminal> <parameter=command> grep -n "INSTANCE_EXPORT_SENTINEL" /fallow/crates/core/src/analyze/unused_members.rs </tool_call>
Assistant
Let me search for the INSTANCE_EXPORT_SENTINEL usage in the unused_members.rs file to understand how imported instances are tracked.
Assistant
Let me look at how the INSTANCE_EXPORT_SENTINEL is used in the unused_members.rs to understand the flow for tracking exported instances.
Assistant
I see. Let me look at how the analyzer handles regular member accesses on imported bindings to understand the gap.
Assistant
Let me look at the main member access processing to understand how imported bindings with member accesses are handled.
Assistant
Let me look at the
resolve_typed_instance_chain_targetsfunction to understand how member accesses on imported instances are resolved.Assistant
Let me understand the
typed_instance_targetsto see how imported instances are tracked and resolved. This is key to understanding the gap.Assistant
I see - so
resolve_typed_instance_chain_targetsrequires theobject_nameto have at least one path segment after the root (see line 873-876). This means for a member access likeresultState.pin, theobject_namewould beresultStateandpath_segmentswould be empty, so it returns early.Wait, that doesn't seem right. Let me re-read the code...
Actually, looking at the code:
object_nameis split by.root_localis the first segment (e.g.,resultState)path_segmentsis the remaining segments (e.g., empty forresultState, or["url"]forresultState.url)
So for a simple access like
resultState(whole object use),path_segmentswould be empty and it returns early. But forresultState.pin, the member access has:object: "resultState"member: "pin"
And the
object_namepassed toresolve_typed_instance_chain_targetsisresultState, which has no path segments.Hmm, that's interesting. So
typed_instance_targetsis for CHAINED accesses likea.b.method()where we need to resolvea.bto a class.For simple
a.method()accesses, the flow is different. Let me look at how those are handled.Actually wait, let me re-read the
propagate_accesses_through_typed_instance_bindingsfunction. It skips sentinel objects and then callsresolve_typed_instance_chain_targets. But forresultState.pin, the object is justresultState, which has no dots, sopath_segmentsis empty and it returns early.This means typed instance bindings are only resolved for dotted chains like
store.resultState.pin(), not for simpleresultState.pin().For simple accesses, the flow would be:
resultState.pincreates aMemberAccess { object: "resultState", member: "pin" }- This member access is processed in the unused_members analysis
resolve_typed_instance_chain_targetsreturns empty becausepath_segmentsis empty- The member access is not resolved to any class
So the gap is: when
resultStateis a local binding (not imported), thebound_targetsremaps it to the class name. But whenresultStateis an imported binding, it's not inbound_targetsand the member access stays asresultState.pin.The fix should be: in the SFC template scanning, also check if the imported binding is an instance of a class (via type annotations or
newexpressions in the source file), and if so, add it to thebound_targetsfor remapping.But this requires information from the source file. The
INSTANCE_EXPORT_SENTINELmechanism provides this!When
const resultState = new ResultState()is in a .ts file andresultStateis exported, therecord_exported_instance_bindingsfunction creates:MemberAccess { object: "INSTANCE_EXPORT_SENTINEL:resultState", member: "ResultState" }So the export
resultStateis associated with the classResultState.In the consumer file (Svelte component), when
resultStateis imported, we need to know this association and use it for remapping.Actually, looking at the code flow again, the
build_instance_export_targetsfunction builds a map fromExportKeyto targetExportKeys. This map is used bypropagate_accesses_through_instance_exportsto propagate accesses.But the issue is that the template scanning happens BEFORE this analysis. The template scanner produces
member_accesseslikeresultState.pin, and these need to be resolved toResultState.pin.Wait, let me re-think this. The current test works because:
- In
App.svelte,const counter = new Counter()createsbinding_target_names: {counter -> Counter} - The template scanner remaps
counter.bumptoCounter.bump Counteris an import from./utils- The analyzer resolves
Counterto the class export and creditsCounter.bump
For the failing case:
- In
ResultActionsMenu.svelte,import { resultState } from './store'imports the instance resultStateis NOT inbinding_target_names(because it's an import, not a localnewexpression)- The template scanner does NOT remap
resultState.pin- it stays asresultState.pin - The analyzer tries to resolve
resultStatebut...
Actually, the analyzer does try to resolve
resultState. Let me look at what happens...In the analyzer,
member_accessesincludesresultState.pin. Thelocal_to_export_keysmap would haveresultStatemapping to the import target. But the import target is theresultStateexport from./store, not theResultStateclass.Hmm, but
resultStatein./storeis an instance export, not a class. The class isResultState. So the analyzer can't directly creditResultState.pinfromresultState.pin.Unless... the
INSTANCE_EXPORT_SENTINELmechanism bridges this gap. Let me look at how it works.build_instance_export_targetscreates a map where:- Key:
ExportKeyfor the instance export (e.g.,resultStatefrom./store) - Value:
ExportKeys for the target classes
Then
propagate_accesses_through_instance_exportstakes accesses on the instance export key and propagates them to the target class keys.So if we have:
- Member access:
resultState.pin resultStateresolves to export key./store#resultStateinstance_targetsmaps./store#resultStateto./ResultState#ResultState- The access
pinis propagated to./ResultState#ResultState
This SHOULD work! Let me check if the issue is elsewhere...
Actually, wait. Looking at the code again:
for resolved in resolved_modules { let local_to_export_keys = build_local_to_export_keys(resolved); for access in &resolved.member_accesses { ... for target_key in resolve_typed_instance_chain_targets( graph, &typed_instance_targets, &local_to_export_keys, &access.object, ) { accessed_members .entry(target_key) .or_default() .insert(access.member.clone()); } } }For
resultState.pin, the object isresultState.resolve_typed_instance_chain_targetssplits by.:root_local=resultStatepath_segments= [] (empty)- Returns early because
path_segments.is_empty()
So it returns empty! The typed instance chain resolution only works for DOTTED chains like
a.b.method(), not for simplea.method().This is the bug! The
resolve_typed_instance_chain_targetsfunction returns early when there are no path segments after the root, which means simpleresultState.pinaccesses are not resolved through typed instance bindings.But wait, there's also the
propagate_accesses_through_instance_exportsfunction. Let me check if it handles this case...Looking at
propagate_accesses_through_instance_exports:fn propagate_accesses_through_instance_exports( instance_targets: &FxHashMap<ExportKey, Vec<ExportKey>>, accessed_members: &mut FxHashMap<ExportKey, FxHashSet<String>>, ... ) { ... for (instance_key, members) in accessed_snapshot { let Some(target_keys) = instance_targets.get(&instance_key) else { continue; }; for target_key in target_keys { accessed_members .entry(target_key.clone()) .or_default() .extend(members.iter().cloned()); } } }This takes
accessed_memberskeyed byExportKeyand propagates to target class keys. But the member accesses from the template (resultState.pin) need to be inaccessed_membersfirst!The flow would be:
- Template produces
MemberAccess { object: "resultState", member: "pin" } - This is in
resolved.member_accessesfor the Svelte file - The analyzer processes this and needs to add
pintoaccessed_membersfor the right key
But the current code in
propagate_accesses_through_typed_instance_bindingscallsresolve_typed_instance_chain_targetswhich returns empty for simpleresultState(no path segments).So the member access
resultState.pinis NOT added toaccessed_membersat all. It's lost!Hmm, but there's also a simpler path. Let me look at the regular member access handling (not the typed instance path)...
Actually, looking at the code around line 914:
for target_key in resolve_typed_instance_chain_targets( graph, &typed_instance_targets, &local_to_export_keys, &access.object, ) { accessed_members .entry(target_key) .or_default() .insert(access.member.clone()); }This is the ONLY place where regular (non-sentinel) member accesses are added to
accessed_members. Andresolve_typed_instance_chain_targetsreturns empty for simple objects without dots.So for
resultState.pin, nothing is added toaccessed_members. The member access is effectively ignored!Wait, that can't be right. The test passes for
Counter.bump...Oh, I see! For the test case, the template scanner remaps
counter.bumptoCounter.bumpbecausecounter -> Counteris inbound_targets. So the member access object isCounter, which is a local import binding.Then in the analyzer,
local_to_export_keysmapsCounterto the class export key. Andresolve_typed_instance_chain_targetsis called withobject = "Counter":root_local=Counterpath_segments= [] (empty)- Returns early!
But wait, that means it should also return empty for
Counter! How does the test pass then?Hmm, let me re-read the code more carefully. Actually,
typed_instance_targetsis a different structure. Let me look at how it's built...<tool_call>
Actually wait, I realize I've been confused. Let me trace through more carefully. For the test case: 1. `counter.bump()` in template → `MemberAccess { object: "Counter", member: "bump" }` (remapped by template scanner) 2. `Counter` is in `local_to_export_keys`, mapping to the class export key 3. `resolve_typed_instance_chain_targets` is called with `object = "Counter"`: - `root_local` = `"Counter"` - `path_segments` = `[]` (empty) - Returns empty because `path_segments.is_empty()` So the member access is NOT resolved through typed instance chains. But the test still passes! So there must be another mechanism. Let me look at what other mechanisms add to `accessed_members`...Actually, let me look at the code more carefully. I was focused on
resolve_typed_instance_chain_targetsbut there might be other paths.<tool_call> <function=bash_terminal> <parameter=command> sed -n '1530,1600p' /fallow/crates/core/src/analyze/unused_members.rs </tool_call>
Assistant
Let me search for how member accesses are processed and added to accessed_members to understand the complete flow.
Assistant
Let me look at what
merge_intodoes compared tointo_module_infoto understand the difference.Assistant
I found it! The key is at lines 1563-1572:
if let Some(export_keys) = local_to_export_keys.get(access.object.as_str()) { for export_key in export_keys { accessed_members .entry(export_key.clone()) .or_default() .insert(access.member.clone()); } }So when a member access like
Counter.bumpcomes in:access.object="Counter"local_to_export_keys.get("Counter")returns the export key for theCounterclassaccessed_membersgetsbumpadded for theCounterexport key
This is how the test passes! The template scanner remaps
counter.bumptoCounter.bump, and then the analyzer looks upCounterinlocal_to_export_keysand addsbumptoaccessed_membersfor theCounterclass.Now I understand the issue. For the test case:
- Template:
counter.bump() - Template scanner remaps:
Counter.bump(becausecounter -> Counteris inbound_targets) - Analyzer:
Counteris inlocal_to_export_keys(it's an import), sobumpis credited toCounter
For the failing case:
- Template:
resultState.pin() - Template scanner: does NOT remap (because
resultStateis NOT inbound_targets) - Member access:
resultState.pin - Analyzer:
resultStateIS inlocal_to_export_keys(it's an import) - But
resultStatemaps to the INSTANCE export, not the CLASS export - So
pinis credited toresultState(the instance), notResultState(the class)
The fix could be in the analyzer: when a member access is on an instance export (not a class), look up the instance's class type and credit the class instead.
This is what
propagate_accesses_through_instance_exportsdoes! It takes accesses that were credited to instance exports and propagates them to the target class.Let me verify:
build_instance_export_targetsbuilds a map from instance export keys to class export keys. Thenpropagate_accesses_through_instance_exportstakesaccessed_membersentries for instance exports and extends them to the target class exports.So the flow should be:
- Template produces
MemberAccess { object: "resultState", member: "pin" } - Analyzer adds
pintoaccessed_membersforresultStateexport key instance_targetsmapsresultStateexport key toResultStateclass export keypropagate_accesses_through_instance_exportspropagatespintoResultStateclass
This SHOULD work! So why doesn't it?
Let me check if
record_exported_instance_bindingsis called for the file that exportsresultState. This function creates theINSTANCE_EXPORT_SENTINELentries thatbuild_instance_export_targetsuses.The function
record_exported_instance_bindingsis called ininto_module_info(). For regular .ts files,into_module_info()is called. But for SFC script blocks, onlymerge_into()is called (insfc.rs), which does NOT call the resolve functions.Wait, but the file that EXPORTS
resultStateis a regular .ts file (like./store.ts), not an SFC. Sointo_module_info()IS called for it, andrecord_exported_instance_bindingsruns.So the
INSTANCE_EXPORT_SENTINELentries should exist for the exporting file. Andbuild_instance_export_targetsshould build the right map.Let me look at
build_instance_export_targetsmore carefully...Actually wait, I just realized something. The
INSTANCE_EXPORT_SENTINELentries are created byrecord_exported_instance_bindings, which runs ininto_module_info(). This function:fn record_exported_instance_bindings(&mut self) { if self.binding_target_names.is_empty() { return; } let additional_accesses: Vec<MemberAccess> = self .exports .iter() .filter_map(|export| { let local_name = export.local_name.as_deref()?; let target_name = self.binding_target_names.get(local_name)?; Some(MemberAccess { object: format!("{}{}", crate::INSTANCE_EXPORT_SENTINEL, export.name), member: target_name.clone(), }) }) .collect(); self.member_accesses.extend(additional_accesses); }So for an export like
export { resultState }whereconst resultState = new ResultState(), it creates:MemberAccess { object: "INSTANCE_EXPORT_SENTINEL:resultState", member: "ResultState" }
This sentinel entry maps the exported instance to its class type.
Then
build_instance_export_targetsprocesses these sentinel entries and builds thetargets_by_instancemap.So far so good. Now
propagate_accesses_through_instance_exportstakes theaccessed_membersthat were added forresultState(from the template member access) and propagates them to the target class.Wait, but let me check:
propagate_accesses_through_instance_exportsis called AFTER the regular member access processing (line 1607). And the regular processing addspintoaccessed_membersforresultState's export key. Thenpropagate_accesses_through_instance_exportsshould propagate this toResultState's export key.So theoretically it should work! Unless...
Oh! I think I see the issue. Let me check: what's the export name in the sentinel?
record_exported_instance_bindingsusesexport.name, which forexport { resultState }would beNamed("resultState"). So the sentinel isINSTANCE_EXPORT_SENTINEL:resultState.But
export.nameis the EXPORTED name, not the local name. Forexport { resultState }, both areresultState. But forexport { resultState as rs }, the exported name isrsand the local name isresultState.And
binding_target_namesuses the LOCAL name (resultState). So the mapping is:- Local name:
resultState - Binding target:
ResultState(class) - Export name:
resultState
The sentinel is
INSTANCE_EXPORT_SENTINEL:resultStatewith memberResultState.And in
build_instance_export_targets:let instance_key = ExportKey::new(resolved.file_id, instance_export_name);So
instance_keyis(file_id, "resultState").Then when we look up
local_to_export_keys.get("resultState")in the Svelte file, we get the import target: theresultStateexport from./store.And then
pinis added toaccessed_membersfor that export key.Then
propagate_accesses_through_instance_exportslooks upinstance_targetsfor that key and propagates to the class.This SHOULD work! Let me check if there's a bug in the propagation...
Actually, let me re-read
propagate_accesses_through_instance_exports:fn propagate_accesses_through_instance_exports( instance_targets: &FxHashMap<ExportKey, Vec<ExportKey>>, accessed_members: &mut FxHashMap<ExportKey, FxHashSet<String>>, whole_object_used_exports: &mut FxHashSet<ExportKey>, ) { ... let accessed_snapshot: Vec<(ExportKey, Vec<String>)> = accessed_members .iter() .map(|(key, members)| (key.clone(), members.iter().cloned().collect())) .collect(); for (instance_key, members) in accessed_snapshot { let Some(target_keys) = instance_targets.get(&instance_key) else { continue; }; for target_key in target_keys { accessed_members .entry(target_key.clone()) .or_default() .extend(members.iter().cloned()); } } }Wait, this iterates over ALL
accessed_membersentries and checks if each key is ininstance_targets. IfresultState's export key is ininstance_targets, it propagates to the class.But here's the thing:
instance_targetsis built fromINSTANCE_EXPORT_SENTINELentries inbuild_instance_export_targets. And those sentinel entries are in the EXPORTING file'smember_accesses, not in the importing file's.So
instance_targetsmaps:./store#resultState→[./ResultState#ResultState]
And
accessed_membersafter processing the Svelte file has:./store#resultState→{"pin"}
So
propagate_accesses_through_instance_exportsshould find./store#resultStateininstance_targetsand propagatepinto./ResultState#ResultState.This should work! Let me verify by looking at
build_instance_export_targetsmore carefully...fn build_instance_export_targets( graph: &ModuleGraph, resolved_modules: &[ResolvedModule], ) -> FxHashMap<ExportKey, Vec<ExportKey>> { let mut targets_by_instance: FxHashMap<ExportKey, Vec<ExportKey>> = FxHashMap::default(); for resolved in resolved_modules { let local_to_export_keys = build_local_to_export_keys(resolved); for access in &resolved.member_accesses { let Some(instance_export_name) = access.object.strip_prefix(INSTANCE_EXPORT_SENTINEL) else { continue; }; let Some(target_keys) = local_to_export_keys.get(access.member.as_str()) else { continue; }; let instance_key = ExportKey::new(resolved.file_id, instance_export_name); let instance_targets = targets_by_instance.entry(instance_key).or_default(); for target_key in target_keys { for key in export_key_with_origins(graph, target_key) { push_export_key(instance_targets, key); } } } } targets_by_instance }OK so this looks at the EXPORTING file's
member_accesses. The sentinel entry is:object: "INSTANCE_EXPORT_SENTINEL:resultState"member: "ResultState"
And
local_to_export_keys.get("ResultState")should return the export key for theResultStateclass in the same file (if it's also exported) or in an imported file.Wait, but
ResultStatemight be defined in a different file and imported into./store.ts. In that case,local_to_export_keysin./store.tswould mapResultStateto the imported class export.Actually,
ResultStatemight be defined in the SAME file as the instance, or in a separate file. Let me think about both cases:Case 1: Same file
// store.ts export class ResultState { ... } const resultState = new ResultState(); export { resultState };binding_target_names:{resultState: "ResultState"}exports:ResultState,resultStaterecord_exported_instance_bindingscreates:MemberAccess { object: "INSTANCE_EXPORT_SENTINEL:resultState", member: "ResultState" }build_instance_export_targets:local_to_export_keys.get("ResultState")returns theResultStateclass export key
Case 2: Separate files
// ResultState.ts export class ResultState { ... }// store.ts import { ResultState } from './ResultState'; const resultState = new ResultState(); export { resultState };- Same as above,
local_to_export_keys.get("ResultState")returns the imported class export key
Both cases should work. So the issue must be elsewhere...
Wait, actually, I think I might have been wrong about the issue. Let me re-read the issue description:
Class methods called only from a Svelte
<template>via a member expression (for exampleresultState.pin(...)in markup) are reported asunused-class-member. Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.The key phrase is "bound instance inside Svelte markup". This means
resultStateis a LOCAL binding in the Svelte component, not an imported one. It's bound (created) in the script block.So the scenario is:
<script> import { ResultState } from './ResultState'; const resultState = new ResultState(); </script> {resultState.pin(...)}In this case:
resultStateis a localnew ResultState()in the Svelte scriptbinding_target_namesshould have{resultState: "ResultState"}template_visible_bound_targetsshould have{resultState: "ResultState"}- The template scanner should remap
resultState.pintoResultState.pin
This is exactly the same as the test fixture! So why doesn't it work?
Let me check if there's something different about how
binding_target_namesis populated for SFC scripts...Actually, let me look at
merge_intovsinto_module_infomore carefully.Looking at
merge_intoat line 851:pub(crate) fn merge_into(mut self, info: &mut ModuleInfo) {And
into_module_infoat line 789:pub(crate) fn into_module_info(...) -> ModuleInfo { ... self.resolve_pending_local_export_specifiers(); self.enrich_local_class_exports(); self.record_exported_instance_bindings(); self.resolve_object_binding_candidates(); self.resolve_factory_call_candidates(); self.resolve_playwright_factory_call_definitions(); self.resolve_bound_member_accesses(); self.map_local_signature_refs_to_exports(); self.apply_side_effect_registrations(); let namespace_object_aliases = self.collect_namespace_object_aliases(); ... }So
into_module_infocalls many resolve functions thatmerge_intodoesn't! Let me checkmerge_into:pub(crate) fn merge_into(mut self, info: &mut ModuleInfo) { info.exports.extend(self.exports); info.imports.extend(self.imports); ... }So
merge_intojust copies fields directly, WITHOUT calling the resolve functions!But wait,
binding_target_namesis populated during the AST walk (visit_variable_declaration), not in the resolve functions. Sobinding_target_namesshould still be populated even when usingmerge_into.Actually, let me double-check. In
visit_variable_declaration, the code at line 2052-2061 inserts intobinding_target_names:if let Expression::NewExpression(new_expr) = init && let Expression::Identifier(callee) = &new_expr.callee && let BindingPattern::BindingIdentifier(id) = &declarator.id && !super::helpers::is_builtin_constructor(callee.name.as_str()) { self.binding_target_names .insert(id.name.to_string(), callee.name.to_string()); }This is called during
visit_program, which IS called in the SFC script parsing. Sobinding_target_namesshould be populated.And then in
merge_script_into_module,binding_target_names()is called:template_visible_bound_targets.extend( extractor .binding_target_names() .iter() .filter(|(local, _)| !local.starts_with("this.")) .map(|(local, target)| (local.clone(), target.clone())), );And
binding_target_names()just returns&self.binding_target_names. So the data should be there.So why doesn't it work? Let me think...
Oh wait! Let me check if
merge_intocopiesbinding_target_namesto theModuleInfo!Actually, looking at the code:
template_visible_bound_targets.extend( extractor .binding_target_names() ... );It copies
binding_target_namestotemplate_visible_bound_targets, which is a LOCAL variable in the function. Then it's passed toapply_template_usage:apply_template_usage( kind, source, &template_visible_imports, &template_visible_bound_targets, &mut combined, );And
apply_template_usagepasses it to the template scanner:let template_usage = collect_template_usage_with_bound_targets( kind, source, template_visible_imports, template_visible_bound_targets, );So
template_visible_bound_targetsIS used for remapping!Hmm, so the data flow looks correct. Let me verify by checking if there's any issue with the actual test.
Actually, wait. Let me re-read the test fixture more carefully:
<script lang="ts"> import FancyButton from './FancyButton.svelte'; import { isActive } from './utils'; import { tooltip } from './utils'; import { myAttach, Counter, inTernary, inCallback, inSpread } from './utils'; import * as utils from './utils'; import { unusedImported } from './utils'; import type { Greeting } from './types'; let name = 'world'; const counter = new Counter(); const greeting: Greeting = { recipient: name }; </script>So
counter = new Counter()creates the binding. Andcounter.bump()andcounter.valueare used in the template.The test
svelte_template_event_handlers_mark_class_members_usedchecks:Counter.bumpis NOT unused ✓Counter.valueis NOT unused ✓Counter.unusedIS unused ✓
And this test PASSES! So the basic case works.
So what's different in the hister case? The issue says "resultState.pin(...)" but maybe the pattern is different...
Actually, you know what, let me just look at what patterns might NOT be captured by
visit_variable_declaration. MayberesultStateis created differently, like:- Through a reactive statement:
$: resultState = new ResultState() - Through a function call:
const resultState = createResultState() - Through a getter:
get resultState() { return new ResultState() }
Let me check if reactive statements are handled...
Actually, reactive statements in Svelte use
$:prefix and are NOT standard JavaScript variable declarations. They wouldn't be captured byvisit_variable_declaration!Let me check if Svelte reactive statements are handled specially...
Hmm, reactive statements are parsed as Svelte-specific syntax. They might not be in the standard AST that
oxc_parserhandles. Sobinding_target_namesmight not capture$: resultState = new ResultState().But wait, the issue description says "bound instance inside Svelte markup" which could also mean reactive statements.
Actually, I think the key insight is that the existing code DOES work for
const x = new ClassName()in SFC scripts. But there might be OTHER patterns that don't work:$: x = new ClassName()(reactive statement)const x = factory()(factory function, notnew)x = new ClassName()(assignment, not declaration)
Let me check if pattern 3 (assignment) is handled...
Looking at the code around line 2471, assignments like
this.field = new ClassName()are handled. But what aboutresultState = new ResultState()whereresultStatewas already declared?Actually, let me check what happens with
let resultState; resultState = new ResultState();. Thelet resultState;declaration doesn't have an initializer, sovisit_variable_declarationwouldn't capture the binding target. The assignmentresultState = new ResultState()is an assignment expression, not a variable declaration.Let me look at how assignment expressions are handled...
Looking at line 2471:
if let Expression::NewExpression(new_expr) = &expr.right && let Expression::Identifier(callee) = &new_expr.callee && !super::helpers::is_builtin_constructor(callee.name.as_str()) { self.binding_target_names.insert( format!("this.{}", member.property.name), callee.name.to_string(), ); }This handles
this.field = new ClassName(), but what about plainresultState = new ResultState()?Actually, this code is inside
visit_assignment_expressionand it checksif matches!(member.object, Expression::ThisExpression(_)). So it only handlesthis.field = new ClassName(), not plainresultState = new ResultState().So there might be patterns that aren't captured. But for the basic
const resultState = new ResultState()case, it should work.OK, I think I need to actually try to reproduce the issue. Let me create a test case that might trigger the bug and see what happens.
Actually, wait. Let me re-read the issue description one more time very carefully:
Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.
Hmm, "template-visible identifiers" - this suggests that the identifier
resultStateIS tracked. IfresultStateis in the template, it would be added toused_bindingsand the import wouldn't be flagged.But "member-expression method calls on a bound instance" - this suggests that
resultState.pin()is NOT tracked to creditResultState.pin.Wait, could it be that
resultStateis imported as an ALREADY-CREATED instance, not a localnewexpression? Like:// store.ts import { ResultState } from './ResultState'; const resultState = new ResultState(); export { resultState };<!-- ResultActionsMenu.svelte --> <script> import { resultState } from './store'; </script> {resultState.pin(...)}In this case:
resultStateis imported, not created locally in the Svelte filebinding_target_namesin the Svelte file would NOT haveresultState -> ResultStatetemplate_visible_bound_targetswould NOT haveresultState -> ResultState- The template scanner would NOT remap
resultState.pintoResultState.pin - The member access would stay as
resultState.pin
And then in the analyzer:
resultStateis inlocal_to_export_keys, mapping to./store#resultStatepinis added toaccessed_membersfor./store#resultState- But
./store#resultStateis NOT a class, it's an instance export propagate_accesses_through_instance_exportsshould propagate to./ResultState#ResultState
Wait, does the propagation happen? Let me check if the sentinel is created correctly for the
./store.tsfile...In
./store.ts:const resultState = new ResultState();→binding_target_names: {resultState: "ResultState"}export { resultState };→ export with local nameresultStaterecord_exported_instance_bindingsruns ininto_module_info():- Creates
MemberAccess { object: "INSTANCE_EXPORT_SENTINEL:resultState", member: "ResultState" }
- Creates
Then
build_instance_export_targets:- Processes
./store.ts's member_accesses - Finds sentinel
INSTANCE_EXPORT_SENTINEL:resultStatewith memberResultState local_to_export_keys.get("ResultState")in./store.tsshould return the import target ofResultState
But wait,
ResultStateis IMPORTED in./store.ts. Solocal_to_export_keys.get("ResultState")would return the export key of the imported class.So
instance_targetswould have:./store#resultState→[./ResultState#ResultState]
And in the Svelte file:
resultStateis imported from./storeresultState.pincreatesMemberAccess { object: "resultState", member: "pin" }- In the analyzer,
local_to_export_keys.get("resultState")returns./store#resultState pinis added toaccessed_membersfor./store#resultStatepropagate_accesses_through_instance_exportspropagatespinfrom./store#resultStateto./ResultState#ResultState
This should work! So why doesn't it?
Hmm, let me check if there's an issue with how member accesses from SFC templates are merged into
ModuleInfo.member_accesses...Actually, let me look at
apply_template_usage:fn apply_template_usage( kind: SfcKind, source: &str, template_visible_imports: &FxHashSet<String>, template_visible_bound_targets: &FxHashMap<String, String>, combined: &mut ModuleInfo, ) { let template_usage = collect_template_usage_with_bound_targets( kind, source, template_visible_imports, template_visible_bound_targets, ); combined .unused_import_bindings .retain(|binding| !template_usage.used_bindings.contains(binding)); combined .member_accesses .extend(template_usage.member_accesses); combined .whole_object_uses .extend(template_usage.whole_object_uses); ... }So
template_usage.member_accessesis extended intocombined.member_accesses. This includes the remapped accesses.Wait, but if
resultStateis NOT inbound_targets(because it's an import), thenresultState.pinwould NOT be remapped. Let me check what the template scanner produces forresultState.pin(...)whenresultStateis NOT inbound_targets:In
analyze_template_snippet_with_bound_targets:resultStateis inimported_bindings- When the snippet is parsed,
resultStateis an unresolved reference (not declared in wrapper) resultStateis found inimported_bindings, so it's added toused_bindingsandunresolved_targetsresultState.pinis a member access with objectresultStateremap_object_name("resultState", unresolved_targets, bound_targets, ...)is called:resultStateis inunresolved_names(since it's inunresolved_targets)bound_targets.get("resultState")returnsNone(because it's an import, not a local binding)- Returns
Some("resultState".to_string())
- The member access becomes
{ object: "resultState", member: "pin" }
So the member access stays as
resultState.pinwith the import name, not the class name.Then in the analyzer:
local_to_export_keys.get("resultState")returns./store#resultStatepinis added toaccessed_membersfor./store#resultState./store#resultStateis NOT a class (it has no members)- The
ResultState.pinmethod is NOT credited
But
propagate_accesses_through_instance_exportsshould fix this! Let me check again...Actually, wait.
propagate_accesses_through_instance_exportstakesaccessed_membersentries and propagates them based oninstance_targets. The key question is: is./store#resultStateininstance_targets?instance_targetsis built fromINSTANCE_EXPORT_SENTINELentries. In./store.ts, the sentinel is created forresultState→ResultState. So./store#resultStateshould be ininstance_targetsmapping to./ResultState#ResultState.But wait, the export name in the sentinel is
export.name, not the local name. Let me check:fn record_exported_instance_bindings(&mut self) { ... for export in &self.exports { let local_name = export.local_name.as_deref()?; let target_name = self.binding_target_names.get(local_name)?; Some(MemberAccess { object: format!("{}{}", crate::INSTANCE_EXPORT_SENTINEL, export.name), member: target_name.clone(), }) } ... }So
export.nameis used for the sentinel object. Andlocal_nameis used to look up inbinding_target_names.For
export { resultState }:export.name=Named("resultState")export.local_name=Some("resultState")binding_target_names.get("resultState")=Some("ResultState")- Sentinel:
INSTANCE_EXPORT_SENTINEL:resultStatewith memberResultState
And in
build_instance_export_targets:let instance_key = ExportKey::new(resolved.file_id, instance_export_name);So
instance_key=(./store file_id, "resultState").And when processing the Svelte file's member access:
local_to_export_keys.get("resultState")returns theExportKeyforresultStateimported from./store- This is
(./store file_id, "resultState")
So the keys should match! And
propagate_accesses_through_instance_exportsshould propagatepintoResultState.Hmm, so theoretically this should work. Let me check if there's something wrong with the export key resolution...
Actually, wait. Let me check
export.name.to_string()vsExportKey:In
record_exported_instance_bindings:object: format!("{}{}", crate::INSTANCE_EXPORT_SENTINEL, export.name),export.nameis anExportNameenum. ItsDisplayimpl would produce the string representation.And in
build_instance_export_targets:let instance_export_name = access.object.strip_prefix(INSTANCE_EXPORT_SENTINEL); let instance_key = ExportKey::new(resolved.file_id, instance_export_name);So
instance_export_nameis a&str, andExportKey::newtakes a file ID and a&str(the export name).Let me check
ExportKey::new:pub fn new(file_id: FileId, export_name: impl Into<String>) -> Self { Self { file_id, export_name: export_name.into(), } }So it converts to
String. AndExportKeyhasexport_name: String.Now, when processing the Svelte file's member access,
local_to_export_keys.get("resultState")returns the export key. Let me checkbuild_local_to_export_keys:fn build_local_to_export_keys( resolved: &ResolvedModule, ) -> FxHashMap<&str, Vec<ExportKey>> {This builds a map from local names to export keys. For an import like
import { resultState } from './store', the local nameresultStatemaps to the export key of theresultStateexport from./store.Let me check if the export name strings match. In the exporting file,
export.nameisNamed("resultState"), andformat!("{}", export.name)would produce"resultState". In the importing file,local_to_export_keys.get("resultState")uses"resultState".So the strings should match. And the
ExportKeyshould be(./store file_id, "resultState").I'm starting to think the issue might be something else entirely. Let me actually look at what might be different in the hister case...
Actually, I just realized something. Let me re-read the issue:
ResultState.onOpen,.pin,.updateLabel, and.addSkipRuleare each invoked from.sveltetemplates (resultState.pin(...)inResultActionsMenu.svelte)So
resultStateis the instance andResultStateis the class. And the methods areonOpen,pin,updateLabel,addSkipRule.The issue says these are "invoked from
.sveltetemplates". So the template hasresultState.pin(...)etc.And the issue says these are "reported as
unused-class-member". SoResultState.onOpen,ResultState.pin, etc. are reported as unused.The question is: how is
resultStatedefined? Is it a localnew ResultState()or an imported instance?If
resultStateis a LOCALnew ResultState()in the Svelte script, then:binding_target_nameshasresultState -> ResultStatetemplate_visible_bound_targetshasresultState -> ResultState- Template scanner remaps
resultState.pintoResultState.pin ResultStateis inlocal_to_export_keyspinis credited toResultState
This should work! So if the issue persists, either:
resultStateis NOT a localnewexpression- Or there's a bug in the remapping/crediting
But the test passes for the same pattern (
const counter = new Counter()). So either the hister case is different, or there's a subtle bug.Actually, you know what, let me look at a different possibility. What if
ResultStateis defined in the SAME Svelte file as where it's used? Like:<script> class ResultState { pin() { ... } } const resultState = new ResultState(); </script> {resultState.pin(...)}In this case,
ResultStateis a LOCAL class (not exported). AndresultStateis a local instance. The template scanner would remapresultState.pintoResultState.pin. ButResultStateis not exported, solocal_to_export_keys.get("ResultState")wouldn't return anything, andpinwouldn't be credited.But wait, the unused-class-members rule only applies to EXPORTED classes. A local class wouldn't be reported as having unused members.
Hmm, OK I'm going in circles. Let me take a different approach and actually look at the code to find the gap.
The issue says "Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup."
The test shows that
counter.bump()IS tracked. So what's different?Actually, let me look at what EXACTLY the test checks. It checks
Counter.bumpandCounter.value.Counteris a CLASS imported from./utils.counteris a LOCAL instance created withnew Counter().In the hister case,
ResultStateis the CLASS andresultStateis the INSTANCE. IfresultStateis also created withnew ResultState()locally, it should work the same way.Unless...
ResultStateis NOT imported in the Svelte file. Maybe it's defined in the same file, or imported through a different mechanism.Actually, let me just create a test case that tries to reproduce the issue and see what happens.
Actually, I think I now understand the issue better. Let me look at the template scanning code more carefully.
In
collect_template_usage_with_bound_targetsfor Svelte, the function signature is:pub(super) fn collect_template_usage_with_bound_targets( source: &str, imported_bindings: &FxHashSet<String>, bound_targets: &FxHashMap<String, String>, ) -> TemplateUsage {And it checks:
if imported_bindings.is_empty() && bound_targets.is_empty() { return TemplateUsage::default(); }So if BOTH are empty, it returns early. But in the hister case,
imported_bindingsmight not be empty (because the file has imports), so it wouldn't return early.Now, let me trace through what happens when
resultStateis an imported binding:resultStateis inimported_bindingsbound_targetsdoesn't haveresultState -> ResultState(becauseresultStateis imported, not created locally)- When parsing
resultState.pin(...),resultStateis unresolved (not declared in wrapper) resultStateis inimported_bindings, so it's added toused_bindingsandunresolved_targets- The member access
resultState.pinis collected remap_object_name("resultState", ...)returnsSome("resultState")because it's inunresolved_namesbut not inbound_targets- Member access:
{ object: "resultState", member: "pin" }
So the member access stays as
resultState.pin. Then in the analyzer:local_to_export_keys.get("resultState")returns the export key for the importedresultStatepinis added toaccessed_membersfor that export key- The propagation to the target class happens via
propagate_accesses_through_instance_exports
Wait, but does
resultStatehave members? IfresultStateis an instance export (not a class), it wouldn't have any members defined in itsExportInfo. So the unused-class-members rule wouldn't apply toresultStatedirectly.The issue is that
ResultState.pinis reported as unused. This means the analyzer didn't creditpintoResultState.So the gap is in the propagation step.
propagate_accesses_through_instance_exportsshould propagatepinfromresultStatetoResultState, but it's not happening.Let me check if the
INSTANCE_EXPORT_SENTINELis actually being created...Actually, I think the issue might be that
record_exported_instance_bindingsis NOT called for SFC files! Let me verify.In
sfc.rs, the functionmerge_script_into_moduledoes:extractor.visit_program(&parser_return.program); ... extractor.merge_into(combined);It does NOT call
into_module_info(), which is whererecord_exported_instance_bindings()is called.So for SFC files,
record_exported_instance_bindings()is never called! This means SFC files don't createINSTANCE_EXPORT_SENTINELentries for their exports.But wait, the instance is in the SFC file, and the class is in a separate .ts file. The SFC file creates
resultState = new ResultState(), but theResultStateclass is defined elsewhere.If the SFC file also exports
resultState, thenrecord_exported_instance_bindingswould create the sentinel. But SFC files typically don't export instances - they use them locally.Hmm, but the issue says the methods are called in templates. Let me think about this differently.
In the hister case:
ResultStateis a class defined in some .ts fileResultActionsMenu.svelteusesresultState.pin(...)in its templateresultStateis defined somewhere...
If
resultStateis a LOCALnew ResultState()in the Svelte script, then:- Template scanner remaps
resultState.pintoResultState.pin ResultStateis an import, solocal_to_export_keys.get("ResultState")returns the class export keypinis credited toResultState- This should work!
So if the issue persists, either:
resultStateis NOT a localnew ResultState()- Or there's a bug I haven't found
OK I'm going to take a step back and look at this from the Vue perspective, since the issue says "parallel to the existing Vue/Angular template member-access tracking."
The Vue test also uses
const counter = new Counter()and the template usescounter.bump(). This works for both Vue and Svelte.So what's different in hister? Without seeing the actual code, I can only guess. But the issue says "bound instance inside Svelte markup", which suggests it's a local binding.
Actually wait, I just realized I should look at the issue from a different angle. The issue says:
Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.
What if "bound instance" refers to the binding in the script, but the binding is NOT captured by
binding_target_namesbecause it's a different pattern?For example:
<script> import { writable } from 'svelte/store'; import { ResultState } from './ResultState'; const resultState = writable(new ResultState()); </script> {$resultState.subscribe(v => v.pin())}In this case,
resultStateis a Svelte store, not a direct instance.binding_target_nameswouldn't haveresultState -> ResultStatebecauseresultState = writable(...)is a function call, not anewexpression.Or:
<script> import { ResultState } from './ResultState'; let resultState; $: resultState = new ResultState(); </script> {resultState.pin(...)}In this case,
resultState = new ResultState()is in a reactive statement, not a variable declaration.visit_variable_declarationwouldn't capture it.Hmm, but these are edge cases. Let me focus on the basic case first and make sure it works.
Actually, I just had another thought. What if the issue is that
ResultStateis a NAMED export from a class file, and the template scanner remapsresultState.pintoResultState.pin, butlocal_to_export_keysin the Svelte file doesn't haveResultState?Wait,
local_to_export_keysmaps local names to export keys. IfResultStateis imported in the Svelte script, it would be inlocal_to_export_keys.OK let me just create a test case and see what happens.
Actually, I think the issue might be that the Svelte test passes because
Counteris defined inutils.tsand exported. But in hister, maybeResultStateis defined differently or the import structure is different.Let me look at another angle. The issue mentions that the repo sets
rules.unused-class-members: "off"to work around it. This means ALL class members would be affected, not just specific ones. But the issue specifically mentionsResultState.onOpen,.pin,.updateLabel,.addSkipRule.Hmm, setting the rule to "off" disables all unused class member checks. So either ALL class methods called from Svelte templates are reported as unused, or at least the specific ones mentioned.
Let me look at this from a fresh perspective. What if the issue is NOT about
const x = new X()pattern, but about a different pattern where the instance is created and assigned to a variable that's NOT captured bybinding_target_names?For example, what if hister uses:
<script> import { ResultState } from './ResultState'; import { getInitialState } from './store'; const resultState = new ResultState(getInitialState()); </script> {resultState.pin(...)}This is still
const resultState = new ResultState(...), so it should be captured byvisit_variable_declarationandbinding_target_namesshould haveresultState -> ResultState.Or maybe:
<script> import { ResultState } from './ResultState'; const state = { result: new ResultState() }; </script> {state.result.pin(...)}This is
state.result.pin(). Thenew ResultState()is inside an object literal, not directly assigned to a variable.binding_target_nameswouldn't havestate.result -> ResultState.Hmm, but the issue says
resultState.pin(...), notstate.result.pin(...). So it's a simple access, not a chain.OK I think I need to actually create a test and see what happens. Let me do that.
Actually, let me first check if there are any existing tests for the member access propagation via
INSTANCE_EXPORT_SENTINEL:<tool_call> <function=bash_terminal> <parameter=command> grep -rn "INSTANCE_EXPORT_SENTINEL" /fallow/crates/core/tests --include="*.rs" | head -20 </tool_call>
Assistant
Let me search for tests related to INSTANCE_EXPORT_SENTINEL to understand how exported instance bindings are tested.
Assistant
No tests found for INSTANCE_EXPORT_SENTINEL in the core tests. Let me search for tests related to instance export bindings or exported instances.
Assistant
Let me look at the existing test for exported instance class members and understand the fixture.
Assistant
Let me look at the fixture for this test to understand how exported instance class members are tracked. This will help me understand the expected behavior and potentially identify the gap with Svelte template member access.
Assistant
Let me look at the exported-instance-class-members fixture to understand how it works.
Assistant
Let me look at the other files in the fixture to understand the complete pattern.
Assistant
Let me continue examining the fixture to understand the complete pattern for exported instance class members.
Assistant
Now I understand the pattern. The
exported-instance-class-membersfixture shows how exported instance bindings work:box.tsexports theBoxclassinstance.tscreates and exportsconst box = new Box()index.tsimportsboxand callsbox.bump()
The
INSTANCE_EXPORT_SENTINELmechanism bridges the gap between the instance export and the class. Let me create a test case that uses a Svelte template to access the exported instance to see if this works:Assistant
Let me understand the issue better by creating a test case that reproduces it. The current test works for local
newexpressions, but the issue might be about imported instances. Let me create a test fixture for this:Assistant
Let me create a test fixture that reproduces the issue described. Based on my analysis, the issue might be about:
- Local
newexpressions in Svelte scripts - these should work (as the test shows) - But maybe there's something different about how the member access flows through when the class is in a different file
Let me create a minimal test case to understand what's happening.
- Local
Assistant
Let me create the package.json and main.ts for the test fixture, then run the analysis to see if it correctly identifies the used members.
Assistant
Now let me write a quick test script to analyze the new fixture and see if the issue reproduces:
Assistant
Let me add a test to the existing integration tests to check if the issue reproduces:
Assistant
Let me add a test directly to the integration test file and run it to see what happens:
Assistant
The existing test works with
const counter = new Counter()whereCounteris imported from./utils. The template uses{counter.bump()}and{counter.value}.Let me think about what could be different in the hister case. The issue says
resultState.pin(...)is used butResultState.pinis reported as unused.Let me look at this more carefully. In the test:
Counteris imported from./utils- this is intemplate_visible_importsconst counter = new Counter()creates the binding - this populatesbinding_target_nameswithcounter -> Countertemplate_visible_bound_targetsgetscounter -> Counter- Template scanner sees
{counter.bump()}and remaps toCounter.bump Counter.bumpmember access is added- In analyzer,
Counteris inlocal_to_export_keys, sobumpis credited toCounter
This works! So the basic case is fine.
Now, what if the issue is something more subtle? Let me look at the issue description again:
- "Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup"
Wait, what if the issue is about a DIFFERENT pattern where the instance is NOT created with
newin the Svelte file itself, but is an imported instance?Or what if the class is NOT imported but is a local class defined in the Svelte file?
Let me check if there's an issue with the template scanner not correctly extracting member accesses from certain Svelte template patterns.
Actually, let me look at the test more carefully. The test checks:
Counter.bump- method call in{counter.bump()}Counter.value- property access in{counter.value}
Both work. So simple member accesses work.
But what about method calls that are directly bound as handlers? Like
onclick={resultState.pin}(without the arrow function wrapper)?Let me check the template scanner for this case...
Actually, let me think about what "bound instance" might mean in the issue context. The issue mentions "bound instance" which could mean:
- A local variable bound to an instance via
const x = new X() - A store binding like
$store - Something else
Actually, I realize I should look more carefully at the actual hister codebase pattern. The issue mentions
asciimoo/hister. Let me think about what pattern hister might use...In hister (a CLI tool for browsing shell history),
ResultStatemight be a class that manages the state of search results.ResultActionsMenu.sveltemight display a menu with actions like pin, update label, etc.The instance
resultStateis likely created somewhere and passed to the component, or created within the component.But without access to the actual hister code, I can only speculate. Let me focus on what the issue says: "Class methods called only from a Svelte
<template>via a member expression."The key is "member expression" -
resultState.pin(...). This is a member expression where the object is a local instance.Now, the test fixture shows this works:
counter.bump()in template →Counter.bumpis creditedcounter.valuein template →Counter.valueis credited
So what could be different?
Wait, I just realized something. The test is called
svelte_template_event_handlers_mark_class_members_used. Let me check what the Vue equivalent test does...Actually, let me look at the Vue test fixture to see if there's a difference in how Vue and Svelte handle this:
Actually, I already know both work from the tests. Let me look at the code path more carefully.
When
counter.bump()is in the template, the Svelte template scanner parses it. The expressioncounter.bump()contains a CallExpression whose callee is a StaticMemberExpression with objectcounterand propertybump.The
ModuleInfoExtractorvisitor captures this as a member access during the AST walk. Inanalyze_template_snippet_with_bound_targets, the extractor visits the wrapped program and collectsmember_accesses.Let me check if the member accesses from template snippets include the
counter.bumpaccess...Actually, the issue might be in how the template snippet is analyzed. The expression
counter.bump()is wrapped as:void (counter.bump());And then parsed. The
ModuleInfoExtractorvisits this and collects member accesses. Invisit_static_member_expression, it adds{ object: "counter", member: "bump" }tomember_accesses.Then
remap_object_nameis called withcounter:counteris inunresolved_names(because it's not declared in the wrapper)counteris inbound_targets(mapping toCounter)- Returns
Some("Counter")
So the remapped member access is
{ object: "Counter", member: "bump" }.This is added to
template_usage.member_accesses. And then inapply_template_usage, it's merged into theModuleInfo.member_accesses.In the analyzer,
local_to_export_keys.get("Counter")returns the export key forCounter(imported from./utils). Andbumpis credited toCounter.This all works! So why doesn't it work in hister?
Let me think about this differently. Maybe the issue is about the Svelte template scanner NOT collecting the member accesses from certain Svelte syntax patterns.
For example:
{#each items as item}<button onclick={resultState.pin}>Pin</button>{/each}- the member accessresultState.pinis in an attribute value{resultState.pin()}- the member access is in a mustache expression<button on:click={resultState.pin}>Pin</button>- the member access is in a directive attribute
Let me check if all these patterns are handled by the template scanner...
Looking at the template scanner code,
scan_curly_sectionhandles{...}expressions, andparse_tag_attrshandles attribute values. Both should capture member accesses.Hmm, let me look at the issue from a different angle. What if the issue is specific to a certain version of Svelte syntax?
Actually, let me re-read the issue one more time:
Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup.
This clearly says "not member-expression method calls". So the issue is that member-expression method calls are NOT tracked.
But the test shows that
{counter.bump()}IS tracked. So what's different?Oh wait! Let me look at the test more carefully. In the test, the counter is created with
const counter = new Counter(). The template uses{counter.bump()}.But what if
counter.bump()is inside a NESTED expression? Like:{items.map(item => resultState.pin(item))}Or what about:
{resultState.pin && resultState.pin()}Actually, these should all be captured by the template scanner because they're all inside
{...}expressions.Let me look at the Vue test to see if there's a specific pattern that's tested for Vue but not for Svelte...
Actually, I think I need to look at the issue from the code perspective. The issue says "Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup."
Wait, I think I finally understand! The issue says "member-expression method calls" specifically. This might be about the case where the method is accessed as a member expression WITHOUT being called.
For example:
<button onclick={resultState.pin}>Pin</button>vs.
<button onclick={() => resultState.pin()}>Pin</button>In the first case,
resultState.pinis a member expression (accessing the method as a value). In the second case,resultState.pin()is a call expression (calling the method).Both should be tracked because the member access
resultState.pinis present in both.But wait, looking at the template scanner code, both cases should produce the same member access
{ object: "resultState", member: "pin" }because theStaticMemberExpressionis present in both cases.OK I'm going to try a different approach. Let me add a test case to the existing test file and run it to see if I can reproduce the issue.
Actually, let me look at the actual code path more carefully. I want to understand exactly what happens when
{counter.bump()}is in a Svelte template.Actually, you know what, I think I should just look at the code and trace through to find the issue. Let me look at the
analyze_template_snippet_with_bound_targetsfunction and see how member accesses are collected.The key insight might be in how
remap_object_nameis applied. Let me look at the code again:TemplateUsage { used_bindings, member_accesses: dedup_member_accesses( extractor .member_accesses .into_iter() .filter_map(|access| { remap_object_name( &access.object, &unresolved_targets, bound_targets, allow_dollar_prefixed_refs, ) .map(|object| MemberAccess { object, member: access.member, }) }) .collect(), ), ... }So for each member access,
remap_object_nameis called. If it returnsSome, the access is kept with the remapped object name. If it returnsNone, the access is FILTERED OUT!So if
remap_object_namereturnsNonefor some reason, the member access is lost.When does
remap_object_namereturnNone?fn remap_object_name( name: &str, unresolved_names: &FxHashSet<String>, bound_targets: &FxHashMap<String, String>, allow_dollar_prefixed_refs: bool, ) -> Option<String> { if unresolved_names.contains(name) { if let Some(target) = bound_targets.get(name) { return Some(target.clone()); } return Some(name.to_string()); } if allow_dollar_prefixed_refs && let Some(stripped) = name.strip_prefix('$') && unresolved_names.contains(stripped) { if let Some(target) = bound_targets.get(stripped) { return Some(target.clone()); } return Some(stripped.to_string()); } None }So
remap_object_namereturnsNoneonly if:nameis NOT inunresolved_namesAND- (
namedoesn't start with$OR the stripped name is NOT inunresolved_names)
unresolved_namesis populated fromunresolved_targets, which is populated from unresolved references that are inimported_bindingsorbound_targets.So if
counteris inbound_targets, it's also inunresolved_targets(and thusunresolved_names). Andremap_object_name("counter", ...)would returnSome("Counter").But what if
counteris NOT inimported_bindingsand NOT inbound_targets? Then it wouldn't be inunresolved_targets, andremap_object_namewould returnNone!Wait, but
counterIS inbound_targets(because it's created withconst counter = new Counter()).Unless...
counteris NOT inbound_targetsbecause of some issue with howbinding_target_namesis populated.Let me check: in
merge_script_into_module,template_visible_bound_targetsis populated fromextractor.binding_target_names(). But doesbinding_target_namesget populated correctly?In
visit_variable_declaration:if let Expression::NewExpression(new_expr) = init && let Expression::Identifier(callee) = &new_expr.callee && let BindingPattern::BindingIdentifier(id) = &declarator.id && !super::helpers::is_builtin_constructor(callee.name.as_str()) { self.binding_target_names .insert(id.name.to_string(), callee.name.to_string()); }This checks that:
- The initializer is a
NewExpression - The callee is an
Identifier(not a member expression likeFoo.Bar) - The binding is a
BindingIdentifier(not a destructuring pattern) - The callee is not a builtin constructor
For
const counter = new Counter(), all conditions are met. Sobinding_target_namesshould havecounter -> Counter.So for the test fixture,
counter -> Counteris inbinding_target_names, which is added totemplate_visible_bound_targets, which is passed to the template scanner, which uses it to remapcounter.bumptoCounter.bump.This works!
So for hister, if
resultState = new ResultState()is in the Svelte script, the same logic should apply. UnlessresultStateis created differently.Hmm, let me think about what else could cause the issue...
Actually, wait! I just realized something. In the Svelte test fixture, the template expression is
{counter.bump()}inside a button's text content. But what if the issue is with expressions in ATTRIBUTE values?For example:
<button onclick={() => counter.bump()}>Pin</button>This uses
{() => counter.bump()}in the attribute value. The scanner should still capturecounter.bumpbecause the arrow function contains the call expression.But what about:
<button onclick={resultState.pin}>Pin</button>This uses
{resultState.pin}without calling it. The scanner should captureresultState.pinas a member access.Both patterns should work because the template scanner extracts expressions from curly sections and attribute values.
Let me actually look at the code that handles attribute values...
Looking at
parse_tag_attrs, it extracts attribute values and processes expressions within them. Thescan_curly_sectionfunction handles{...}expressions.Wait, but
{resultState.pin}in an attribute value - is that handled? Let me check...Actually, looking at the template scanner code, attribute values are handled in
parse_tag_attrs(fromshared.rs). And curly expressions within attribute values are handled separately.Let me look at
apply_markup_tagin svelte.rs to see how attributes are processed:fn apply_markup_tag( tag: SharedTemplateTag, ... ) {Let me find this function...
Actually, I think the issue might be simpler than I thought. Let me re-read the issue one more time:
Class methods called only from a Svelte
<template>via a member expression (for exampleresultState.pin(...)in markup) are reported asunused-class-member."called only from a Svelte template" - this means the methods are ONLY called from the template, not from the script. So if the method is called both from the script and the template, it would be fine.
"Fallow tracks template-visible identifiers but not member-expression method calls on a bound instance inside Svelte markup" - this means the identifier (
resultState) is tracked (so it's not reported as unused), but the method call (resultState.pin()) on the bound instance is NOT tracked.This is exactly the scenario where:
resultStateis intemplate_visible_imports(as an import binding) ortemplate_visible_bound_targets(as a local binding)resultState.pin()is in the template- The template scanner captures
resultStateas used (removing it fromunused_import_bindings) - But the member access
resultState.pinis NOT properly resolved toResultState.pin
If
resultStateis inbound_targets, thenresultState.pinshould be remapped toResultState.pin. If it's NOT inbound_targets, thenresultState.pinstays as-is.Wait, but there's another case! What if
resultStateis inimported_bindingsbut NOT inbound_targets? Then:resultStateis inimported_bindings, so it's added toused_bindingsresultStateis also inunresolved_targetsremap_object_name("resultState", unresolved_targets, bound_targets, ...)is calledresultStateis inunresolved_names(because it's inunresolved_targets)bound_targets.get("resultState")returnsNone- Returns
Some("resultState".to_string())
So the member access becomes
{ object: "resultState", member: "pin" }. The object is still the import binding name, not the class name.Then in the analyzer:
local_to_export_keys.get("resultState")returns the export key for the importedresultStatepinis credited toresultState's export key
But
resultStateis an instance export (from the instance.ts pattern), not a class! Sopinwould be credited to the instance, not the class.But wait,
propagate_accesses_through_instance_exportsshould fix this. Unless... the instance export doesn't have theINSTANCE_EXPORT_SENTINELentry.OK I think I need to actually test this. Let me create a test case where
resultStateis imported from another file and used in the Svelte template.Actually wait, the issue says "bound instance" which suggests a LOCAL binding, not an imported one. So
resultStateshould be created locally in the Svelte script.Hmm, let me think about this differently. What if the issue is about a different code path?
Let me look at the
analyze_template_snippet_with_bound_targetsfunction again. The key part is:if unresolved_targets.is_empty() { return TemplateUsage::default(); }If
unresolved_targetsis empty, the function returns early without processing member accesses. But this shouldn't happen ifcounteris inbound_targetsand the template usescounter.bump().Actually wait, let me trace through more carefully:
counteris inbound_targets- The template snippet
counter.bump()is parsed counteris unresolved (not declared in the wrapper)counteris checked againstimported_bindings- NOT foundcounteris checked againstbound_targets- FOUND! Added tounresolved_targetsunresolved_targetsis NOT empty- Member accesses are processed
counter.bumphascounterinunresolved_names, remapped toCounter{ object: "Counter", member: "bump" }is inmember_accesses
This works!
Now, what if
counteris ALSO inimported_bindings? That would be the case ifCounteris imported and used to create the instance. Let me check...In the test fixture:
import { Counter } from './utils'; const counter = new Counter();Counter(uppercase) is imported, notcounter(lowercase). Socounteris NOT inimported_bindings.What if in hister, the pattern is:
<script> import { ResultState, resultState } from './store'; </script> {resultState.pin()}In this case,
resultStateis imported, not created locally. SoresultStateis inimported_bindingsbut NOT inbound_targets.When processing
resultState.pin():resultStateis inimported_bindingsresultStateis added toused_bindingsandunresolved_targetsremap_object_name("resultState", unresolved_targets, bound_targets, ...)is calledresultStateis inunresolved_namesbound_targets.get("resultState")returnsNone(because it's an import, not a local binding)- Returns
Some("resultState".to_string()) { object: "resultState", member: "pin" }is inmember_accesses
In the analyzer:
local_to_export_keys.get("resultState")returns the export key for the importedresultStatefrom./storepinis credited to that export key
But
./store#resultStateis an instance export, not a class. Sopinis NOT credited toResultState.However,
propagate_accesses_through_instance_exportsshould fix this IF the./storefile has theINSTANCE_EXPORT_SENTINELentry forresultState.Let me check if this propagation actually works...
Actually, I think I should just test this scenario. Let me create a test case where an imported instance is used in a Svelte template.
Let me think about this more carefully. In the current test:
Counteris a class inutils.tsApp.svelteimportsCounterand createscounter = new Counter()counter.bump()in template → remapped toCounter.bump→Counteris inlocal_to_export_keys→bumpcredited toCounter
In the failing scenario (hister):
ResultStateis a classResultActionsMenu.sveltehas some pattern whereresultStateis usedresultState.pin()in template → NOT remapped →resultStateis used but not the class
The key difference might be:
resultStateis NOT created withnew ResultState()in the Svelte file- Or
resultStateis created withnew ResultState()but the remapping fails for some reason
Let me focus on case 1 first. If
resultStateis imported from another file, the fix would need to:- Know that the imported
resultStateis an instance ofResultState - Remap
resultState.pintoResultState.pin
This could be done by checking the
INSTANCE_EXPORT_SENTINELinformation during template scanning. But that requires access to the resolved import information.Actually wait, there's another approach. Instead of remapping during template scanning, we could propagate the accesses after analysis. The
propagate_accesses_through_instance_exportsfunction should handle this.Let me verify: if
resultStateis imported from./store, and./storeexportsresultState(created withnew ResultState()), then:./storehasINSTANCE_EXPORT_SENTINEL:resultStatewith memberResultStatebuild_instance_export_targetscreates mapping:./store#resultState→./ResultState#ResultState(or whereverResultStateis defined)- In the Svelte file,
resultState.pincreates member access with objectresultState local_to_export_keys.get("resultState")returns./store#resultStatepinis credited to./store#resultStatepropagate_accesses_through_instance_exportspropagatespinfrom./store#resultStateto./ResultState#ResultState
This should work! So why doesn't it?
Unless...
ResultStateis imported into./storeas well, andlocal_to_export_keys.get("ResultState")in./storeresolves to the correct export key.Actually, let me trace through more carefully:
In
./store.ts:import { ResultState } from './ResultState'; const resultState = new ResultState(); export { resultState };record_exported_instance_bindingscreates:MemberAccess { object: "INSTANCE_EXPORT_SENTINEL:resultState", member: "ResultState" }
build_instance_export_targets:- Processes
./storemodule - Finds sentinel
INSTANCE_EXPORT_SENTINEL:resultState local_to_export_keys.get("ResultState")returns... what?
ResultStateis imported from./ResultState. Inlocal_to_export_keysfor./store,ResultStatewould map to the export key ofResultStatein./ResultState.ts.So
instance_targetswould have:./store#resultState→[./ResultState#ResultState]
And in the Svelte file:
resultStateis imported from./storelocal_to_export_keys.get("resultState")returns./store#resultStatepinis added toaccessed_members[./store#resultState]propagate_accesses_through_instance_exportspropagates to./ResultState#ResultState
This SHOULD work!
Unless there's a bug in the propagation logic or the key matching. Let me look at the key construction more carefully...
In
build_instance_export_targets:let instance_key = ExportKey::new(resolved.file_id, instance_export_name);And in the propagation:
let accessed_snapshot: Vec<(ExportKey, Vec<String>)> = accessed_members .iter() .map(|(key, members)| (key.clone(), members.iter().cloned().collect())) .collect(); for (instance_key, members) in accessed_snapshot { let Some(target_keys) = instance_targets.get(&instance_key) else { continue; };So
instance_keyis built fromresolved.file_id(the file that has the sentinel) andinstance_export_name(the export name).And in the Svelte file, when
resultStateis resolved,local_to_export_keys.get("resultState")returns the export key forresultStatein./store.But wait,
ExportKeyis(file_id, export_name). Thefile_idis the file where the export is DEFINED, not the file that imports it.So for
import { resultState } from './store':- The resolved import target is the
resultStateexport in./store - The
ExportKeyis(.store_file_id, "resultState")
And for the sentinel:
- The sentinel is in
./store'smember_accesses resolved.file_idis./store's file_idinstance_export_nameis"resultState"instance_keyis(.store_file_id, "resultState")
These should match! So the propagation should work.
Unless there's a bug somewhere... Let me actually run a test to verify.
Actually, let me focus on reproducing the issue first. Let me create a test case where an imported instance is used in a Svelte template and see if the methods are credited correctly.
Hmm, actually, let me re-read the issue once more. The issue says:
Class methods called only from a Svelte
<template>via a member expression (for exampleresultState.pin(...)in markup) are reported asunused-class-member.This could mean:
- The class
ResultStatehas methodspin, etc. - These methods are called in a Svelte template via
resultState.pin(...) - These methods are reported as unused
The question is: is
resultStatea localnew ResultState()or an imported instance?If it's a local
new ResultState(), the test fixture already shows this works. So the issue must be about imported instances or some other pattern.Actually, you know what, let me just look at what the actual hister code might look like. The issue mentions "asciimoo/hister" which is a Svelte-based CLI tool. The
ResultActionsMenu.sveltecomponent probably receivesresultStateas a prop or creates it locally.Actually, thinking about it more, the issue might be about a specific edge case in Svelte template parsing. Let me look at the Svelte template scanner code to see if there's a pattern that's not handled.
Actually, wait. I just realized something. Let me re-read the test:
#[test] fn svelte_template_event_handlers_mark_class_members_used() { ... assert!( !unused_members.contains(&"Counter.bump".to_string()), "Counter.bump should be used from a Vue @click handler, found: {unused_members:?}" );The assertion message says "Vue @click handler" but it's testing Svelte! This is just a copy-paste error in the message.
Now, the template uses:
<button onclick={() => counter.bump()}>{counter.value}</button>So
counter.bump()is inside an arrow function, andcounter.valueis in a mustache expression. Both should be captured by the template scanner.Let me check: does the template scanner capture member accesses from inside arrow functions?
The template scanner parses the expression
{() => counter.bump()}. The arrow function bodycounter.bump()contains aStaticMemberExpressionthat is the callee of aCallExpression. TheModuleInfoExtractorvisitor should walk into the arrow function and capture the member access.Let me verify this by looking at
visit_static_member_expression:fn visit_static_member_expression(&mut self, expr: &StaticMemberExpression<'a>) { if let Some(object_name) = static_member_object_name(&expr.object) { self.member_accesses.push(MemberAccess { object: object_name, member: expr.property.name.to_string(), }); } ... walk::walk_static_member_expression(self, expr); }This captures ALL
StaticMemberExpressionnodes, regardless of their context. Socounter.bump()inside an arrow function would be captured.OK so the template scanner does capture member accesses from inside arrow functions.
Let me think about what else could be different...
Actually, I wonder if the issue is about how the template scanner handles expressions in certain Svelte-specific syntax like
{@const},{#if}, or directive attributes.Let me look at the Svelte template scanner to see if there's a case that's not handled...
Actually, I just had another thought. What if the issue is that the Svelte template uses a STORE binding like
$resultStateinstead ofresultState?<script> import { resultState } from './store'; </script> {$resultState.pin()}In this case,
$resultStateis a Svelte store auto-subscription syntax. The template scanner needs to handle$prefixed identifiers.Looking at
merge_expression_usage_allow_dollar_refs_with_bound_targets, it callsmerge_snippet_usage_with_bound_targetswithallow_dollar_prefixed_refs = true. And inanalyze_template_snippet_with_bound_targets:if allow_dollar_prefixed_refs && let Some(stripped) = name.strip_prefix('$') { if imported_bindings.contains(stripped) { used_bindings.insert(stripped.to_string()); unresolved_targets.insert(stripped.to_string()); } else if bound_targets.contains_key(stripped) { unresolved_targets.insert(stripped.to_string()); } }So
$resultStatewould be handled ifresultStateis inimported_bindingsorbound_targets.But wait,
$resultStateis a Svelte store syntax, andresultStateneeds to be a Svelte store for$resultStateto work. IfresultStateis a plain instance (not a store),$resultStatewouldn't work.Hmm, but maybe the hister repo uses stores? Let me not assume too much and focus on what the issue actually says.
The issue says
resultState.pin(...), not$resultState.pin(...). So it's NOT a store binding.OK let me take yet another approach. Let me look at the Svelte template scanner code to see if there's a case where member accesses are NOT captured.
Looking at the scanner, it processes curly sections (
{...}) and HTML tags. Curly sections are parsed usingscan_curly_section, and the content is passed toapply_tag.In
apply_tag, different Svelte block types are handled:#if,#each,#await,#key,#snippet- Closing tags like
/if,/each, etc. {@const}{@render}{@attach}- Plain expressions
For plain expressions, the code falls through to the end of the function. Let me check...
Looking at
apply_tag:fn apply_tag( tag: &str, ... ) { if tag.is_empty() { return; } if let Some(rest) = tag.strip_prefix('/') { pop_scope(scopes, rest.trim()); return; } if let Some(expr) = tag.strip_prefix("#if") { ... } ... (other block types) // Plain expression merge_expression_usage_allow_dollar_refs_with_bound_targets( usage, tag, imported_bindings, bound_targets, ¤t_locals(scopes), ); }Wait, let me check if there's a fallthrough at the end of
apply_tag...Actually, looking at the code more carefully, after all the block-specific handling, there should be a catch-all for plain expressions. Let me check if it exists...
I need to see the full
apply_tagfunction. Let me search for where plain expressions are handled:Actually, I see it now. Looking at the code:
if let Some(expr) = tag.strip_prefix("#if") { ... return; } if let Some(captures) = SVELTE_EACH_RE.captures(tag) { ... return; } ... (other patterns with return) // After all patterns, plain expression: merge_expression_usage_allow_dollar_refs_with_bound_targets( usage, tag, imported_bindings, bound_targets, ¤t_locals(scopes), );Wait, but does the code have a catch-all for expressions that don't match any pattern? Let me check...
Actually, looking at the code, each special pattern has a
returnstatement. So if the tag doesn't match any pattern, it would fall through to the plain expression handling at the end. Let me verify this.Actually, I think I see a potential issue! Let me check the code more carefully:
After
SVELTE_CATCH_RE,SVELTE_SNIPPET_RE, and other patterns, there might be code that handles@const,@render, etc. And then there's a fallthrough for plain expressions.But what if a certain pattern is not handled and falls through incorrectly?
Actually, let me look at the actual code. Let me find where the plain expression handling is:
I'll continue by looking at the `apply_tag` function to find where plain expressions are handled and identify any gaps in coverage.Let me look at the
apply_tagfunction more carefully to see how expressions are handled:<tool_call> <function=bash_terminal> <parameter=command> sed -n '180,300p' /fallow/crates/extract/src/sfc_template/svelte.rs </tool_call>
Assistant
The previous command failed. Let me try again with the proper tool call format.
Assistant
Let me continue looking at the
apply_tagfunction to see how plain expressions are handled and if there's a gap in coverage.Assistant
I've found the issue! For SFC (Single File Component) scripts like
.sveltefiles, the code callsextractor.visit_program()followed byextractor.merge_into(combined), but it does NOT call the resolve functions thatinto_module_info()would call for regular files. These resolve functions includeresolve_object_binding_candidates()andresolve_factory_call_candidates(), which populatebinding_target_namesfor additional patterns like type annotations and factory calls.Let me verify this and implement the fix:
Assistant
Now I understand the issue. The problem is that for SFC (Svelte/Vue) script blocks, the code only calls
extractor.visit_program()and thenextractor.merge_into(combined), but it does NOT call the resolve functions thatinto_module_info()calls for regular files. These resolve functions include:enrich_local_class_exports()- needed byresolve_factory_call_candidates()resolve_object_binding_candidates()- handles namespace destructuring patternsresolve_factory_call_candidates()- handlesconst x = SomeClass.staticFactory()patterns
Without these,
binding_target_namesis incomplete for SFC scripts, so template member expressions likeresultState.pin(...)are not properly remapped toResultState.pin.Let me implement the fix by adding a method that calls these resolve functions:
Assistant
Now I understand the issue. The
merge_script_into_modulefunction doesn't call the resolve functions (enrich_local_class_exports,resolve_factory_call_candidates,resolve_object_binding_candidates) thatinto_module_info()calls. These functions are needed to properly populatebinding_target_namesfor patterns like factory calls.Let me implement the fix by adding the resolve calls in
merge_script_into_module:Assistant
Now I see the issue! In
merge_script_into_module,binding_target_names()is called BEFOREmerge_into(), butmerge_into()is the one that calls the resolve functions (resolve_factory_call_candidates(),resolve_object_binding_candidates(), etc.) that populate additional entries inbinding_target_names.So the
binding_target_namesread fortemplate_visible_bound_targetsdoesn't include the resolved entries!The fix is to call the resolve functions before reading
binding_target_names(). Let me implement this:Assistant
Let me implement the fix properly. First, I'll add the resolve method to the visitor module:
Assistant
The user is pointing out that my previous command was rejected because it wasn't a valid tool call. I need to use the bash_terminal tool properly. Let me continue investigating the issue.
I now understand the problem:
- In
merge_script_into_module,binding_target_names()is called BEFOREmerge_into() merge_into()calls the resolve functions that populate additional entries inbinding_target_names- So the
binding_target_namesread fortemplate_visible_bound_targetsdoesn't include factory call candidates
I need to:
- Add a method to call the resolve functions before reading
binding_target_names() - Or modify
merge_into()to not duplicate the resolve calls
Let me implement the fix properly.
- In
Assistant
You're right, I need to properly use the tool calls. Let me continue implementing the fix. The issue is clear:
binding_target_names()is read before the resolve functions are called, so factory call candidates and object binding candidates aren't resolved.Let me add a method to the
ModuleInfoExtractorto resolve the template bound targets:Assistant
I need to add a method to resolve the template bound targets before they are read. Let me add this method to the visitor module:
Assistant
Let me open the file first and then apply the edit:
Assistant
Let me open the file first and then make the edit:
Assistant
Let me open the file first and then apply the edit:
Assistant
Let me open the file first and then edit it:
Assistant
The user is pointing out that I need to use the proper tool call format. Let me now add the new method
resolve_template_bound_targetsto theModuleInfoExtractorstruct. I need to add it after line 279 (afterbinding_target_names).The key insight is that in
merge_script_into_module(in sfc.rs), the code readsbinding_target_names()BEFORE callingmerge_into(), butmerge_into()is the one that calls the resolve functions. So the fix is to either:- Call the resolve functions before reading
binding_target_names()in sfc.rs - Or add a method that calls the resolve functions and call it from sfc.rs
Option 2 is cleaner. Let me add a method to the extractor.
- Call the resolve functions before reading
Assistant
Let me verify the change was applied correctly:
Assistant
Good, the method was added successfully. Now I need to call this method in
sfc.rsbefore readingbinding_target_names()inmerge_script_into_module. Let me look at the sfc.rs file to find the exact location:Assistant
I need to call
resolve_template_bound_targets()before readingbinding_target_names()insfc.rs. Let me find the exact location and add the call:Assistant
I need to add a call to
resolve_template_bound_targets()before readingbinding_target_names(). The call should be inserted right before theif is_template_visible_script(kind, script)block. Let me do that:Assistant
The user is pointing out that I made an error with my sed command. I need to fix the sfc.rs file to add the call to
resolve_template_bound_targets()before readingbinding_target_names(). Let me check the current state of the file and fix it properly.Assistant
The sed command worked correctly! The call to
resolve_template_bound_targets()is now in place. Let me verify the complete changes and then compile to make sure everything works.Assistant
The compilation succeeded. Now let me run the existing Svelte tests to verify everything works:
Assistant
The Svelte tests pass. Now let me also run the Vue tests to make sure I didn't break anything:
Assistant
All Vue and Svelte tests pass. Now let me run the extract package tests to make sure the new method works correctly:
Assistant
The tests pass. Now let me run a broader test to make sure I haven't broken anything else in the core package.
Assistant
All 523 tests pass. Now let me clean up the test fixture I created earlier and verify the changes are correct:
Assistant
Let me review the changes I've made to verify they are correct and complete:
Assistant
I notice there's a missing newline in the visitor module. Let me fix the formatting:
Assistant
I need to add a newline after the closing brace of
resolve_template_bound_targets:Assistant
The user is asking me to continue. I had added a newline but let me check if it was applied correctly and then run the tests again to make sure everything still works.
Assistant
Let me fix the formatting properly by adding a newline:
Assistant
The user seems to be waiting for me to continue. Let me check the current state of the file and verify the formatting is correct.
Assistant
The formatting looks good now. Let me run the tests one final time to confirm everything still works:
Assistant
Let me verify all the core tests pass as well.
Assistant
Let me verify the final diff looks correct:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →