Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

write me a linter to check forbidden function for c program in robust way, all defined…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-opus-4-20250514’s answer.
  1. User

    write me a linter to check forbidden function for c program in robust way, all defined function in project is allowed { "allow_funcs": ["malloc", "printf", "hello_*"] "excludes": ["folder", "file.c"] }

  2. Assistant

    Certainly! Below is a robust Python linter script that checks for forbidden function calls in a C project. It allows you to specify:

    • Allowed functions (with support for wildcards, e.g., hello_*)
    • Excluded files/folders (which will be skipped)

    This script recursively scans .c and .h files, parses function calls, and reports any usage of functions not in the allowed list.


    c_func_linter.py

    import os
    import re
    import fnmatch
    import argparse
    import json
    
    def load_config(config_path):
        with open(config_path, 'r') as f:
            return json.load(f)
    
    def is_excluded(path, excludes):
        for pattern in excludes:
            if os.path.isdir(path) and os.path.basename(path) == pattern:
                return True
            if fnmatch.fnmatch(os.path.basename(path), pattern):
                return True
            if os.path.abspath(path).startswith(os.path.abspath(pattern)):
                return True
        return False
    
    def get_c_files(root, excludes):
        c_files = []
        for dirpath, dirnames, filenames in os.walk(root):
            # Exclude directories
            dirnames[:] = [d for d in dirnames if not is_excluded(os.path.join(dirpath, d), excludes)]
            for filename in filenames:
                if filename.endswith(('.c', '.h')):
                    file_path = os.path.join(dirpath, filename)
                    if not is_excluded(file_path, excludes):
                        c_files.append(file_path)
        return c_files
    
    def get_defined_functions(file_content):
        # Matches function definitions (not declarations)
        func_def_pattern = re.compile(r'^\s*[\w\*\s]+?\s+(\w+)\s*\([^;]*\)\s*\{', re.MULTILINE)
        return set(func_def_pattern.findall(file_content))
    
    def get_function_calls(file_content):
        # Matches function calls (not definitions or declarations)
        # Excludes function definitions by negative lookahead for '{' after ')'
        call_pattern = re.compile(r'(?<![\w])(\w+)\s*\(', re.MULTILINE)
        return set(call_pattern.findall(file_content))
    
    def is_allowed(func, allow_patterns):
        for pattern in allow_patterns:
            if fnmatch.fnmatch(func, pattern):
                return True
        return False
    
    def main():
        parser = argparse.ArgumentParser(description="C Forbidden Function Linter")
        parser.add_argument('--config', type=str, required=True, help='Path to config JSON')
        parser.add_argument('--root', type=str, default='.', help='Root directory of the project')
        args = parser.parse_args()
    
        config = load_config(args.config)
        allow_funcs = config.get('allow_funcs', [])
        excludes = config.get('excludes', [])
    
        # Collect all defined functions in the project
        defined_funcs = set()
        c_files = get_c_files(args.root, excludes)
        for file_path in c_files:
            with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
                defined_funcs.update(get_defined_functions(content))
    
        # Add all defined functions to allowed list
        allow_patterns = allow_funcs + list(defined_funcs)
    
        # Now check for forbidden function calls
        forbidden_calls = []
        for file_path in c_files:
            with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
                calls = get_function_calls(content)
                for call in calls:
                    if not is_allowed(call, allow_patterns):
                        forbidden_calls.append((file_path, call))
    
        if forbidden_calls:
            print("Forbidden function calls found:")
            for file_path, func in forbidden_calls:
                print(f"{file_path}: {func}")
            exit(1)
        else:
            print("No forbidden function calls found.")
    
    if __name__ == "__main__":
        main()
    

    Example config.json

    {
        "allow_funcs": ["malloc", "printf", "hello_*"],
        "excludes": ["folder", "file.c"]
    }
    

    Usage

    python c_func_linter.py --config config.json --root path/to/your/project
    

    Notes:

    • The linter supports wildcards in allowed functions (e.g., hello_*).
    • It automatically allows all functions defined in your project.
    • It skips files and folders listed in excludes.
    • It only checks for function calls, not macro invocations or function pointers.
    • For more advanced parsing (e.g., handling macros, function pointers), consider using a C parser library like pycparser.

    Let me know if you need further customization!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.