",
"using namespace std;",
"const int M = 1e9 + 7;",
"#define endl '\\n'",
"#define int long long",
"",
"signed main()",
"{",
" ios::sync_with_stdio(0);",
" cin.tie(0);",
" cout.tie(0);",
" int t = 1;",
" cin >> t;",
" for (int tt = 0; tt < t; tt++)",
" {",
" $1",
" }",
" return 0;",
"}"
],
"description": "Competitive Programming Template"
},
"competitive_2": {
"prefix": "competitive_2",
"body": [
"#include Use pycparser Library to extract function, structures, and other code elements from .c file. Only extract functions, structures, etc present in current file and not the ones present in #include statement. Finally print these elements. Use python for writing code. from tree_sitter import Language, Parserimport os def extract_functions(source_code): """ Parses the C source code and extracts the names of all functions defined. """ tree = parser.parse(bytes(source_code, "utf8")) root_node = tree.root_node
# Function to recursively traverse the syntax tree and extract function names def traverse(node): functions = [] if node.type == 'function_definition': # The function name is within the 'declarator' child node declarator = node.child_by_field_name('declarator') if declarator: # Extract the identifier (function name) identifier = declarator.descendant_of_type('identifier') if identifier: functions.append(identifier.text.decode('utf-8')) # Traverse child nodes for child in node.children: functions.extend(traverse(child)) return functions
return traverse(root_node) if not os.path.isfile(C_SOURCE_FILE): print(f"Error: File '{C_SOURCE_FILE}' does not exist.")else: with open(C_SOURCE_FILE, 'r', encoding='utf-8') as f: code = f.read()
# Extract and print function names functions = extract_functions(code) if functions: print("Functions found in the source file:") for func in functions: print(f"- {func}") else: print("No functions found in the source file."){
"competitive programming template": {
"prefix": "competitive",
"body": [
"#include <bits/stdc++.h>",
"using namespace std;",
"const int M = 1e9 + 7;",
"#define endl '\\\\n'",
"#define int long long",
"",
"signed main()",
"{",
" ios::sync_with_stdio(0);",
" cin.tie(0);",
" cout.tie(0);",
" int t = 1;",
" cin >> t;",
" for (int tt = 0; tt < t; tt++)",
" {",
" $1",
" }",
" return 0;",
"}"
],
"description": "Competitive Programming Template"
},
"competitive_2": {
"prefix": "competitive_2",
"body": [
"#include <bits/stdc++.h>",
"",
"using namespace std;",
"",
"#define frr(i,a,b) for(int i=a;i<=b;i++)",
"#define test(t) int t; cin >> t; frr(tno,1,t)",
"#define endl '\\\\n'",
"#define int long long",
"// __builtin_popcountll(x) number of 1s",
"//__builtin_clzll(x): number of leading 0s (64 bit representation for unsigned long long)",
"//64-__builtin_clzll(x): number of binary digits",
"//__builtin_ctzll(x):number of trailing zeroes",
"//__lg(x) position of msb, 0-indexed",
"//for square root use sqrtl()",
"",
"const int N=1000000007;",
"const int mod=1000000007;",
"const int INF=1000000000000000;",
"const int M=1000005;",
"",
"int binPow(int a,int b)",
"{",
" a=a%N;",
" if (b == 0)return 1;",
" if (b == 1)return a;",
" int ret = binPow(a,b/2);",
" if (b%2 == 0)return (ret%N * ret%N)%N;",
" return ((ret%N * ret%N)%N * a)%N;",
"}",
"int inv(int a)",
"{",
" return (binPow(a,N - 2)%N + N)%N;",
"}",
"int max(int a,int b,int c)",
"{",
" return max(a,max(b,c));",
"}",
"int max(int a,int b,int c,int d)",
"{",
" return max(max(a,b),max(c,d));",
"}",
"bool isPrime(int n)",
"{",
" int i;",
" for(i = 2;i*i<=n;i++)",
" {",
" if(n%i == 0)return false;",
" }",
" return true;",
"}",
"int mod_mul(int a, int b) {a = a % N; b = b % N; return (((a * b) %N) + N) % N;}",
"int mod_add(int a, int b) {a = a % N; b = b % N; return (((a + b) % N) + N) % N;}",
"int mod_sub(int a,int b){a=a%N;b=b%N;return (a-b+2*N)%N;}",
"int mod_add(int a, int b,int c,int d) {a = a % N; b = b % N; c=c%N;d=d%N;int x=mod_add(a,b);int y=mod_add(c,d);return mod_add(x,y);}",
"int mod_add(int a,int b,int c){a=a%N;b=b%N;c=c%N;int x=mod_add(a,b);int y=mod_add(x,c);return y;}",
"",
"// vector<int>fact(M+1,1);",
"// vector<int>ifact(M+1,1);",
"// int make_factorial()",
"// {",
"// for(int i=2;i<=M;i++)",
"// {",
"// fact[i]=mod_mul(fact[i-1],i);",
"// }",
"// ifact[M]=inv(fact[M]);",
"// for (int i=M-1;i>=1;i--)",
"// {",
"// ifact[i]=mod_mul(i+1,ifact[i+1]);",
"// }",
"// return 0;",
"// }",
"// int x=make_factorial();",
"// int binom(int $n,int $r)",
"// {",
"// if($n<$r || $n<0 || $r<0) return 0;",
"// //if($n>Fact_Length) { cout<<\\"Error\\"<<endl; return; }",
"// int $ans=(fact[$n]*(ifact[$r]))%N;",
"// $ans=($ans*(ifact[$n-$r]))%N;",
"// return $ans;",
"// }",
"",
"// ------------------------------------------------------",
"// const int P = 200020;",
"// vector<vector<int>> divisor(P);",
"// int Sieve(){",
"// for(int i=1; i<P; i++){",
"// for(int j=i; j<P; j+=i){",
"// divisor[j].push_back(i);",
"// }",
"// }",
"// return 0;",
"// }",
"// int y = Sieve();",
"",
"void inp(vector<int>&a){",
" int n=a.size();",
" for(int i=0;i<n;i++)cin>>a[i];",
"}",
"void inp(vector<vector<int>>&a){",
" int n=a.size();",
" int m=a[0].size();",
" for(int i=0;i<n;i++){",
" for(int j=0;j<m;j++)cin>>a[i][j];",
" }",
"}",
"void print(vector<int>&a){",
" for(auto &x:a)cout<<x<<\\" \\";",
" cout<<endl;",
"}",
"void print(vector<vector<int>>&a){",
" int n=a.size();",
" int m=a[0].size();",
" for(int i=0;i<n;i++){",
" for(int j=0;j<m;j++)cout<<a[i][j]<<\\" \\";",
" cout<<endl;",
" }",
"}",
"signed main()",
"{",
" ios_base::sync_with_stdio(false);",
" cin.tie(NULL); cout.tie(NULL);",
" int t = 1;",
" cin >> t;",
" for (int tt = 0; tt < t; tt++)",
" {",
" $1",
" }",
" return 0;",
"}"
],
"description": "Competitive programming template"
},
"leetcode": {
"prefix": "leetcode",
"body": [
"#include <bits/stdc++.h>",
"using namespace std;",
"const int M = 1e9 + 7;",
"#define endl '\\\\n'",
"#define int long long",
"",
"class Solution {",
"public:",
"$1",
"};",
"",
"signed main()",
"{",
" ios::sync_with_stdio(0);",
" cin.tie(0);",
" cout.tie(0);",
" Solution sol;",
" ",
" return 0;",
"}"
],
"description": "C++ template for LeetCode problems"
}
}
from pycparser import parse_file, c_ast, c_generatorimport os
# Define a visitor class to traverse the AST and find function definitionsclass FuncDefVisitor(c_ast.NodeVisitor): def __init__(self): self.functions = []
def visit_FuncDef(self, node): """ Called for each function definition in the AST. Extracts the function's name, return type, parameters, and body. """ func_decl = node.decl func_name = func_decl.name return_type = self._get_type(func_decl.type) params = self._get_params(func_decl.type.args) body = self._get_body(node.body) self.functions.append({ 'name': func_name, 'return_type': return_type, 'params': params, 'body': body })
def _get_type(self, type_decl): """ Recursively retrieves the return type of the function as a string. Handles pointers and complex type declarations. """ if isinstance(type_decl, c_ast.TypeDecl): type_str = ' '.join(type_decl.type.names) return type_str elif isinstance(type_decl, c_ast.PtrDecl): return self._get_type(type_decl.type) + ' *' elif isinstance(type_decl, c_ast.FuncDecl): return self._get_type(type_decl.type) else: return ''
def _get_params(self, param_list): """ Retrieves the function's parameters as a list of dictionaries, each containing the parameter's name and type. """ params = [] if param_list is None: return params # Function has no parameters (i.e., void) for param in param_list.params: param_type = self._get_type(param.type) param_name = param.name if param.name else '' params.append({ 'name': param_name, 'type': param_type }) return params
def _get_body(self, body): """ Converts the function body AST back to C code for readability. """ generator = c_generator.CGenerator() return generator.visit(body)
def extract_functions_from_c_file(c_file_path): """ Parses the given C file and extracts all function definitions. :param c_file_path: Path to the C source file. :return: List of dictionaries, each representing a function definition. """ if not os.path.isfile(c_file_path): raise FileNotFoundError(f"The file {c_file_path} does not exist.")
# Parse the C file with preprocessing ast = parse_file( c_file_path, use_cpp=True, cpp_path='cpp', # Ensure 'cpp' is in your system's PATH; on Windows, use appropriate CPP path cpp_args=['-Iutils/fake_libc_include'] )
# Initialize the visitor and traverse the AST visitor = FuncDefVisitor() visitor.visit(ast)
return visitor.functions
if __name__ == "__main__": # Replace 'your_file.c' with the path to your C source file c_file = 'your_file.c' try: functions = extract_functions_from_c_file(c_file) # Display extracted function information for func in functions: print(f"Function Name: {func['name']}") print(f"Return Type: {func['return_type']}") print("Parameters:") if func['params']: for param in func['params']: print(f" - {param['type']} {param['name']}") else: print(" - void") print("Function Body:") print(func['body']) print("-" * 40) except Exception as e: print(f"An error occurred: {e}")
import pycparserfrom pycparser import c_ast, parse_file
class FunctionVisitor(c_ast.NodeVisitor): def visit_FuncDef(self, node): func_name = node.decl.name params = [] if isinstance(node.decl.type, c_ast.FuncDecl): if node.decl.type.args: for param in node.decl.type.args.params: if isinstance(param.type, c_ast.TypeDecl): param_name = param.name param_type = param.type.type.names[0] # Get the type name params.append(f'{param_type} {param_name}') elif isinstance(param.type, c_ast.PtrDecl): param_name = param.type.type.declname param_type = ' '.join(param.type.type.type.names) + '*' params.append(f'{param_type} {param_name}') else: params.append('unknown') params_str = ', '.join(params) print(f'Function Name: {func_name}') print(f'Parameters: ({params_str})') print('---') self.generic_visit(node)
def extract_functions_from_c_file(filename): ast = parse_file(filename, use_cpp=True) visitor = FunctionVisitor() visitor.visit(ast)
# Example usage:c_file = 'example.c' # Replace with your C fileextract_functions_from_c_file(c_file)
import pycparserfrom pycparser import c_parser, c_ast, parse_file
class CodeVisitor(c_ast.NodeVisitor): def __init__(self): self.functions = [] self.structures = [] self.unions = [] self.enums = []
def visit_FuncDef(self, node): # Extract function names func_name = node.decl.name self.functions.append(func_name) self.generic_visit(node)
def visit_Struct(self, node): # Extract structure names struct_name = node.name if struct_name: # Only add named structures self.structures.append(struct_name) self.generic_visit(node)
def visit_Union(self, node): # Extract union names union_name = node.name if union_name: # Only add named unions self.unions.append(union_name) self.generic_visit(node)
def visit_Enum(self, node): # Extract enum names enum_name = node.name if enum_name: # Only add named enums self.enums.append(enum_name) self.generic_visit(node)
def extract_code_elements_from_c_file(file_path): parser = c_parser.CParser()
# Parse the file ast = parse_file(file_path, use_cpp=True)
# Visit the AST nodes to collect functions, structures, etc. visitor = CodeVisitor() visitor.visit(ast)
return visitor
# Example usagefile_path = 'your_c_file.c'code_elements = extract_code_elements_from_c_file(file_path)
# Print the extracted elementsprint("Functions:")for func in code_elements.functions: print(f" - {func}")
print("\\nStructures:")for struct in code_elements.structures: print(f" - {struct}")
print("\\nUnions:")for union in code_elements.unions: print(f" - {union}")
print("\\nEnums:")for enum in code_elements.enums: print(f" - {enum}")import pycparser
from pycparser import c_parser, c_ast, parse_file
class CodeVisitor(c_ast.NodeVisitor): def __init__(self): self.functions = [] self.structures = [] self.unions = [] self.enums = []
def visit_FuncDef(self, node): # Extract function names func_name = node.decl.name self.functions.append(func_name) self.generic_visit(node)
def visit_Struct(self, node): # Extract structure names struct_name = node.name if struct_name: # Only add named structures self.structures.append(struct_name) self.generic_visit(node)
def visit_Union(self, node): # Extract union names union_name = node.name if union_name: # Only add named unions self.unions.append(union_name) self.generic_visit(node)
def visit_Enum(self, node): # Extract enum names enum_name = node.name if enum_name: # Only add named enums self.enums.append(enum_name) self.generic_visit(node)
def extract_code_elements_from_c_file(file_path): parser = c_parser.CParser()
# Parse the file ast = parse_file(file_path, use_cpp=True)
# Visit the AST nodes to collect functions, structures, etc. visitor = CodeVisitor() visitor.visit(ast)
return visitor
# Example usagefile_path = 'your_c_file.c'code_elements = extract_code_elements_from_c_file(file_path)
# Print the extracted elementsprint("Functions:")for func in code_elements.functions: print(f" - {func}")
print("\\nStructures:")for struct in code_elements.structures: print(f" - {struct}")
print("\\nUnions:")for union in code_elements.unions: print(f" - {union}")
print("\\nEnums:")for enum in code_elements.enums: print(f" - {enum}")
from tree_sitter import Language, Parserfrom tree_sitter_languages import get_language
# Load the C language grammarC_LANGUAGE = get_language('c')
parser = Parser()parser.set_language(C_LANGUAGE)
def extract_functions(source_code): tree = parser.parse(bytes(source_code, "utf8")) root_node = tree.root_node function_names = [] for node in root_node.walk(): if node.type == 'function_definition': function_name = node.child_by_field_name('declarator').text function_names.append(function_name.decode('utf-8')) return function_names
# Read the .c filewith open('example.c', 'r') as f: code = f.read()
# Extract functionsfunctions = extract_functions(code)for func in functions: print(func)
Locate the path to the pre-built C grammar shared library# The 'tree_sitter_c' package installs the shared library in its directoryfrom tree_sitter_c import LIB_NAME, LIB_PATH
Build the path to the shared libraryC_LANGUAGE = Language(LIB_PATH, 'c')
Initialize the parser and set the languageparser = Parser()parser.set_language(C_LANGUAGE)
Path to your C source fileC_SOURCE_FILE = 'example.c' # Replace with your actual file path
from tree_sitter import Language, Parser
import os
# Locate the path to the pre-built C grammar shared library
# The 'tree_sitter_c' package installs the shared library in its directory
from tree_sitter_c import LIB_NAME, LIB_PATH
# Build the path to the shared library
C_LANGUAGE = Language(LIB_PATH, 'c')
# Initialize the parser and set the language
parser = Parser()
parser.set_language(C_LANGUAGE)
def extract_functions(source_code):
"""
Parses the C source code and extracts the names of all functions defined.
"""
tree = parser.parse(bytes(source_code, "utf8"))
root_node = tree.root_node
# Function to recursively traverse the syntax tree and extract function names
def traverse(node):
functions = []
if node.type == 'function_definition':
# The function name is within the 'declarator' child node
declarator = node.child_by_field_name('declarator')
if declarator:
# Extract the identifier (function name)
identifier = declarator.descendant_of_type('identifier')
if identifier:
functions.append(identifier.text.decode('utf-8'))
# Traverse child nodes
for child in node.children:
functions.extend(traverse(child))
return functions
return traverse(root_node)
# Path to your C source file
C_SOURCE_FILE = 'example.c' # Replace with your actual file path
if not os.path.isfile(C_SOURCE_FILE):
print(f"Error: File '{C_SOURCE_FILE}' does not exist.")
else:
with open(C_SOURCE_FILE, 'r', encoding='utf-8') as f:
code = f.read()
# Extract and print function names
functions = extract_functions(code)
if functions:
print("Functions found in the source file:")
for func in functions:
print(f"- {func}")
else:
print("No functions found in the source file.")
from tree_sitter import Language, Parserfrom tree_sitter_languages import get_language
# Load the C language grammarC_LANGUAGE = get_language('c')
parser = Parser()parser.set_language(C_LANGUAGE)
def extract_functions(source_code): tree = parser.parse(bytes(source_code, "utf8")) root_node = tree.root_node function_names = [] for node in root_node.walk(): if node.type == 'function_definition': function_name = node.child_by_field_name('declarator').text function_names.append(function_name.decode('utf-8')) return function_names
# Read the .c filewith open('example.c', 'r') as f: code = f.read()
# Extract functionsfunctions = extract_functions(code)for func in functions: print(func)