ProgramLanguageDetector

Helpers & Utilities · AiDotNet.Evolution.Programs

Infers a program’s language and maps languages to file extensions, comment prefixes, and fence labels.

For Beginners

When a model hands back a block of code you often have to work out what language it is written in — to pick the right file extension, the right comment character, or the right sandbox. This class makes that guess by looking for telltale signs: #include means C or C++, fn main means Rust, SELECT ... FROM means SQL. It also answers the reverse questions, such as “what file extension does C# use?” and “does the label py mean Python?” (it does).

How It Works

The reference OpenEvolve implementation detects a language with six ordered regular expressions and returns a bare string, so public class Main is reported as Python because the Python rule tests ^class\s first, and C#, TypeScript, and Go have no rule at all. This detector scores every language in ProgramLanguage against weighted, mutually distinguishing signals and returns the highest scorer, resolving ties by enumeration order so the result is reproducible on every machine and every run.

Detection is purely lexical and performs no I/O, so it costs one pass over the source and never depends on the file system, the current culture, or an installed toolchain. The mapping helpers are the companion piece: they give the fence label to ask a model for, the comment prefix an evolve-block marker must use, and the file extension a sandbox should write, all from the same single source of truth.

Methods

Method Summary
ProgramLanguage Detect(string source, ProgramLanguage fallback) Infers the most likely language of a source snippet.
bool TryDetect(string source, ProgramLanguage language) Attempts to infer the language of a source snippet.
bool TryGetLanguageForFenceLabel(string label, ProgramLanguage language) Resolves a markdown fence label, including common aliases, to a language.
bool TryGetLanguageForFileExtension(string extension, ProgramLanguage language) Resolves a file extension, with or without its leading dot, to a language.
string GetFenceLabel(ProgramLanguage language) Returns the markdown fence label conventionally used for a language.
string GetFileExtension(ProgramLanguage language) Returns the conventional file extension for a language, including the leading dot.
string GetLineCommentPrefix(ProgramLanguage language) Returns the single-line comment prefix a language uses.