graphify icon indicating copy to clipboard operation
graphify copied to clipboard

VB.NET: qualified calls to modules/types in other files are dropped; multi-line string literals and `ByVal Optional` break parsing of the whole file

Open jjvegamelis opened this issue 1 week ago • 9 comments

Version: graphifyy 0.9.112 (graphifyy[vbnet]), Windows, graphify extract <path> --code-only

1. Qualified calls to a type/module declared in another file produce no edge

In extractors/vbnet.py, a qualified call such as DataLayer.LoadCustomers() is resolved through owner_by_short, which only contains types declared in the same file. When the receiver type lives in another file, target_owner is None and the call is neither linked nor stored in raw_calls, so the cross-file pass never sees it. In typical WinForms projects most calls go to shared helper classes/modules in other files, so most of the call graph is missing.

Minimal repro (two files):

' DataLayer.vb
Public Class DataLayer
    Public Shared Function LoadCustomers() As Integer
        Return 0
    End Function
End Class
' Form1.vb
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim n = DataLayer.LoadCustomers()
    End Sub
End Class

Expected: Button1_Click --calls--> LoadCustomers. Actual: no edge (graphify explain LoadCustomers shows no callers).

The same happens with unqualified calls to members of a Module declared in another file (VB modules are imported project-wide, so HelperFunction() can be called without a prefix).

A local patch that fixed it for us (about 2,000 new edges on a ~380-file project, all checked against grep on a sample): store those calls in raw_calls with the receiver's short name (and mark unqualified ones), then resolve them in resolve_vbnet_partial_calls against all VB types (and against Module members for unqualified calls), only when exactly one candidate matches, tagged INFERRED. Diff below.

Note: after changing the extractor the AST cache (graphify-out/cache/ast) had to be deleted by hand; --force still served the old per-file results.

2. Two constructs make tree-sitter-vb-dotnet wrap the whole file in a single ERROR node (all its methods are lost)

Module M
    Sub A()
        Dim s = "first line
second line"          ' multi-line string literal (VB 14 / VS 2015+)
    End Sub
End Module
Module M
    Sub B(ByVal Optional x As Integer = 0)   ' fails; "Optional ByVal" parses fine
    End Sub
End Module

Both compile with the VB compiler. A single occurrence is enough to lose every method in the file (in our case files with embedded JavaScript for browser automation, and a 5,000-line module with one ByVal Optional). This is probably a grammar issue upstream, but it might be worth a warning in the extract output ("N files produced a parse error"), since today it is silent.

Patch for point 1

--- a/graphify/extractors/vbnet.py	2026-11-18 16:15:38.706065600 +0000
+++ b/graphify/extractors/vbnet.py	2026-11-18 16:16:08.681996900 +0000
@@ -43,6 +43,29 @@
                         (owner.casefold(), name.casefold(), arity), []
                     ).append(node["id"])
 
+    # local patch: short type name -> owner keys, and which owners are Modules
+    short_to_owners: dict[str, set[str]] = {}
+    module_owners: set[str] = set()
+    for node in all_nodes:
+        metadata = node.get("metadata")
+        if not isinstance(metadata, dict) or metadata.get("language") != "vbnet":
+            continue
+        kind = metadata.get("kind")
+        full_name = metadata.get("full_name")
+        name = metadata.get("name")
+        if kind in _TYPE_BLOCKS.values() and isinstance(full_name, str) and isinstance(name, str):
+            short_to_owners.setdefault(name.casefold(), set()).add(full_name.casefold())
+            if kind == "module":
+                module_owners.add(full_name.casefold())
+
+    def _candidates(owners, callee: str, arity: int) -> list[str]:
+        found: list[str] = []
+        for owner in owners:
+            for nid in methods.get((owner, callee.casefold(), arity), []):
+                if nid not in found:
+                    found.append(nid)
+        return found
+
     existing = {
         (edge.get("source"), edge.get("target"))
         for edge in all_edges
@@ -50,14 +73,24 @@
     }
     for result in per_file:
         for call in result.get("raw_calls", []):
-            if call.get("language") != "vbnet" or not call.get("owner"):
+            if call.get("language") != "vbnet":
+                continue
+            callee = str(call.get("callee", ""))
+            arity = int(call.get("arity", -1))
+            context = "partial_type_call"
+            confidence = "EXTRACTED"
+            candidates: list[str] = []
+            if call.get("owner"):
+                candidates = methods.get((str(call["owner"]).casefold(), callee.casefold(), arity), [])
+                if not candidates and call.get("unqualified"):
+                    candidates = _candidates(module_owners, callee, arity)
+                    context, confidence = "module_call", "INFERRED"
+            elif call.get("owner_short"):
+                owners = short_to_owners.get(str(call["owner_short"]).casefold(), set())
+                candidates = _candidates(owners, callee, arity)
+                context, confidence = "qualified_cross_file_call", "INFERRED"
+            else:
                 continue
-            key = (
-                str(call["owner"]).casefold(),
-                str(call.get("callee", "")).casefold(),
-                int(call.get("arity", -1)),
-            )
-            candidates = methods.get(key, [])
             caller = call.get("caller_nid")
             if len(candidates) != 1 or candidates[0] == caller:
                 continue
@@ -69,9 +102,9 @@
                 "source": caller,
                 "target": candidates[0],
                 "relation": "calls",
-                "context": "partial_type_call",
-                "confidence": "EXTRACTED",
-                "confidence_score": 1.0,
+                "context": context,
+                "confidence": confidence,
+                "confidence_score": 1.0 if confidence == "EXTRACTED" else 0.9,
                 "source_file": call.get("source_file", ""),
                 "source_location": call.get("source_location"),
                 "weight": 1.0,
@@ -424,10 +457,28 @@
                                 "arity": arity,
                                 "owner": target_owner,
                                 "is_member_call": True,
+                                # local patch: no receiver, it may be a member of a
+                                # Module declared in another file
+                                "unqualified": not receiver,
                                 "language": "vbnet",
                                 "source_file": source_file,
                                 "source_location": f"L{node.start_point[0] + 1}",
                             })
+                    elif receiver and receiver not in {"mybase", "me", "myclass"}:
+                        # local patch: receiver type/module declared in
+                        # another file (OtherType.X()): keep it for the cross-file pass
+                        arity = len(arguments.named_children) if arguments is not None else 0
+                        raw_calls.append({
+                            "caller_nid": caller_id,
+                            "callee": callee,
+                            "arity": arity,
+                            "owner": None,
+                            "owner_short": receiver.split(".")[-1],
+                            "is_member_call": True,
+                            "language": "vbnet",
+                            "source_file": source_file,
+                            "source_location": f"L{node.start_point[0] + 1}",
+                        })
             stack.extend(reversed(node.named_children))
 
     clean_edges = [

jjvegamelis avatar Nov 18 '26 16:11 jjvegamelis

Thanks for opening this issue, @jjvegamelis. A maintainer will take a look soon.

If you would like to discuss it in real time, come say hi on our Discord server. For longer-form questions and ideas there is also GitHub Discussions.

To help us triage, please make sure the report includes what you expected, what actually happened, and the steps (and a small sample) to reproduce it.

github-actions[bot] avatar Nov 18 '26 16:11 github-actions[bot]

Thanks for the detailed report and the patch. I went through each point on 0.9.112:

1. Qualified and Module calls into another file. Reproduced: both of your examples give no edge. #4573 covers this (cross-file Module members, Type.Member(), typed locals, C# statics), and #4623 on top of it handles calls through fields, Me.field and With blocks. I rebased both onto 0.9.112 today; with them, Button1_Click -> LoadCustomers and Go -> HelperFunction both appear.

2a. ByVal Optional. On my side the file's methods survive, but every call that leaves the optional argument out is dropped: the extractor only treated a parameter as optional when its text started with Optional. #5327 fixes that by checking for a default value instead (the VB compiler requires one exactly when the parameter is Optional).

2b. Multi-line string literals. I couldn't reproduce the whole file being lost. With your snippet, and with a multi-line JS body containing ' and {}, tree-sitter-vb-dotnet 0.3.0 keeps the error inside that one statement and every method and call survives. Could you share (or trim down) a file where the methods disappear, along with your tree-sitter-vb-dotnet version?

Cache after a local patch. That's expected: --force skips the semantic cache, and the AST cache is keyed on the package version, so a local edit without a version bump is served from cache. Released fixes bump the cache schema.

Deepjyoti-Sarmah avatar Nov 18 '26 20:11 Deepjyoti-Sarmah

Thanks a lot for the quick and thorough answer — great news about #4573/#4623 and #5327.

On 2b, I narrowed it down. Same versions as you: tree-sitter-vb-dotnet 0.3.0 (tree-sitter 0.25.2, graphifyy 0.9.112). The trigger is a single quote ' on a continuation line of a multi-line string literal (not on its first line):

Public Class Demo
    Public Sub Antes()
        Dim a = 1
    End Sub
    Public Sub Medio(ByVal id As String)
        Dim s = "
        var el = document.getElementById('abc');
        return el;"
    End Sub

    Public Sub Despues()
        Dim b = 2
    End Sub
End Class

Parsing this with tree-sitter-vb-dotnet 0.3.0 gives an ERROR node from line 6 to the end of the file, and only 2 of the 3 methods survive (Despues is lost). It looks like the ' on line 7 is taken as the start of a comment, which swallows the closing ". Variants I tried:

  • ' on the first line of the multi-line string (Dim s = "x('abc'); + newline + return el;"): OK, 3/3
  • multi-line string without any ': OK, 3/3
  • same content on a single line: OK, 3/3
  • ' on a continuation line, with or without " & id & " around it: broken (2/3)

In our code base this pattern is common (JavaScript injected into WebView2/Selenium), which is why whole files dropped out. Since this is in the grammar rather than in graphify, I can open an issue on tree-sitter-vb-dotnet if you prefer.

The cache explanation makes sense, thanks.

jjvegamelis avatar Nov 18 '26 22:11 jjvegamelis

Thanks, that narrowed it down. I reproduced it with your file on tree-sitter-vb-dotnet 0.3.0: the ERROR node runs from line 6 to the end of the file and Despues is lost. With the ' on the first line of the string, or with no ' at all, it parses fine, same as you saw.

Yes, please open the issue on tree-sitter-vb-dotnet. Once a string literal crosses a line break, the grammar seems to read ' as the start of a comment, so it never sees the closing ". A fix there helps every tool that uses the grammar.

On the graphify side, I'll check whether we can keep the methods after a broken statement from disappearing. That's a separate change, so it stays out of #5327.

Deepjyoti-Sarmah avatar Nov 19 '26 14:11 Deepjyoti-Sarmah

Thanks! Opened it here: https://github.com/CodeAnt-AI/tree-sitter-vb-dotnet/issues/9. Note that the PyPI package is built from repowise-dev/tree-sitter-vb-dotnet, a fork of CodeAnt-AI's, and issues are disabled on that fork, so I filed it on the original repository. Looking forward to the change on the graphify side.

jjvegamelis avatar Nov 19 '26 17:11 jjvegamelis

Thanks for filing it upstream. The graphify-side change is up as #5345.

It narrowed down further: the ' comment swallows the ) of getElementById('abc'), and the unclosed ( is what loses the rest of the file. A bare foo(1 with no string at all does the same. So #5345 flattens a string that spans lines before parsing, keeping line numbers. With your file, Despues() is back on line 12 along with its calls, and multi-line $"..." strings work too.

It also fixes a slowdown: on an 8,000-line file, one multi-line string made the parse take 14.5 s instead of 0.1 s. That's gone now.

Once tree-sitter-vb-dotnet supports multi-line strings, the rewrite will no longer be needed.

Deepjyoti-Sarmah avatar Nov 19 '26 18:11 Deepjyoti-Sarmah

Thanks a lot for digging into this and for #5345 — flattening multi-line strings while keeping line numbers is a neat fix, and the speed-up is a nice bonus. I'll update and regenerate our graph as soon as it's released, and report back if anything else in our VB.NET files still breaks.

El jue, 19 nov 2026 a las 18:14, Deepjyoti Sarmah @.***>) escribió:

Deepjyoti-Sarmah left a comment (Graphify-Labs/graphify#5320) https://github.com/Graphify-Labs/graphify/issues/5320#issuecomment-7017864053

Thanks for filing it upstream. The graphify-side change is up as #5345 https://github.com/Graphify-Labs/graphify/pull/5345.

It narrowed down further: the ' comment swallows the ) of getElementById('abc'), and the unclosed ( is what loses the rest of the file. A bare foo(1 with no string at all does the same. So #5345 https://github.com/Graphify-Labs/graphify/pull/5345 flattens a string that spans lines before parsing, keeping line numbers. With your file, Despues() is back on line 12 along with its calls, and multi-line $"..." strings work too.

It also fixes a slowdown: on an 8,000-line file, one multi-line string made the parse take 14.5 s instead of 0.1 s. That's gone now.

Once tree-sitter-vb-dotnet supports multi-line strings, the rewrite will no longer be needed.

— Reply to this email directly, view it on GitHub https://github.com/Graphify-Labs/graphify/issues/5320?email_source=notifications&email_token=BRKJW6R7ACNP4JTCJDNA4KT5Z4Z7VA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTOMBRG44DMNBQGUZ2M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLDGN5XXIZLSL5RWY2LDNM#issuecomment-7017864053, or unsubscribe https://github.com/notifications/unsubscribe-auth/BRKJW6RPJYZ7SSPTOGDE5KT5Z4Z7VAVCNFSNUABGKJSXA33TNF2G64TZHMYTEMBQGU4TOMRWGM5US43TOVSTWNRUG4YTQMJRGE3THILWAI . Triage notifications, keep track of coding agent tasks and review pull requests on the go with GitHub Mobile for iOS https://github.com/notifications/mobile/ios/BRKJW6WIE3RLBIZ5BJNY2535Z4Z7VA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTOMBRG44DMNBQGUZ2M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJKTGN5XXIZLSL5UW64Y and Android https://github.com/notifications/mobile/android/BRKJW6WQSNISYEYPUBF33N35Z4Z7VA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTOMBRG44DMNBQGUZ2M4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLTGN5XXIZLSL5QW4ZDSN5UWI. Download it today! You are receiving this because you were mentioned.Message ID: <Graphify-Labs/graphify/issues/5320/7017864053 @.*** com>

-- Reciba un afectuoso saludo .

*YADIRA GONZALEZ RUEDA *

  •                Abogada*
    

Calle Pedro de Vera 2 Código Postal 35003 LPGC- España. Teléfono 928365457 Móvil: 653 754 791 Whatsapp: 669 976 795

www.yadiragonzalezrueda.com

En cumplimiento del Reglamento (UE) 2016 /679 y de la Ley Orgánica de Protección de Datos de Carácter Personal, le informamos de que la identidad del responsable que trata sus datos personales es: YADIRA GONZÁLEZ RUEDA con NIF 49407761N, dirección calle Carmen Llopis 7, local exterior, código postal 35003, provincia Las Palmas y Correo electrónico @.***

Los datos personales que tratamos en nuestra organización son los mínimos necesarios para contactar con usted vía correo electrónico, con la finalidad de enviarle información, incluida, en su caso, la comercial y/o publicitaria. Le informamos de que todos ellos están protegidos con las seguridades necesarias y de que serán conservados exclusivamente hasta la finalización de la prestación de servicios jurídicos.

Este tratamiento se basa en nuestro interés legítimo en comunicarnos con usted, en cumplimiento y/o mantenimiento de relaciones comerciales o laborales. Le informamos de que no compartiremos sus datos personales, facilitados por usted.

Recuerde que tiene una serie de derechos en relación con el uso de sus datos personales. Le garantizamos el ejercicio del derecho de acceso, rectificación, supresión, oposición, limitación, portabilidad y oposición a la toma de decisiones. A fin de que sus datos sean un fiel reflejo de la realidad, no dude en hacer uso de su derecho de rectificación en el caso de que estos sufran alguna modificación, cambio o anulación. Puede ejercer todos estos derechos remitiendo un e-mail a la dirección arriba indicada. También tiene derecho a presentar reclamaciones ante la Agencia Protección de Datos y acudir a los Tribunales de Justicia.

Por último, le recordamos que el contenido íntegro del presente correo se dirige exclusivamente a su destinatario y es estrictamente confidencial. Si usted lo hubiera recibido por error, queda obligado a guardar secreto y a destruirlo de inmediato, poniéndose en contacto con el remitente a la mayor brevedad posible a fin de comunicarle la incidencia. Gracias.

jjvegamelis avatar Nov 20 '26 14:11 jjvegamelis

Thanks for shipping the multi-line string fix in 0.9.114.

I updated to 0.9.118 and regenerated the graph of our VB.NET WinForms codebase (about 12,350 nodes and 23,300 edges, roughly 40 s with extract --code-only --force). The multi-line literal problem is gone: every method declared after a multi-line string literal (injected JavaScript inside "..." spanning several lines, with ' and unbalanced parentheses inside) now shows up in the graph. In the files that used to be truncated I get the same count of Sub/Function in the graph as in the source.

What is still open on my side is the first part of this issue: qualified calls to Module members and to types in other files (Module.Function, typed fields, Me.field) are still dropped. I keep a small local patch in extractors/vbnet.py for that, and it still applies cleanly on 0.9.118. #4573 and #4623 cover it; are they planned for an upcoming release?

Two small notes:

  • graphify explain failed after the upgrade with ModuleNotFoundError: No module named 'anyio' (imported from graphify/serve.py). Installing graphifyy[vbnet] did not pull it in; pip install anyio fixed it. It may need to be a core dependency.
  • #5327 (ByVal Optional counted as optional) was closed without merging. Was it superseded by another change? I have not seen it mentioned in the changelog.

jjvegamelis avatar Nov 23 '26 17:11 jjvegamelis

Thanks for checking it on your codebase.

anyio: Confirmed, and it's a regression in 0.9.118. query, path, affected and benchmark fail the same way. The import in serve.py moved to module level, but anyio only comes with the mcp and all extras. The fix is up as #5422. Until it's released, pip install anyio is the right workaround.

#5327: It landed in 0.9.113 as 086d19f6. The changelog lists it under #5320.

#4573 / #4623: Both are still open, and yes, they cover the calls you listed. They conflict with the current branch, so I'll rebase them. The release timing is up to the maintainers.

Deepjyoti-Sarmah avatar Nov 23 '26 18:11 Deepjyoti-Sarmah