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