summaryrefslogtreecommitdiff
path: root/Compiler/Preprocessor.cs
diff options
context:
space:
mode:
authorMelodi <62381002+Melodi17@users.noreply.github.com>2025-08-28 14:44:51 +1000
committerMelodi <62381002+Melodi17@users.noreply.github.com>2025-08-28 14:44:51 +1000
commitcf7e621c104cb4aea801392585d2dcc9335bc013 (patch)
treeee4aef401c399995968afe217d06557587707c51 /Compiler/Preprocessor.cs
parent7f96fc5e7f412a66d460dcaa82bbdbcaea08f360 (diff)
added preprocessor (wip)
Diffstat (limited to 'Compiler/Preprocessor.cs')
-rw-r--r--Compiler/Preprocessor.cs59
1 files changed, 59 insertions, 0 deletions
diff --git a/Compiler/Preprocessor.cs b/Compiler/Preprocessor.cs
new file mode 100644
index 0000000..01c14ab
--- /dev/null
+++ b/Compiler/Preprocessor.cs
@@ -0,0 +1,59 @@
+namespace Q1.Compiler;
+
+using System.Text.RegularExpressions;
+
+public static class Preprocessor
+{
+ private static readonly Dictionary<string, string> Defines = new();
+
+ public static string Process(string filePath)
+ {
+ List<string> lines = [];
+ ProcessFile(filePath, lines, []);
+ return string.Join(Environment.NewLine, lines);
+ }
+
+ private static void ProcessFile(string filePath, List<string> output, HashSet<string> includeGuard)
+ {
+ if (includeGuard.Contains(Path.GetFullPath(filePath)))
+ return; // prevent recursive includes
+
+ includeGuard.Add(Path.GetFullPath(filePath));
+
+ foreach (string rawLine in File.ReadAllLines(filePath))
+ {
+ string line = rawLine.Trim();
+
+ if (line.StartsWith("#include"))
+ {
+ // simple format: #include "file"
+ Match match = Regex.Match(line, "#include\\s+\"([^\"]+)\"");
+ if (match.Success)
+ {
+ string includePath = Path.Combine(Path.GetDirectoryName(filePath)!, match.Groups[1].Value);
+ ProcessFile(includePath, output, includeGuard);
+ }
+ continue;
+ }
+ else if (line.StartsWith("#define"))
+ {
+ // simple format: #define NAME VALUE
+ Match match = Regex.Match(line, "#define\\s+(\\w+)\\s+(.*)");
+ if (match.Success)
+ Defines[match.Groups[1].Value] = match.Groups[2].Value;
+ continue;
+ }
+ else if (line.StartsWith("#load"))
+ {
+ output.Add(line.Replace("#load", "#.include"));
+ continue;
+ }
+
+ // expand macros
+ foreach (KeyValuePair<string, string> kvp in Defines)
+ line = line.Replace(kvp.Key, kvp.Value);
+
+ output.Add(line);
+ }
+ }
+} \ No newline at end of file