Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(salesforce): link Visualforce pages and components to their Apex controllers, bound members and pages (#4415)
Raghav Chamadiya2c171cfe4f0d
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex debab26ec..32de4ccef 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -980,6 +980,16 @@ Salesforce CLI coverage names a class or trigger, never a file, so it maps tothe one `.cls` or `.trigger` file of that name, ignoring case. A name two filesshare, or no file has, stays unmapped.+### Salesforce Visualforce++Pages and components link the Apex classes their `controller=` and+`extensions=` name, and each `{!expr}` binds the identifier before its first `.`+to a public member (property, `getX`, or `setX` for inputs) of the controller,+then each extension, up the `extends` chain. Custom component tags, included+pages and Apex `Page.X` references link pages and components; a+`PageReference('/apex/X')` literal is a `dynamic_uses` edge. Names fold case,+and a name two equally near files declare binds nothing.+### QMLModule specs resolve against an index built from the `qmldir` manifests in thediff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 39e2d5652..b2bd76030 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -215,6 +215,8 @@ invoked by name.- Salesforce Aura markup (`.cmp`, `.app`, `.evt`, `.intf`, `.design`, `.tokens` inan `aura/<bundle>/` folder) carries no symbols but is read for the Apexcontroller, controller functions, child components and events it names.+- Salesforce Visualforce pages and components (`.page`, `.component`) carry no+ symbols but link their Apex controllers and the members their expressions bind.## Code-health coveragediff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.pyindex b16ff3ca3..5f1adc98f 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py@@ -53,6 +53,7 @@ from . import (test_runner_setup,trpc,typo3,+ visualforce,vscode_extension,)from .base import DetectionContext, FrameworkHandler, _add_edge_if_new, read_text@@ -105,6 +106,8 @@ _HANDLERS: list[FrameworkHandler] = [# Salesforce Aura bundles: markup names its Apex controller, controller# functions and child components; nothing is an import.*aura.HANDLERS,+ # Salesforce Visualforce: markup names its Apex controller and bound members.+ *visualforce.HANDLERS,]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/visualforce.py b/packages/core/src/repowise/core/ingestion/framework_edges/visualforce.pynew file mode 100644index 000000000..acc60da67--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/visualforce.py@@ -0,0 +1,385 @@+"""Salesforce Visualforce edges: pages and components to their Apex and to each other.++* ``controller=`` / ``extensions=`` on the root tag -> the Apex classes and the+ constructor the platform calls.+* ``{!expr}`` -> the controller member its first identifier names (property,+ ``getX``, or ``setX`` for an input or ``assignTo``), looked up through the+ controller, then each extension, each up its ``extends`` chain.+* ``<c:X>``, ``pageName=``, ``template=`` and ``$Page.X`` -> components and pages;+ Apex ``Page.X`` -> the page, a ``PageReference('/apex/X')`` literal as+ ``dynamic_uses``.++Names fold case; two equally near candidates bind neither. Pages are entry points.+"""++from __future__ import annotations++import re+from pathlib import PurePosixPath+from typing import TYPE_CHECKING, Any++from ...analysis.security_scan import mask_comments_and_strings+from ..return_types import signature_parameter_count+from ..type_names import bare_type_name, type_qualifier+from .aura import _file_edge, _mask_xml, _nearest, _own_namespaces+from .base import DetectionContext, FrameworkHandler, add_symbol_edge, source_text++if TYPE_CHECKING:+ import networkx as nx++ from ..resolvers import ResolverContext++_TAG_RE = re.compile(r"""<([A-Za-z]\w*):([A-Za-z_]\w*)((?:[^>"']|"[^"]*"|'[^']*')*)>""")+_ATTR_RE = re.compile(r"""([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')""")+_EXPR_RE = re.compile(r"\{!(.*?)\}", re.DOTALL)+_EXPR_STRING_RE = re.compile(r"""'(?:\\.|[^'\\])*'|"[^"]*\"""")+# An identifier not reached through `.`, `$` or `:`; the caller drops calls.+_EXPR_IDENT_RE = re.compile(r"(?<![\w$.:])([A-Za-z_]\w*)(?!\w)")+_BARE_EXPR_RE = re.compile(r"^\s*([A-Za-z_]\w*)\s*$")+_PAGE_GLOBAL_RE = re.compile(r"(?<![\w.])\$Page\s*\.\s*([A-Za-z_]\w*)", re.IGNORECASE)+# Loop and apex:variable locals, read file-wide (this only drops bindings).+_VAR_ATTR_RE = re.compile(r"""\bvar\s*=\s*["']\s*(\w+)\s*["']""", re.IGNORECASE)+# Not followed by `(`: `page.getParameters()` on a local named `page` is a call.+_APEX_PAGE_RE = re.compile(r"(?<![\w.$])Page\s*\.\s*([A-Za-z_]\w*)\b(?!\s*\()", re.IGNORECASE)+# The name must end the path or the literal: `'/apex/Report_' + kind` is a prefix.+_PAGE_REFERENCE_RE = re.compile(+ r"\bnew\s+(?:System\s*\.\s*)?PageReference\s*\(\s*'/apex/([A-Za-z_]\w*)(?:[?#/]|'\s*\))",+ re.IGNORECASE,+)+# Tags whose `value` the platform writes back on submit, through a setter.+_SELECT_INPUT_TAGS = frozenset({"selectlist", "selectradio", "selectcheckboxes"})+_ROOT_TAGS = ("page", "component")+_EXTENDS_DEPTH = 6+++def _attrs(blob: str) -> dict[str, str]:+ """Attribute name (lowercased: Visualforce ignores its case) -> value."""+ return {+ m.group(1).lower(): m.group(2) if m.group(2) is not None else m.group(3)+ for m in _ATTR_RE.finditer(blob)+ }+++def _apex_class_files(parsed_files: dict[str, Any]) -> dict[str, list[str]]:+ """Lowercased Apex class name -> its ``.cls`` files.++ Ceiling: local index; replace with the Apex resolution pass's class index when it lands.+ """+ out: dict[str, list[str]] = {}+ for path in sorted(parsed_files):+ if parsed_files[path].file_info.language == "apex" and path.lower().endswith(".cls"):+ out.setdefault(PurePosixPath(path).stem.lower(), []).append(path)+ return out+++class _VfIndex:+ def __init__(+ self, graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext+ ) -> None:+ self.graph = graph+ self.parsed_files = parsed_files+ self.source_map: dict[str, bytes] = getattr(ctx, "source_map", None) or {}+ self.own_ns = _own_namespaces(parsed_files, self.source_map)+ self.apex = _apex_class_files(parsed_files)+ self.pages: dict[str, list[str]] = {}+ self.components: dict[str, list[str]] = {}+ for path in sorted(parsed_files):+ if parsed_files[path].file_info.language != "visualforce":+ continue+ p = PurePosixPath(path)+ index = self.pages if p.suffix.lower() == ".page" else self.components+ index.setdefault(p.stem.lower(), []).append(path)+ self._members: dict[tuple[str, str], dict[str, list[Any]]] = {}++ def text(self, path: str) -> str:+ return source_text(path, self.parsed_files[path], self.source_map, "utf-8-sig")++ def _own_name(self, written: str) -> str | None:+ """*written* without an own ``ns__`` prefix (names never hold ``__``), else None."""+ head, sep, tail = written.strip().partition("__")+ if sep:+ return tail if tail and head.lower() in self.own_ns else None+ return head++ def page(self, written: str, src: str) -> str | None:+ name = self._own_name(written)+ return _nearest(src, self.pages.get(name.lower(), [])) if name else None++ def component(self, name: str, src: str) -> str | None:+ return _nearest(src, self.components.get(name.lower(), []))++ def apex_class(self, written: str, src: str) -> tuple[str, str] | None:+ """``(class file, class name)`` for ``[ns.]Cls`` written in *src*, own namespace only."""+ written = written.strip()+ head, tail = type_qualifier(written), bare_type_name(written)+ if not tail or (head and head.lower() not in self.own_ns):+ return None+ path = _nearest(src, self.apex.get(tail.lower(), []))+ return (path, tail) if path else None++ def chain(self, cls_file: str, cls: str) -> list[tuple[str, str]]:+ """The class and its ``extends`` ancestors the repository declares, nearest first."""+ out = [(cls_file, cls)]+ while len(out) < _EXTENDS_DEPTH:+ path, name = out[-1]+ parent = next(+ (+ h.parent_name+ for h in self.parsed_files[path].heritage+ if h.kind == "extends" and h.child_name.lower() == name.lower()+ ),+ None,+ )+ hit = self.apex_class(parent, path) if parent else None+ if hit is None or hit in out:+ break+ out.append(hit)+ return out++ def members(self, cls_file: str, cls: str) -> dict[str, list[Any]]:+ """Lowercased name -> the public member symbols *cls* declares itself."""+ key = (cls_file, cls.lower())+ if key not in self._members:+ found: dict[str, list[Any]] = {}+ for s in self.parsed_files[cls_file].symbols:+ if (s.parent_name or "").lower() == key[1] and s.visibility == "public":+ found.setdefault(s.name.lower(), []).append(s)+ self._members[key] = found+ return self._members[key]++ def constructors(self, cls_file: str, cls: str, arity: int) -> list[Any]:+ """Public constructors of *cls* taking *arity* parameters."""+ ctors = self.members(cls_file, cls).get(cls.lower(), [])+ return [s for s in ctors if signature_parameter_count(s.signature or "") == arity]+++class _Edges:+ """File edges gathered per (source, target) so each carries every name it vouches for."""++ def __init__(self, graph: nx.DiGraph) -> None:+ self.graph = graph+ self.names: dict[tuple[str, str], set[str]] = {}+ self.dynamic: set[tuple[str, str]] = set()+ self.count = 0++ def file(self, src: str, dst: str | None, names: set[str] | None = None) -> None:+ if dst is not None:+ self.names.setdefault((src, dst), set()).update(names or ())++ def bind(self, src_file: str, dst_file: str, symbols: list[Any], name: str) -> None:+ for sym_id in dict.fromkeys(s.id for s in symbols):+ self.count += add_symbol_edge(self.graph, f"{src_file}::__module__", sym_id)+ self.file(src_file, dst_file, {name})++ def flush(self) -> int:+ for (src, dst), names in sorted(self.names.items()):+ self.count += _file_edge(self.graph, src, dst, names)+ # A `Page.X` framework edge to the same page is the stronger evidence and stays.+ for src, dst in sorted(self.dynamic):+ if (+ src != dst+ and src in self.graph+ and dst in self.graph+ and not self.graph.has_edge(src, dst)+ ):+ self.graph.add_edge(+ src,+ dst,+ edge_type="dynamic_uses",+ hint_source="vf_page_reference",+ weight=1.0,+ imported_names=[],+ )+ self.count += 1+ return self.count+++def _expressions(text: str) -> list[str]:+ """The body of every ``{!...}`` with its string literals blanked."""+ return [+ _EXPR_STRING_RE.sub(lambda s: " " * len(s.group(0)), m.group(1))+ for m in _EXPR_RE.finditer(text)+ ]+++def _member_names(expr: str) -> list[str]:+ """Identifiers of *expr* that can name a controller member, in order."""+ return [+ m.group(1)+ for m in _EXPR_IDENT_RE.finditer(expr)+ if not expr[m.end() :].lstrip().startswith("(")+ ]+++def _controllers(idx: _VfIndex, path: str, root_attrs: dict[str, str]) -> list[tuple[str, str]]:+ """``(class file, class name)`` of the controller, then each extension in order."""+ out: list[tuple[str, str]] = []+ written = [root_attrs.get("controller", ""), *root_attrs.get("extensions", "").split(",")]+ for w in written:+ hit = idx.apex_class(w, path) if w.strip() and "{" not in w else None+ if hit is not None and hit not in out:+ out.append(hit)+ return out+++def _bare_names(written: str) -> set[str]:+ """Lowercased names of the bare ``{!name}`` expressions in *written*."""+ return {m.group(1).lower() for b in _expressions(written) if (m := _BARE_EXPR_RE.match(b))}+++class _MarkupNames:+ """Names an expression must not bind, and names written back to the controller."""++ def __init__(self, text: str, root_attrs: dict[str, str]) -> None:+ self.local = {m.group(1).lower() for m in _VAR_ATTR_RE.finditer(text)}+ for key in ("standardcontroller", "recordsetvar"):+ if root_attrs.get(key):+ self.local.add(root_attrs[key].strip().lower())+ # An `assignTo` binds even when the attribute shares its name.+ self.setters: set[str] = set()+ self.assigned: set[str] = set()++ def read_apex_tag(self, tag: str, attrs: dict[str, str]) -> None:+ if tag == "attribute" and attrs.get("name"):+ self.local.add(attrs["name"].strip().lower())+ if tag.startswith("input") or tag in _SELECT_INPUT_TAGS:+ self.setters |= _bare_names(attrs.get("value", ""))+ self.assigned |= _bare_names(attrs.get("assignto", ""))++ def skips(self, name: str) -> bool:+ return name in self.local and name not in self.assigned++ def writes(self, name: str) -> bool:+ return name in self.setters or name in self.assigned+++def _tag_edges(+ idx: _VfIndex, path: str, tags: list[re.Match[str]], names: _MarkupNames, edges: _Edges+) -> None:+ """Component tags and included pages; records the names the tags declare or write."""+ for m in tags:+ ns, tag = m.group(1).lower(), m.group(2).lower()+ if ns in idx.own_ns:+ edges.file(path, idx.component(m.group(2), path))+ elif ns == "apex":+ attrs = _attrs(m.group(3))+ names.read_apex_tag(tag, attrs)+ page_attr = {"include": "pagename", "composition": "template"}.get(tag)+ if page_attr and attrs.get(page_attr):+ edges.file(path, idx.page(attrs[page_attr], path))+++def _root_attrs(idx: _VfIndex, path: str, tags: list[re.Match[str]]) -> dict[str, str]:+ """Attributes of the ``<apex:page>`` / ``<apex:component>`` root; marks a page an entry point."""+ root = next(+ (m for m in tags if m.group(1).lower() == "apex" and m.group(2).lower() in _ROOT_TAGS),+ None,+ )+ if root is None:+ return {}+ if root.group(2).lower() == "page":+ idx.graph.nodes[path]["is_entry_point"] = True+ return _attrs(root.group(3))+++def _bind_constructors(+ idx: _VfIndex, path: str, controllers: list[tuple[str, str]], custom: str, edges: _Edges+) -> None:+ has_custom = bool(custom.strip())+ for i, (cls_file, cls) in enumerate(controllers):+ # A controller is built with no argument, an extension with the controller.+ arity = 0 if i == 0 and has_custom else 1+ edges.bind(path, cls_file, idx.constructors(cls_file, cls, arity), cls)+++def _markup_edges(idx: _VfIndex, path: str, edges: _Edges) -> None:+ text = _mask_xml(idx.text(path))+ tags = list(_TAG_RE.finditer(text))+ root_attrs = _root_attrs(idx, path, tags)+ controllers = _controllers(idx, path, root_attrs)+ _bind_constructors(idx, path, controllers, root_attrs.get("controller", ""), edges)++ names = _MarkupNames(text, root_attrs)+ _tag_edges(idx, path, tags, names, edges)+ for m in _PAGE_GLOBAL_RE.finditer(text):+ edges.file(path, idx.page(m.group(1), path))++ if not controllers:+ return+ seen: set[str] = set()+ for body in _expressions(text):+ for name in _member_names(body):+ low = name.lower()+ if low not in seen and not names.skips(low):+ seen.add(low)+ _bind_member(idx, path, controllers, low, names.writes(low), edges)+++def _bind_member(+ idx: _VfIndex,+ path: str,+ controllers: list[tuple[str, str]],+ name: str,+ is_setter: bool,+ edges: _Edges,+) -> None:+ """Bind ``{!name}`` to the first controller or extension member it names."""+ for top in controllers:+ for cls_file, cls in idx.chain(*top):+ members = idx.members(cls_file, cls)+ if name in members and name != cls.lower():+ edges.bind(path, cls_file, members[name], name)+ return+ getter, setter = members.get(f"get{name}"), members.get(f"set{name}")+ if getter or (is_setter and setter):+ edges.bind(path, cls_file, getter or [], f"get{name}")+ if is_setter and setter:+ edges.bind(path, cls_file, setter, f"set{name}")+ return+++def _apex_edges(idx: _VfIndex, path: str, edges: _Edges) -> None:+ raw = idx.text(path)+ # A repository class named Page would shadow the platform's.+ if "page" not in idx.apex:+ code = mask_comments_and_strings(raw, hash_comments=False)+ for m in _APEX_PAGE_RE.finditer(code):+ target = idx.page(m.group(1), path)+ if target is not None:+ edges.file(path, target, {m.group(1)})+ literals = mask_comments_and_strings(raw, strings=False, hash_comments=False)+ for m in _PAGE_REFERENCE_RE.finditer(literals):+ target = idx.page(m.group(1), path)+ if target is not None:+ edges.dynamic.add((path, target))+++def _add_visualforce_edges(+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext+) -> int:+ idx = _VfIndex(graph, parsed_files, ctx)+ edges = _Edges(graph)+ for path in sorted(parsed_files):+ lang = parsed_files[path].file_info.language+ if lang == "visualforce" and path in graph:+ _markup_edges(idx, path, edges)+ elif lang == "apex" and idx.pages:+ _apex_edges(idx, path, edges)+ return edges.flush()+++class _VisualforceHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ return any(p.file_info.language == "visualforce" for p in dctx.parsed_files.values())++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ return _add_visualforce_edges(graph, parsed_files, ctx)+++HANDLERS: list[FrameworkHandler] = [_VisualforceHandler()]diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.pyindex 9bf010e4f..37e3bcb1c 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -66,6 +66,7 @@ from .toml import SPEC as _TOMLfrom .typescript import SPEC as _TYPESCRIPTfrom .unknown import SPEC as _UNKNOWNfrom .vbnet import SPEC as _VBNET+from .visualforce import SPEC as _VISUALFORCEfrom .vue import SPEC as _VUEfrom .xaml import SPEC as _XAMLfrom .yaml import SPEC as _YAML@@ -134,6 +135,8 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (# root-relative asset paths. Markup, so it is never reported as dead code# while its edges still anchor what it references._HTML,+ # Salesforce Visualforce markup: no symbols, edges from framework_edges/visualforce.py.+ _VISUALFORCE,# XAML / AXAML markup for WPF, WinUI 3, UWP, MAUI, Avalonia, Uno.# No AST grammar — handled by the XamlDynamicHints extractor which# emits ``dynamic_uses`` edges to bound C# types. Registered here sodiff --git a/packages/core/src/repowise/core/ingestion/languages/specs/visualforce.py b/packages/core/src/repowise/core/ingestion/languages/specs/visualforce.pynew file mode 100644index 000000000..b21d31292--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/visualforce.py@@ -0,0 +1,18 @@+"""LanguageSpec for Salesforce Visualforce pages and components, an edge-only tag.++Markup declares no symbols (``is_code=False``, never reported as dead); the+edges come from ``framework_edges/visualforce.py``. Both suffixes are claimed+anywhere, as Salesforce maps them to ApexPage / ApexComponent in any folder.+"""++from ..spec import LanguageSpec++SPEC = LanguageSpec(+ tag="visualforce",+ display_name="Visualforce",+ extensions=frozenset({".page", ".component"}),+ is_code=False,+ is_passthrough=True,+ # Salesforce blue, the same as the Apex spec.+ color_hex="#1797C0",+)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex c5a98ad30..e4b8daf6e 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -81,6 +81,8 @@ LanguageTag = Literal["xaml",# Markup with no symbols, but <script src>/<link href> are real edges."html",+ # Salesforce Visualforce (.page/.component): markup that names its Apex controller.+ "visualforce",# Lightweight: qmldir-declared module imports and quoted references."qml",# Godot .tscn/.tres/.escn + project.godot: data with no symbols, butdiff --git a/tests/unit/ingestion/test_visualforce_framework_edges.py b/tests/unit/ingestion/test_visualforce_framework_edges.pynew file mode 100644index 000000000..d6bfb1625--- /dev/null+++ b/tests/unit/ingestion/test_visualforce_framework_edges.py@@ -0,0 +1,263 @@+"""Salesforce Visualforce: page and component edges to Apex and to each other.++End to end through traverse -> parse -> graph -> framework edges, the path a+real index takes.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_D = "force-app/main/default"+_PAGE = f"{_D}/pages/AccountEdit.page"+_CMP = f"{_D}/components/AddressBlock.component"+_CTRL = f"{_D}/classes/AccountEditCtrl.cls"+_BASE = f"{_D}/classes/BaseCtrl.cls"+_EXT = f"{_D}/classes/AuditExt.cls"+_CMP_CTRL = f"{_D}/classes/AddressBlockCtrl.cls"++_REPO = {+ "sfdx-project.json": '{"packageDirectories": [{"path": "force-app"}], "namespace": "acme"}',+ _PAGE: (+ '<apex:page Controller="AccountEditCtrl" extensions="acme.AuditExt, other.Foreign"'+ ' action="{!init}">\n'+ " <!-- {!commentedOut} <c:Retired/> -->\n"+ " <apex:form>\n"+ ' <apex:inputText value="{!searchTerm}"/>\n'+ ' <apex:outputText value="{!IF(NOT(isAdmin), $Label.Hello, title)}"/>\n'+ ' <apex:outputField value="{!acc.Name}"/>\n'+ ' <apex:repeat value="{!rows}" var="row">{!row.Name} {!auditCount}</apex:repeat>\n'+ ' <apex:commandButton action="{!save}" value="{!baseLabel}"/>\n'+ ' <apex:selectList value="{!pick}"><apex:selectOptions value="{!items}"/></apex:selectList>\n'+ " <apex:outputText value=\"{!LEN('missing')} {!notAMember}\"/>\n"+ " </apex:form>\n"+ ' <c:addressBlock record="{!acc}"/>\n'+ " <acme:AddressBlock/>\n"+ " <other:AddressBlock/>\n"+ ' <apex:include pageName="acme__Footer"/>\n'+ ' <a href="{!URLFOR($Page.Help)}">help</a>\n'+ " <script>var x = '{!JSENCODE(secret)}';</script>\n"+ "</apex:page>\n"+ ),+ f"{_D}/pages/Footer.page": "<apex:page>footer</apex:page>\n",+ f"{_D}/pages/Help.page": "<apex:page>help</apex:page>\n",+ f"{_D}/pages/Orphan.page": '<apex:page standardController="Account">{!Account.Name}</apex:page>\n',+ _CMP: (+ '<apex:component controller="AddressBlockCtrl">\n'+ ' <apex:attribute name="record" type="Account" assignTo="{!rec}" description="x"/>\n'+ ' <apex:attribute name="title" type="String" assignTo="{!title}"/>\n'+ " {!record.Name} {!street}\n"+ "</apex:component>\n"+ ),+ _CTRL: (+ "public with sharing class AccountEditCtrl extends BaseCtrl {\n"+ " public AccountEditCtrl() {}\n"+ " public String searchTerm { get; set; }\n"+ " public Boolean isAdmin { get; private set; }\n"+ " public Account acc { get; set; }\n"+ " private String secret;\n"+ " public String getTitle() { return ''; }\n"+ " public List<Account> getRows() { return null; }\n"+ " public PageReference init() { return null; }\n"+ " public PageReference save() { return null; }\n"+ " public String getPick() { return null; }\n"+ " public void setPick(String p) {}\n"+ " public List<SelectOption> getItems() { return null; }\n"+ " public void setItems(List<SelectOption> s) {}\n"+ "}\n"+ ),+ _BASE: "public virtual class BaseCtrl {\n public String baseLabel { get; set; }\n}\n",+ _EXT: (+ "public class AuditExt {\n"+ " public AuditExt() {}\n"+ " public AuditExt(AccountEditCtrl c) {}\n"+ " public Integer auditCount { get; set; }\n"+ " public String searchTerm { get; set; }\n"+ "}\n"+ ),+ _CMP_CTRL: (+ "public class AddressBlockCtrl {\n"+ " public Account rec { get; set; }\n"+ " public String title { get; set; }\n"+ " public String getStreet() { return ''; }\n"+ "}\n"+ ),+ f"{_D}/classes/Nav.cls": (+ "public class Nav {\n"+ " // Page.Orphan in a comment\n"+ " public PageReference go() { return Page.ACCOUNTEDIT; }\n"+ " public PageReference again() { return new PageReference('/apex/AccountEdit'); }\n"+ " public PageReference url() { return new PageReference('/apex/Orphan?id=1'); }\n"+ " public String s() { return 'Page.Help'; }\n"+ " public PageReference built(String n) { return new PageReference('/apex/' + n); }\n"+ "}\n"+ ),+}+++def _write(repo: Path, files: dict[str, str]) -> Path:+ for rel, text in files.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return repo+++def _build(repo: Path):+ builder = GraphBuilder(repo)+ parser = ASTParser()+ source_map: dict[str, bytes] = {}+ for fi in FileTraverser(repo).traverse():+ src = Path(fi.abs_path).read_bytes()+ builder.add_file(parser.parse_file(fi, src))+ source_map[fi.path] = src+ builder.set_source_map(source_map)+ builder.build()+ builder.add_framework_edges([])+ return builder+++def _edges(graph, edge_type: str) -> set[tuple[str, str]]:+ return {(s, t) for s, t, d in graph.edges(data=True) if d.get("edge_type") == edge_type}+++def _bound(graph, src: str) -> set[str]:+ """``Class::member`` names bound from *src*'s markup."""+ return {+ t.split("::", 1)[1].split("#")[0]+ for s, t in _edges(graph, "framework_binds")+ if s == f"{src}::__module__"+ }+++def test_pages_and_components_are_visualforce(tmp_path: Path) -> None:+ builder = _build(_write(tmp_path, _REPO))+ langs = {p: pf.file_info.language for p, pf in builder._parsed_files.items()}+ assert langs[_PAGE] == "visualforce"+ assert langs[_CMP] == "visualforce"+++def test_controller_and_extension_edges(tmp_path: Path) -> None:+ g = _build(_write(tmp_path, _REPO)).graph()+ framework = _edges(g, "framework")+ assert {(_PAGE, _CTRL), (_PAGE, _EXT), (_PAGE, _BASE), (_CMP, _CMP_CTRL)} <= framework+ assert g.nodes[_PAGE].get("is_entry_point") is True+ assert not g.nodes[_CMP].get("is_entry_point")+++def test_expression_members_bind_in_lookup_order(tmp_path: Path) -> None:+ g = _build(_write(tmp_path, _REPO)).graph()+ bound = _bound(g, _PAGE)+ assert {+ "AccountEditCtrl::AccountEditCtrl", # constructed by the platform+ "AuditExt::AuditExt",+ "AccountEditCtrl::init",+ "AccountEditCtrl::searchTerm", # controller wins over the extension+ "AccountEditCtrl::isAdmin",+ "AccountEditCtrl::getTitle",+ "AccountEditCtrl::acc",+ "AccountEditCtrl::getRows",+ "AccountEditCtrl::save",+ "AccountEditCtrl::getPick",+ "AccountEditCtrl::setPick", # input value: written back through the setter+ "AccountEditCtrl::getItems",+ "AuditExt::auditCount",+ "BaseCtrl::baseLabel", # inherited through extends+ } <= bound+ # An extension is built with the page's controller, never with no argument.+ ext_ctors = {+ t for s, t in _edges(g, "framework_binds") if t.startswith(f"{_EXT}::AuditExt::AuditExt")+ }+ assert len(ext_ctors) == 1 and "AccountEditCtrl" in g.nodes[ext_ctors.pop()]["signature"]+ assert "AuditExt::searchTerm" not in bound+ assert "AccountEditCtrl::setItems" not in bound # selectOptions only reads+ assert "AccountEditCtrl::secret" not in bound # private+ assert g.edges[_PAGE, _CTRL]["imported_names"][:2] == ["AccountEditCtrl", "acc"]+++def test_component_attributes_and_assign_to(tmp_path: Path) -> None:+ g = _build(_write(tmp_path, _REPO)).graph()+ # `record` is the component's own attribute; `title` is too, but its+ # assignTo writes the controller property of the same name.+ assert _bound(g, _CMP) == {+ "AddressBlockCtrl::rec",+ "AddressBlockCtrl::getStreet",+ "AddressBlockCtrl::title",+ }+++def test_component_tags_and_page_references(tmp_path: Path) -> None:+ g = _build(_write(tmp_path, _REPO)).graph()+ framework = _edges(g, "framework")+ assert (_PAGE, _CMP) in framework # <c:addressBlock>, case folded; <acme:...> too+ assert (_PAGE, f"{_D}/pages/Footer.page") in framework # own ns__ prefix dropped+ assert (_PAGE, f"{_D}/pages/Help.page") in framework # $Page.Help+ nav = f"{_D}/classes/Nav.cls"+ # Page.ACCOUNTEDIT; the literal to the same page keeps the compile-checked edge.+ assert (nav, _PAGE) in framework+ assert (nav, _PAGE) not in _edges(g, "dynamic_uses")+ assert (nav, f"{_D}/pages/Help.page") not in framework # a string, not code+ assert (nav, f"{_D}/pages/Orphan.page") in _edges(g, "dynamic_uses")+ assert g.edges[nav, f"{_D}/pages/Orphan.page"]["hint_source"] == "vf_page_reference"+ assert not any(t.endswith("Retired.component") for _, t in framework)+++_NEG = {+ "sfdx-project.json": '{"packageDirectories": [{"path": "a"}, {"path": "b"}], "namespace": "acme"}',+ "a/pages/Dup.page": "<apex:page/>\n",+ "b/pages/Dup.page": "<apex:page/>\n",+ "a/pages/Report_.page": "<apex:page/>\n",+ "a/pages/getParameters.page": "<apex:page/>\n",+ "a/pages/Main.page": (+ '<apex:page controller="MainCtrl">\n'+ ' <apex:include pageName="other__Report_"/>\n'+ " {!hidden} {!guarded} {!writeOnly}\n"+ ' <apex:inputText value="{!writeOnly}"/>\n'+ "</apex:page>\n"+ ),+ # Not Visualforce markup: no root tag, so not an entry point.+ "a/pages/Notes.page": "plain text\n",+ "a/classes/MainCtrl.cls": (+ "public class MainCtrl {\n"+ " protected String hidden { get; set; }\n"+ " private String getGuarded() { return ''; }\n"+ " public void setWriteOnly(String s) {}\n"+ "}\n"+ ),+ "c/classes/Nav.cls": (+ "public class Nav {\n"+ " public void go(PageReference page, String kind) {\n"+ " page.getParameters();\n"+ " PageReference a = Page.Dup;\n"+ " PageReference b = new PageReference('/apex/Report_' + kind);\n"+ " }\n"+ "}\n"+ ),+}+++def test_refusals(tmp_path: Path) -> None:+ g = _build(_write(tmp_path, _NEG)).graph()+ nav = "c/classes/Nav.cls"+ targets = {t for s, t in g.out_edges(nav) if t.endswith(".page")}+ # Two equally near Dup pages, a method call on a local named `page`, and+ # a concatenated literal that is only a prefix of a page name.+ assert targets == set()+ main = "a/pages/Main.page"+ assert not any(t.endswith("Report_.page") for _, t in g.out_edges(main)) # foreign ns+ # Protected and private members never bind; a setter alone binds for an input.+ assert _bound(g, main) == {"MainCtrl::setWriteOnly"}+ assert g.nodes[main].get("is_entry_point") is True+ assert not g.nodes["a/pages/Notes.page"].get("is_entry_point")+++def test_a_class_named_page_shadows_page_references(tmp_path: Path) -> None:+ files = {+ "pages/Foo.page": "<apex:page/>\n",+ "classes/Page.cls": "public class Page { public static String Foo = ''; }\n",+ "classes/Use.cls": "public class Use { String s = Page.Foo; }\n",+ }+ g = _build(_write(tmp_path, files)).graph()+ assert not g.has_edge("classes/Use.cls", "pages/Foo.page")