I'll create a robust C linter that checks for forbidden functions without using regex for function definitions. Here's a complete implementation:
#!/usr/bin/env python3
import json
import os
import sys
from typing import Set, List, Dict, Tuple
import fnmatch
class CLinter:
def __init__(self, config_file: str):
self.config = self._load_config(config_file)
self.allowed_funcs = set(self.config.get('allow_funcs', []))
self.excludes = set(self.config.get('excludes', []))
self.defined_funcs = set()
self.called_funcs = {} # {func_name: [(file, line, context)]}
def _load_config(self, config_file: str) -> dict:
"""Load configuration from JSON file"""
try:
with open(config_file, 'r') as f:
return json.load(f)
except Exception as e:
print(f"Error loading config file: {e}")
sys.exit(1)
def _should_exclude(self, path: str) -> bool:
"""Check if file/folder should be excluded"""
for exclude in self.excludes:
if os.path.isdir(exclude) and path.startswith(exclude):
return True
if path == exclude or path.endswith(f"/{exclude}"):
return True
return False
def _is_allowed_func(self, func_name: str) -> bool:
"""Check if function is in allowed list (supports wildcards)"""
for allowed in self.allowed_funcs:
if '*' in allowed:
if fnmatch.fnmatch(func_name, allowed):
return True
elif func_name == allowed:
return True
return False
def _tokenize(self, content: str) -> List[Tuple[str, int, int]]:
"""Simple tokenizer that preserves line numbers"""
tokens = []
current_token = ""
line_num = 1
col_num = 1
i = 0
while i < len(content):
char = content[i]
# Handle newlines
if char == '\n':
if current_token:
tokens.append((current_token, line_num, col_num - len(current_token)))
current_token = ""
line_num += 1
col_num = 1
i += 1
continue
# Handle string literals
if char in '"\'':
if current_token:
tokens.append((current_token, line_num, col_num - len(current_token)))
current_token = ""
quote = char
start_col = col_num
i += 1
col_num += 1
string_content = quote
while i < len(content) and content[i] != quote:
if content[i] == '\\' and i + 1 < len(content):
string_content += content[i:i+2]
i += 2
col_num += 2
else:
string_content += content[i]
if content[i] == '\n':
line_num += 1
col_num = 1
else:
col_num += 1
i += 1
if i < len(content):
string_content += content[i]
i += 1
col_num += 1
tokens.append((string_content, line_num, start_col))
continue
# Handle comments
if i + 1 < len(content):
if char == '/' and content[i + 1] == '/':
if current_token:
tokens.append((current_token, line_num, col_num - len(current_token)))
current_token = ""
# Skip to end of line
while i < len(content) and content[i] != '\n':
i += 1
col_num += 1
continue
elif char == '/' and content[i + 1] == '*':
if current_token:
tokens.append((current_token, line_num, col_num - len(current_token)))
current_token = ""
# Skip block comment
i += 2
col_num += 2
while i + 1 < len(content):
if content[i] == '*' and content[i + 1] == '/':
i += 2
col_num += 2
break
if content[i] == '\n':
line_num += 1
col_num = 1
else:
col_num += 1
i += 1
continue
# Handle operators and delimiters
if char in '(){}[];,.:->':
if current_token:
tokens.append((current_token, line_num, col_num - len(current_token)))
current_token = ""
tokens.append((char, line_num, col_num))
col_num += 1
i += 1
continue
# Handle whitespace
if char.isspace():
if current_token:
tokens.append((current_token, line_num, col_num - len(current_token)))
current_token = ""
col_num += 1
i += 1
continue
# Build token
current_token += char
col_num += 1
i += 1
if current_token:
tokens.append((current_token, line_num, col_num - len(current_token)))
return tokens
def _find_function_definitions(self, tokens: List[Tuple[str, int, int]]) -> Set[str]:
"""Find all function definitions in tokenized code"""
defined = set()
i = 0
while i < len(tokens):
# Look for pattern: type name ( ... ) {
if i + 4 < len(tokens):
# Check if we have a potential function definition
if (tokens[i + 2][0] == '(' and
self._is_identifier(tokens[i + 1][0])):
# Find matching closing parenthesis
paren_count = 1
j = i + 3
while j < len(tokens) and paren_count > 0:
if tokens[j][0] == '(':
paren_count += 1
elif tokens[j][0] == ')':
paren_count -= 1
j += 1
# Check if followed by {
if j < len(tokens):
k = j
while k < len(tokens) and tokens[k][0] in [';', '\n']:
k += 1
if k < len(tokens) and tokens[k][0] == '{':
# This is a function definition
func_name = tokens[i + 1][0]
defined.add(func_name)
i += 1
return defined
def _find_function_calls(self, tokens: List[Tuple[str, int, int]], filename: str) -> Dict[str, List[Tuple[str, int, str]]]:
"""Find all function calls in tokenized code"""
calls = {}
i = 0
while i < len(tokens):
# Look for pattern: identifier (
if i + 1 < len(tokens):
if (self._is_identifier(tokens[i][0]) and
tokens[i + 1][0] == '('):
func_name = tokens[i][0]
line_num = tokens[i][1]
# Get context (surrounding code)
context_start = max(0, i - 5)
context_end = min(len(tokens), i + 10)
context = ' '.join([t[0] for t in tokens[context_start:context_end]])
if func_name not in calls:
calls[func_name] = []
calls[func_name].append((filename, line_num, context))
i += 1
return calls
def _is_identifier(self, token: str) -> bool:
"""Check if token is a valid C identifier"""
if not token or not (token[0].isalpha() or token[0] == '_'):
return False
return all(c.isalnum() or c == '_' for c in token)
def _process_file(self, filepath: str):
"""Process a single C file"""
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
tokens = self._tokenize(content)
# Find defined functions
defined = self._find_function_definitions(tokens)
self.defined_funcs.update(defined)
# Find function calls
calls = self._find_function_calls(tokens, filepath)
for func_name, locations in calls.items():
if func_name not in self.called_funcs:
self.called_funcs[func_name] = []
self.called_funcs[func_name].extend(locations)
except Exception as e:
print(f"Error processing {filepath}: {e}")
def lint_project(self, project_path: str) -> List[Dict]:
"""Lint entire project and return violations"""
# First pass: collect all defined functions
for root, dirs, files in os.walk(project_path):
# Remove excluded directories from dirs to prevent walking into them
dirs[:] = [d for d in dirs if not self._should_exclude(os.path.join(root, d))]
for file in files:
if file.endswith('.c'):
filepath = os.path.join(root, file)
if not self._should_exclude(filepath):
self._process_file(filepath)
# Check for violations
violations = []
for func_name, locations in self.called_funcs.items():
# Skip if function is defined in project
if func_name in self.defined_funcs:
continue
# Skip if function is in allowed list
if self._is_allowed_func(func_name):
continue
# This is a violation
for filepath, line_num, context in locations:
violations.append({
'function': func_name,
'file': filepath,
'line': line_num,
'context': context.strip()
})
return violations
def print_report(self, violations: List[Dict]):
"""Print violation report"""
if not violations:
print("✓ No forbidden functions found!")
return
print(f"\n❌ Found {len(violations)} forbidden function call(s):\n")
# Group by function
by_function = {}
for v in violations:
func = v['function']
if func not in by_function:
by_function[func] = []
by_function[func].append(v)
for func, calls in sorted(by_function.items()):
print(f"Function '{func}' ({len(calls)} call(s)):")
for call in calls:
print(f" {call['file']}:{call['line']}")
print(f" Context: {call['context']}")
print()
def main():
if len(sys.argv) < 3:
print("Usage: python linter.py <config_file> <project_path>")
sys.exit(1)
config_file = sys.argv[1]
project_path = sys.argv[2]
if not os.path.exists(config_file):
print(f"Error: Config file '{config_file}' not found")
sys.exit(1)
if not os.path.exists(project_path):
print(f"Error: Project path '{project_path}' not found")
sys.exit(1)
linter = CLinter(config_file)
violations = linter.lint_project(project_path)
linter.print_report(violations)
# Exit with error code if violations found
sys.exit(1 if violations else 0)
if __name__ == "__main__":
main()
Here's also an example configuration file (config.json):
{
"allow_funcs": ["malloc", "free", "printf", "scanf", "fopen", "fclose", "hello_*", "test_*"],
"excludes": ["tests", "build", "vendor", "test.c"]
}
Key features of this linter:
-
Robust Parsing: Uses a custom tokenizer that properly handles:
- String literals (with escape sequences)
- Single-line comments (
//)
- Multi-line comments (
/* */)
- Preserves line numbers for accurate reporting
-
Function Definition Detection: Identifies function definitions by looking for the pattern type name(params) { without using regex.
-
Wildcard Support: Supports wildcards in allowed function names (e.g., hello_* allows hello_world, hello_user, etc.)
-
Exclusion Support: Can exclude entire directories or specific files from checking.
-
Detailed Reporting: Shows:
- Function name that violated the rules
- File and line number
- Context around the function call
-
Two-Pass Analysis:
- First pass: Collects all function definitions in the project
- Second pass: Checks all function calls against allowed list and defined functions
Usage:
python linter.py config.json /path/to/c/project
The linter will exit with code 0 if no violations are found, or 1 if violations are detected, making it suitable for CI/CD pipelines.