Untitled

mail@pastecode.io avatar
unknown
python
a year ago
2.6 kB
0
Indexable
Never
import tree_sitter

# Load the C++ language grammar
language = tree_sitter.Language("path/to/cpp.so")

# Create a new parser and set the language
parser = tree_sitter.Parser()
parser.set_language(language)

def extract_function_metadata(code: str):
    # Parse the code to produce a syntax tree
    tree = parser.parse(code.encode('utf-8'))
    
    # Iterate over the child nodes of the root node
    for child in tree.root_node.children:
        # Check if the child node represents a function definition
        if child.type == "function_definition":
            function_node = child

            # Extract the return type
            return_type = ""
            for return_type_node in function_node.children:
                if return_type_node.type == "declaration_specifier":
                    return_type = return_type_node.text
            
            # Extract the function name
            function_name = function_node.children[-2].text

            # Extract the function parameters
            parameters = []
            for parameter_node in function_node.children[-1].children:
                parameter_type = ""
                for parameter_type_node in parameter_node.children:
                    if parameter_type_node.type == "declaration_specifier":
                        parameter_type = parameter_type_node.text
                parameter_name = parameter_node.children[-1].text
                parameters.append((parameter_type, parameter_name))

            # Return the extracted metadata
            return return_type, function_name, parameters

# Example usage
code = "static QRinput_List *QRinput_List_newEntry(QRencodeMode mode, int size, const unsigned char *data)\n{\n\tQRinput_List *entry;\n\n\t// Check if QRinput_check mode size data.\n\tif(QRinput_check(mode, size, data)) {\n\t\terrno = EINVAL;\n\t\treturn NULL;\n\t}\n\n\tentry = (QRinput_List *)malloc(sizeof(QRinput_List));\n\t// Returns the entry or NULL if there is no entry.\n\tif(entry == NULL) return NULL;\n\n\tentry->mode = mode;\n\tentry->size = size;\n\tentry->data = (unsigned char *)malloc(size);\n\t// Free the entry and free the memory used by this entry.\n\tif(entry->data == NULL) {\n\t\tfree(entry);\n\t\treturn NULL;\n\t}\n\tmemcpy(entry->data, data, size);\n\tentry->bstream = NULL;\n\tentry->next = NULL;\n\n\treturn entry;\n}"
return_type, function_name, parameters = extract_function_metadata(code)
print("Return Type:", return_type)
print("Function Name:", function_name)
print("Parameters: