Try to determine the programming language of a code snippet using simple heuristics. Args: code: The code snippet string. Returns: A string representing the detected language (e.g., "python") or "unknown".
(code: str)
| 210 | |
| 211 | |
| 212 | def extract_code_language(code: str) -> str: |
| 213 | """ |
| 214 | Try to determine the programming language of a code snippet using simple heuristics. |
| 215 | |
| 216 | Args: |
| 217 | code: The code snippet string. |
| 218 | |
| 219 | Returns: |
| 220 | A string representing the detected language (e.g., "python") or "unknown". |
| 221 | """ |
| 222 | # Look for common language-specific keywords or patterns at the start of lines |
| 223 | if re.search(r"^(import|from|def|class)\s", code, re.MULTILINE): |
| 224 | return "python" |
| 225 | elif re.search(r"^(package|import java|public class)", code, re.MULTILINE): |
| 226 | return "java" |
| 227 | elif re.search(r"^(#include|int main|void main)", code, re.MULTILINE): |
| 228 | return "cpp" |
| 229 | elif re.search(r"^(function|var|let|const|console\.log)", code, re.MULTILINE): |
| 230 | return "javascript" |
| 231 | elif re.search(r"^(module|fn|let mut|impl)", code, re.MULTILINE): |
| 232 | return "rust" |
| 233 | elif re.search(r"^(SELECT|CREATE TABLE|INSERT INTO)", code, re.MULTILINE): |
| 234 | return "sql" |
| 235 | |
| 236 | # If no specific patterns are matched, return "unknown" |
| 237 | return "unknown" |