Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Get object's raw source #21

Open
lpinilla opened this issue Dec 17, 2021 · 2 comments
Open

Feature Request: Get object's raw source #21

lpinilla opened this issue Dec 17, 2021 · 2 comments

Comments

@lpinilla
Copy link

Hi,

How are you? Thanks of all, thanks for doing the port of the tool, I was thinking of doing it myself and I found someone else did it 😄

I was wondering if there was a way to get the raw source of an objects, let's say a contract or function.

I was thinking in something like:

sourceUnitObject = parser.objectify(sourceUnit)
raw_text = sourceUnitObject.contracts['MyContract'].raw
print(raw_text)
>>'contract MyContract { ..'

Thanks!

@seyyedaliayati
Copy link

This is indeed a very useful feature. I started working on it.

@seyyedaliayati
Copy link

seyyedaliayati commented May 16, 2023

This is indeed a very useful feature. I started working on it.

Here is my solution:

  1. Set loc=True in parse function.
  2. Use the following helper function:
def get_content_between_positions(file_path, positions):
    start_line = positions['start']['line']
    start_column = positions['start']['column']
    end_line = positions['end']['line']
    end_column = positions['end']['column']

    with open(file_path, 'r') as file:
        lines = file.readlines()

    content = ''
    for line_number, line in enumerate(lines, 1):
        if start_line <= line_number <= end_line:
            if line_number == start_line:
                content += line[start_column:]
            elif line_number == end_line:
                content += line[:end_column+1]
            else:
                content += line

    return content
  1. use ._node.loc. to access the location dictionary.
from solidity_parser import parser, objectify, visit
source_unit = parser.parse_file(sample_test_file, loc=True)
source_unit_obj = objectify(source_unit)

contracts = source_unit_obj.contracts

for contract in contracts.values():
    print(get_content_between_positions(sample_test_file, contract.functions['<function-name>']._node.loc))

The output will be the context of the function! Enjoy it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants