weggli icon indicating copy to clipboard operation
weggli copied to clipboard

Add captured_value python binding

Open andrestirabo opened this issue 11 months ago • 0 comments

Hi, I'd like to add a new python binding to be able to retrieve the value of the captured variables. I'm no sure exactly how to run the tests or run them against the new python library that is built. How should I do this?

Here is a quick example of what the new binding does:

In this example we just list the values for the different captures weggli-python-example.py

from collections import defaultdict
import weggli

captured_values = defaultdict(set)
capture_1 = '$capture1'
capture_2 = '$capture2'
capture_key_list = [capture_1, capture_2, '$doesNotExist']
query_example = '{} = SystemTable->{};'.format(capture_1, capture_2)
query_tree = weggli.parse_query(query_example)

source_path = '/home/example-weggli.c'
with open(source_path, 'r') as file:
    source = file.read()
    query_results = weggli.matches(query_tree, source, False)
    for query_result in query_results:
        display_result = weggli.display(query_result, source, True)
        for key in capture_key_list:
            captured_values[key].add(weggli.captured_value(query_result, key, source))
        
        print(display_result)
    print('CAPTURES:')
    for key in capture_key_list:
        print('{}: {}'.format(key, captured_values[key]))

This is the output for the example:

void f(void) {
pEVar2 = SystemTable->BootServices; # This line is marked in red, can't show this in the PR description
if (pEVar1 != (EFI_BOOT_SERVICES *)0x0)
  {
    gBS_5 = pEVar1;
    if (pEVar1->HandleProtocol != (EFI_HANDLE_PROTOCOL)0x0)
    {
      pEVar1->HandleProtocol = DC_FUN_180014976;
    }
  }

void g(void) {
  pEVar2 = SystemTable->BootServices; # This line is marked in red, can't show this in the PR description
  if (pEVar2 != (EFI_BOOT_SERVICES *)0x0)
  {
    gBS_5 = pEVar2;
    if (pEVar2->HandleProtocol != (EFI_HANDLE_PROTOCOL)0x0)
    {
      pEVar2->HandleProtocol = DC_FUN_180014976;
    }
  }

CAPTURES:
$capture1: {'pEVar2', 'pEVar1'}
$capture2: {'BootServices'}
$doesNotExist: {None}

With the variable that doesn't exist captured_value returns None.

This is the C file the example uses, example-weggli.c:

void f(void) {
  pEVar1 = SystemTable->BootServices;
  if (pEVar1 != (EFI_BOOT_SERVICES *)0x0)
  {
    gBS_5 = pEVar1;
    if (pEVar1->HandleProtocol != (EFI_HANDLE_PROTOCOL)0x0)
    {
      pEVar1->HandleProtocol = DC_FUN_180014976;
    }
  }
}

void g(void) {
  pEVar2 = SystemTable->BootServices;
  if (pEVar2 != (EFI_BOOT_SERVICES *)0x0)
  {
    gBS_5 = pEVar2;
    if (pEVar2->HandleProtocol != (EFI_HANDLE_PROTOCOL)0x0)
    {
      pEVar2->HandleProtocol = DC_FUN_180014976;
    }
  }
}

andrestirabo avatar Feb 05 '25 16:02 andrestirabo