[Lldb-commits] [lldb] [lldb][python] Add polymorphic `__getitem__` to `SBModuleSpecList` for Pythonic indexing (PR #189125)

Piyush Jaiswal via lldb-commits lldb-commits at lists.llvm.org
Mon Apr 6 14:29:42 PDT 2026


https://github.com/piyushjaiswal98 updated https://github.com/llvm/llvm-project/pull/189125

>From 659c7a641110d22b318cf81027f5071fbda31d96 Mon Sep 17 00:00:00 2001
From: Piyush Jaiswal <piyushjais at meta.com>
Date: Fri, 27 Mar 2026 14:35:13 -0700
Subject: [PATCH] [lldb][python] Add __getitem__ to SBModuleSpecList for
 Pythonic indexing

SBModuleSpecList supports len() and iteration but is not subscriptable.
This adds a __getitem__ method following the same polymorphic lookup
pattern used by SBTarget.modules_access in SBTargetExtensions.i.

Supported key types:
- int: Direct index with negative index support: specs[0], specs[-1]
- str: Lookup by file basename or full path: specs['a.out']
- re.compile(...): Regex match on file path, returns a list
---
 .../interface/SBModuleSpecListExtensions.i    | 45 +++++++++---
 .../API/python_api/sbmodule/TestSBModule.py   | 72 +++++++++++++++++++
 2 files changed, 108 insertions(+), 9 deletions(-)

diff --git a/lldb/bindings/interface/SBModuleSpecListExtensions.i b/lldb/bindings/interface/SBModuleSpecListExtensions.i
index 073e9d06738f5..a4bfe474b430b 100644
--- a/lldb/bindings/interface/SBModuleSpecListExtensions.i
+++ b/lldb/bindings/interface/SBModuleSpecListExtensions.i
@@ -11,16 +11,43 @@ STRING_EXTENSION_OUTSIDE(SBModuleSpecList)
       '''Iterate over all ModuleSpecs in a lldb.SBModuleSpecList object.'''
       return lldb_iter(self, 'GetSize', 'GetSpecAtIndex')
 
-    def __getitem__(self, idx):
-      '''Get the ModuleSpec at a given index in an lldb.SBModuleSpecList object.'''
-      if not isinstance(idx, int):
-        raise TypeError("unsupported index type: %s" % type(idx))
+    def __getitem__(self, key):
+      '''Access module specs by index, full or partial path, or regular expression.
+         specs[0]                      - access by integer index
+         specs[-1]                     - access by negative integer index
+         specs['a.out']                - find first spec matching file basename
+         specs['/usr/lib/liba.dylib']  - find first spec matching file fullpath
+         specs[re.compile(r'lib.*')]   - find all specs matching regex on fullpath
+      '''
       count = len(self)
-      if not (-count <= idx < count):
-        raise IndexError("list index out of range")
-      idx %= count
-      return self.GetSpecAtIndex(idx)
+      if type(key) is int:
+          if -count <= key < count:
+              key %= count
+              return self.GetSpecAtIndex(key)
+          else:
+              raise IndexError("list index out of range")
+      elif type(key) is str:
+          if key.find('/') == -1:
+              for idx in range(count):
+                  spec = self.GetSpecAtIndex(idx)
+                  if spec.GetFileSpec().GetFilename() == key:
+                      return spec
+          else:
+              for idx in range(count):
+                  spec = self.GetSpecAtIndex(idx)
+                  if str(spec.GetFileSpec()) == key:
+                      return spec
+          return None
+      elif isinstance(key, type(re.compile(''))):
+          matching_specs = []
+          for idx in range(count):
+              spec = self.GetSpecAtIndex(idx)
+              re_match = key.search(str(spec.GetFileSpec()))
+              if re_match:
+                  matching_specs.append(spec)
+          return matching_specs
+      else:
+          raise TypeError("unsupported index type: %s" % type(key))
     %}
 #endif
 }
-
diff --git a/lldb/test/API/python_api/sbmodule/TestSBModule.py b/lldb/test/API/python_api/sbmodule/TestSBModule.py
index 1e6cdefc8d8f0..7cc68876ee4c6 100644
--- a/lldb/test/API/python_api/sbmodule/TestSBModule.py
+++ b/lldb/test/API/python_api/sbmodule/TestSBModule.py
@@ -1,5 +1,7 @@
 """Test the SBDModule APIs."""
 
+import re
+
 import lldb
 from lldbsuite.test.decorators import *
 from lldbsuite.test.lldbtest import *
@@ -110,3 +112,73 @@ def test_module_is_file_backed(self):
         self.assertSuccess(
             error, "couldn't destroy process %s" % background_process.pid
         )
+
+    @skipIfRemote
+    def test_module_spec_list_indexing(self):
+        """Test that SBModuleSpecList supports Pythonic indexing."""
+        self.build()
+        libfoo_path = self.getBuildArtifact("libfoo.a")
+        specs = lldb.SBModuleSpecList.GetModuleSpecifications(libfoo_path)
+        count = specs.GetSize()
+        self.assertGreater(count, 0, "Archive should have at least one module spec")
+
+        # Integer indexing: positive indices
+        for i in range(count):
+            self.assertEqual(
+                str(specs[i]),
+                str(specs.GetSpecAtIndex(i)),
+                "specs[%d] should match GetSpecAtIndex(%d)" % (i, i),
+            )
+
+        # Integer indexing: negative indices
+        self.assertEqual(
+            str(specs[-1]),
+            str(specs.GetSpecAtIndex(count - 1)),
+            "specs[-1] should match last element",
+        )
+        self.assertEqual(
+            str(specs[-count]),
+            str(specs.GetSpecAtIndex(0)),
+            "specs[-count] should match first element",
+        )
+
+        # Integer indexing: out of bounds raises IndexError
+        self.assertRaises(IndexError, lambda: specs[count])
+        self.assertRaises(IndexError, lambda: specs[-count - 1])
+
+        # Unsupported key type raises TypeError
+        self.assertRaises(TypeError, lambda: specs[1.5])
+
+        # String indexing: lookup by file basename
+        spec0 = specs.GetSpecAtIndex(0)
+        basename = spec0.GetFileSpec().GetFilename()
+        if basename:
+            found = specs[basename]
+            self.assertIsNotNone(found, "Should find spec by basename '%s'" % basename)
+            self.assertEqual(
+                found.GetFileSpec().GetFilename(),
+                basename,
+                "Found spec basename should match",
+            )
+
+        # String indexing: missing basename returns None
+        self.assertIsNone(
+            specs["nonexistent_file.xyz"],
+            "Lookup of nonexistent basename should return None",
+        )
+
+        # Regex indexing: match all specs
+        all_matches = specs[re.compile(r".*")]
+        self.assertEqual(
+            len(all_matches),
+            count,
+            "Regex '.*' should match all specs",
+        )
+
+        # Regex indexing: no matches returns empty list
+        no_matches = specs[re.compile(r"^ZZZZZ_no_match$")]
+        self.assertEqual(
+            len(no_matches),
+            0,
+            "Regex with no matches should return empty list",
+        )



More information about the lldb-commits mailing list