|
| 1 | +using System.Reflection; |
| 2 | +using System.IO; |
| 3 | + |
| 4 | +using Antlr4.Runtime; |
| 5 | + |
| 6 | +using Decaf.Frontend; |
| 7 | +using Decaf.MiddleEnd.TypeChecker; |
| 8 | +using Decaf.MiddleEnd.Optimizations; |
| 9 | +using Decaf.MiddleEnd; |
| 10 | +using Decaf.Backend; |
| 11 | + |
| 12 | +using ParseTree = Decaf.IR.ParseTree; |
| 13 | +using TypedTree = Decaf.IR.TypedTree; |
| 14 | +using AnfTree = Decaf.IR.AnfTree; |
| 15 | +using Wasm = Decaf.WasmBuilder; |
| 16 | + |
| 17 | +namespace Decaf.Compiler { |
| 18 | + public static class Compiler { |
| 19 | + // --- Generic --- |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// This method bundles the runtime code into the user program. |
| 23 | + /// |
| 24 | + /// This is done in a rather naive way we simply take the runtime code, and then append the parsed runtime modules to the |
| 25 | + /// user-defined modules. |
| 26 | + /// This is not the most efficient way to do this, but it is simple and works for our purposes. |
| 27 | + /// One benefit of appending the parsed runtime modules over doing a string append is that we get better error reporting and handling |
| 28 | + /// as locations are right and malformed runtime code will be caught while parsing the runtime, |
| 29 | + /// so user errors are scoped to their source. |
| 30 | + /// </summary> |
| 31 | + /// <param name="program">The program to bundle the runtime code into.</param> |
| 32 | + /// <returns>The bundled program.</returns> |
| 33 | + private static ParseTree.ProgramNode BundleRuntime(ParseTree.ProgramNode program) { |
| 34 | + // Get the embedded runtime resource (This is basically a hack to include the runtime code in the compiled assembly) |
| 35 | + var assembly = Assembly.GetExecutingAssembly(); |
| 36 | + using var stream = assembly.GetManifestResourceStream("decaf.Runtime.decaf"); |
| 37 | + using var reader = new BinaryReader(stream); |
| 38 | + byte[] data = reader.ReadBytes((int)stream.Length); |
| 39 | + var runtimeSource = System.Text.Encoding.UTF8.GetString(data); |
| 40 | + // Process with the front end |
| 41 | + var runtimeProgram = FrontEnd(runtimeSource, "$internal$/Runtime.decaf", false); |
| 42 | + // Bundle the runtime into the program |
| 43 | + return new ParseTree.ProgramNode( |
| 44 | + program.Position, |
| 45 | + // Put the runtime modules before the user-defined modules to ensure that the runtime modules are |
| 46 | + // available to the user-defined modules |
| 47 | + [.. runtimeProgram.Modules, .. program.Modules] |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + // --- Entry points --- |
| 52 | + |
| 53 | + /// <summary> |
| 54 | + /// This is the main entry point for the compiler, it takes the raw source code and runs the |
| 55 | + /// entire compilation pipeline on it, returning the compiled wasm module. |
| 56 | + /// |
| 57 | + /// This method runs the entire compilation pipeline on the given source code, this includes: |
| 58 | + /// - Front end (Lexing, Parsing, Semantic Analysis) |
| 59 | + /// - Middle end (Type checking, Lowering to ANF, Optimizations) |
| 60 | + /// - Back end (Lowering to wasm) |
| 61 | + /// </summary> |
| 62 | + /// <param name="source">The raw source code to compile.</param> |
| 63 | + /// <param name="inputFileName">The name of the file that contained the source code.</param> |
| 64 | + /// <returns>The compiled wasm module.</returns> |
| 65 | +#nullable enable |
| 66 | + public static Wasm.WasmModule CompileString(string source, string? inputFileName) { |
| 67 | + // Front end |
| 68 | + var frontEndProgram = FrontEnd(source, inputFileName); |
| 69 | + // Middle end |
| 70 | + var middleEndProgram = MiddleEnd(frontEndProgram); |
| 71 | + // Back end |
| 72 | + var wasmModule = Backend(middleEndProgram); |
| 73 | + // Return the compiled wasm module |
| 74 | + return wasmModule; |
| 75 | + } |
| 76 | +#nullable restore |
| 77 | + // --- Front end --- |
| 78 | + |
| 79 | + /// <summary> |
| 80 | + /// This method runs the entire front end pipeline on the given source code, this includes: |
| 81 | + /// - Lexing |
| 82 | + /// - Parsing |
| 83 | + /// - Bundling the runtime code |
| 84 | + /// - Scope checking |
| 85 | + /// - Semantic checking |
| 86 | + /// </summary> |
| 87 | + /// <param name="source">The raw source code to compile.</param> |
| 88 | + /// <param name="inputFileName">The name of the file that contained the source code.</param> |
| 89 | + /// <returns>The program after front end processing.</returns> |
| 90 | +#nullable enable |
| 91 | + public static ParseTree.ProgramNode FrontEnd(string source, string? inputFileName, bool bundleRuntime = true) { |
| 92 | + // Lex the program |
| 93 | + var lexer = LexSource(source, inputFileName); |
| 94 | + // Parse the program |
| 95 | + var tokenStream = new CommonTokenStream(lexer); |
| 96 | + var program = ParseSource(tokenStream); |
| 97 | + // Bundle the runtime |
| 98 | + var bundledProgram = bundleRuntime ? BundleRuntime(program) : program; |
| 99 | + // Check semantics - NOTE: we can't do semantic checks before bundling |
| 100 | + var checkedProgram = bundleRuntime ? CheckSemantics(bundledProgram) : program; |
| 101 | + // Return the program after front end processing |
| 102 | + return checkedProgram; |
| 103 | + } |
| 104 | +#nullable restore |
| 105 | + /// <summary> |
| 106 | + /// This method runs the lexer on the given source code. |
| 107 | + /// </summary> |
| 108 | + /// <param name="source">The raw source code to lex.</param> |
| 109 | + /// <param name="inputFileName">The name of the file that contained the source code.</param> |
| 110 | + /// <returns>The lexer instance.</returns> |
| 111 | +#nullable enable |
| 112 | + public static DecafLexer LexSource(string source, string? inputFileName) { |
| 113 | + // Create Input Stream |
| 114 | + var inputStream = new AntlrInputStream(source) { |
| 115 | + name = inputFileName ?? "<unknown file>" |
| 116 | + }; |
| 117 | + // Create Lexer Instance |
| 118 | + var lexer = new DecafLexer(inputStream); |
| 119 | + // Setup our custom error handler for better error reporting |
| 120 | + lexer.RemoveErrorListeners(); |
| 121 | + lexer.AddErrorListener(LexerErrorListener.Instance); |
| 122 | + return lexer; |
| 123 | + } |
| 124 | +#nullable restore |
| 125 | + /// <summary>This method runs the parser on the given token stream.</summary> |
| 126 | + /// <param name="tokenStream">The token stream to parse.</param> |
| 127 | + /// <returns>The parsed program.</returns> |
| 128 | + public static ParseTree.ProgramNode ParseSource(CommonTokenStream tokenStream) { |
| 129 | + // Initialize the parser |
| 130 | + var parser = new DecafParser(tokenStream); |
| 131 | + // Setup our custom error handler for better error reporting |
| 132 | + parser.RemoveErrorListeners(); |
| 133 | + parser.AddErrorListener(ParserErrorListener.Instance); |
| 134 | + // Convert the ANTLR parse tree to our own parse tree representation |
| 135 | + var program = ParseTreeMapper.MapProgramContext(parser.program()); |
| 136 | + return program; |
| 137 | + } |
| 138 | + /// <summary> |
| 139 | + /// This method runs the semantic analysis phase on the given program, which includes: |
| 140 | + /// - Scope Validation |
| 141 | + /// - Semantic Validation |
| 142 | + /// </summary> |
| 143 | + /// <param name="program">The parsed program to check.</param> |
| 144 | + /// <returns>The checked program.</returns> |
| 145 | + public static ParseTree.ProgramNode CheckSemantics(ParseTree.ProgramNode program) { |
| 146 | + // Validate program scoping semantics |
| 147 | + ScopeChecker.CheckProgramNode(program); |
| 148 | + // Validate program general semantics |
| 149 | + SemanticChecker.CheckProgramNode(program); |
| 150 | + return program; |
| 151 | + } |
| 152 | + // --- Middle end --- |
| 153 | + |
| 154 | + /// <summary> |
| 155 | + /// This method runs the entire middle end pipeline on the given program, this includes: |
| 156 | + /// - Type checking |
| 157 | + /// - Lowering to ANF |
| 158 | + /// - Optimizations |
| 159 | + /// |
| 160 | + /// NOTE: This method expects the input program to have already been processed by the front end, |
| 161 | + /// if scoping or semantics have not been validated then this may not work correctly and may throw |
| 162 | + /// unexpected exceptions, or produce malformed outputs. |
| 163 | + /// </summary> |
| 164 | + /// <param name="program">The parsed program to process.</param> |
| 165 | + /// <returns>The processed program.</returns> |
| 166 | + public static AnfTree.ProgramNode MiddleEnd(ParseTree.ProgramNode program) { |
| 167 | + // Type check the program |
| 168 | + var typedProgram = TypeChecker.TypeProgramNode(program); |
| 169 | + // Lower to ANF |
| 170 | + var anfProgram = AnfMapper.FromProgramNode(typedProgram); |
| 171 | + // Run optimizations |
| 172 | + var optimizedProgram = Optimizer.Optimize(anfProgram); |
| 173 | + // Return the program after middle end processing |
| 174 | + return optimizedProgram; |
| 175 | + } |
| 176 | + /// <summary> |
| 177 | + /// This method runs the type checker on the given program, which includes: |
| 178 | + /// - Validating that all expressions are well-typed |
| 179 | + /// - Annotating the parse tree with type information |
| 180 | + /// </summary> |
| 181 | + /// <param name="program">The parsed program to check.</param> |
| 182 | + /// <returns>The type-checked program.</returns> |
| 183 | + public static TypedTree.ProgramNode TypeCheck(ParseTree.ProgramNode program) { |
| 184 | + // Type check the program |
| 185 | + return TypeChecker.TypeProgramNode(program); |
| 186 | + } |
| 187 | + /// <summary> |
| 188 | + /// This method lowers the given program to ANF, which includes: |
| 189 | + /// - Converting all expressions to ANF form |
| 190 | + /// </summary> |
| 191 | + /// <param name="program">The type-checked program to lower.</param> |
| 192 | + /// <returns>The program in ANF form.</returns> |
| 193 | + public static AnfTree.ProgramNode LowerToAnf(TypedTree.ProgramNode program) { |
| 194 | + // Map the typed tree to the anf tree |
| 195 | + return AnfMapper.FromProgramNode(program); |
| 196 | + } |
| 197 | + /// <summary> |
| 198 | + /// This method runs the optimizer on the given program, which includes: |
| 199 | + /// - Running various optimization passes on the program to improve performance and reduce code size. |
| 200 | + /// </summary> |
| 201 | + /// <param name="program">The anf program to optimize.</param> |
| 202 | + /// <returns>The optimized program.</returns> |
| 203 | + public static AnfTree.ProgramNode OptimizeAnf(AnfTree.ProgramNode program) { |
| 204 | + // Run optimizations |
| 205 | + return Optimizer.Optimize(program); |
| 206 | + } |
| 207 | + // --- Back end --- |
| 208 | + |
| 209 | + /// <summary> |
| 210 | + /// This method runs the entire back end pipeline on the given program, this includes: |
| 211 | + /// - Lowering to wasm |
| 212 | + /// </summary> |
| 213 | + /// <param name="program">The anf program to compile.</param> |
| 214 | + /// <returns>The compiled wasm module.</returns> |
| 215 | + public static Wasm.WasmModule Backend(AnfTree.ProgramNode program) { |
| 216 | + // Lower the program to wasm |
| 217 | + var wasmModule = Codegen.CompileProgram(program); |
| 218 | + // Return the program after back end processing |
| 219 | + return wasmModule; |
| 220 | + } |
| 221 | + /// <summary> |
| 222 | + /// This method lowers the given program to wasm, which includes: |
| 223 | + /// - Converting all ANF instructions to their corresponding wasm instructions |
| 224 | + /// </summary> |
| 225 | + /// <param name="program">The anf program to lower.</param> |
| 226 | + /// <returns>The compiled wasm module.</returns> |
| 227 | + public static Wasm.WasmModule LowerToWasm(AnfTree.ProgramNode program) { |
| 228 | + // Lower the program to wasm |
| 229 | + return Codegen.CompileProgram(program); |
| 230 | + } |
| 231 | + } |
| 232 | + |
| 233 | +} |
0 commit comments