]> git.ipfire.org Git - thirdparty/binutils-gdb.git/commitdiff
Enable call of overloaded subscript operator from python
authorHannes Domani <ssbssa@yahoo.de>
Mon, 3 Jun 2024 15:23:26 +0000 (17:23 +0200)
committerHannes Domani <ssbssa@yahoo.de>
Mon, 3 Jun 2024 15:23:26 +0000 (17:23 +0200)
If you try to use the overloaded subscript operator of a class
in python, it fails like this:

(gdb) py print(gdb.parse_and_eval('b')[5])
Traceback (most recent call last):
  File "<string>", line 1, in <module>
gdb.error: Cannot subscript requested type.
Error while executing Python code.

This simply checks if such an operator exists, and calls it
instead, making this possible:

(gdb) py print(gdb.parse_and_eval('b')[5])
102 'f'

Approved-By: Tom Tromey <tom@tromey.com>
gdb/python/py-value.c
gdb/testsuite/gdb.python/py-value-cc.cc
gdb/testsuite/gdb.python/py-value-cc.exp

index 1ae26d73261f992de988aa9bb9bdb5de1f8ed77b..dada8bfb7e783e0a8603a79dcb837bde73134059 100644 (file)
@@ -1153,7 +1153,11 @@ valpy_getitem (PyObject *self, PyObject *key)
             type.  */
          struct value *idx = convert_value_from_python (key);
 
-         if (idx != NULL)
+         if (idx != NULL
+             && binop_user_defined_p (BINOP_SUBSCRIPT, tmp, idx))
+           res_val = value_x_binop (tmp, idx, BINOP_SUBSCRIPT,
+                                    OP_NULL, EVAL_NORMAL);
+         else if (idx != NULL)
            {
              /* Check the value's type is something that can be accessed via
                 a subscript.  */
index 2d38a26d948da2adfcaf9df343a5ac28bb27ff9b..08b99158d027084bc44447ca73574481dd3119df 100644 (file)
@@ -42,6 +42,7 @@ class B : public A {
   int arg0_func ();
   int arg1_func (int arg1);
   int arg2_func (int arg1, int arg2);
+  char operator[] (int num);
 };
 
 int B::static_func ()
@@ -64,6 +65,11 @@ int B::arg2_func (int arg1, int arg2)
   return a * arg1 + arg2;
 }
 
+char B::operator[] (int num)
+{
+  return a + num;
+}
+
 struct X
 {
   union { int x; char y; };
index 17a67e20c1cfde36d64a6976a0feff212ac0e5e9..b096c7538a13f20de2d50557efda4122abcd11f8 100644 (file)
@@ -99,6 +99,7 @@ gdb_test "python print(uu\[uu_fields\[1\]\]\['a'\])" "1000" "uu.a via field"
 # Test overloaded operators.
 gdb_test_no_output "python a = gdb.parse_and_eval('a')" "init a"
 gdb_test "python print(a + 5)" "10" "a + 5"
+gdb_test "python print(gdb.parse_and_eval('b')\[5\])" "102 'f'"
 
 # Test inferior function calls of methods.
 gdb_test "py print(b_obj\['static_func'\]())" "1111"