xref: /llvm-project/lldb/examples/python/shadow.py (revision 2238dcc39358353cac21df75c3c3286ab20b8f53)
1#!/usr/bin/env python
2
3import lldb
4import shlex
5
6
7@lldb.command("shadow")
8def check_shadow_command(debugger, command, exe_ctx, result, dict):
9    """Check the currently selected stack frame for shadowed variables"""
10    process = exe_ctx.GetProcess()
11    state = process.GetState()
12    if state != lldb.eStateStopped:
13        print(
14            "process must be stopped, state is %s"
15            % lldb.SBDebugger.StateAsCString(state),
16            file=result,
17        )
18        return
19    frame = exe_ctx.GetFrame()
20    if not frame:
21        print("invalid frame", file=result)
22        return
23    # Parse command line args
24    command_args = shlex.split(command)
25    # TODO: add support for using arguments that are passed to this command...
26
27    # Make a dictionary of variable name to "SBBlock and SBValue"
28    shadow_dict = {}
29
30    num_shadowed_variables = 0
31    # Get the deepest most block from the current frame
32    block = frame.GetBlock()
33    # Iterate through the block and all of its parents
34    while block.IsValid():
35        # Get block variables from the current block only
36        block_vars = block.GetVariables(frame, True, True, True, 0)
37        # Iterate through all variables in the current block
38        for block_var in block_vars:
39            # Since we can have multiple shadowed variables, we our variable
40            # name dictionary to have an array or "block + variable" pairs so
41            # We can correctly print out all shadowed variables and whow which
42            # blocks they come from
43            block_var_name = block_var.GetName()
44            if block_var_name in shadow_dict:
45                shadow_dict[block_var_name].append(block_var)
46            else:
47                shadow_dict[block_var_name] = [block_var]
48        # Get the parent block and continue
49        block = block.GetParent()
50
51    num_shadowed_variables = 0
52    if shadow_dict:
53        for name in shadow_dict.keys():
54            shadow_vars = shadow_dict[name]
55            if len(shadow_vars) > 1:
56                print('"%s" is shadowed by the following declarations:' % (name))
57                num_shadowed_variables += 1
58                for shadow_var in shadow_vars:
59                    print(str(shadow_var.GetDeclaration()), file=result)
60    if num_shadowed_variables == 0:
61        print("no variables are shadowed", file=result)
62