import ast
import json
import os
import re
import shutil
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import Process, cpu_count


def is_compilable(code):
    try:
        ast.parse(code)
        return True
    except SyntaxError:
        return False
    except Exception as e:
        print("Error in is_compilable: ",e)
        return False


from tree_sitter_languages import get_language, get_parser

language = get_language('python')
global_parser = get_parser('python')

QUERY = language.query("""
(function_definition name: (identifier) @fn-name)
""")


def node_to_string(src: bytes, node):
    return src[node.start_byte:node.end_byte].decode("utf8")

def get_fn_name(code, parser=global_parser):
    src = bytes(code, "utf8")
    tree = parser.parse(src)
    node = tree.root_node
    for cap, typ in QUERY.captures(node):
        if typ == "fn-name":
            return node_to_string(src, cap)
    return None
