-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompiler_Generic_Driver.H
More file actions
527 lines (446 loc) · 17.3 KB
/
Copy pathCompiler_Generic_Driver.H
File metadata and controls
527 lines (446 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file Compiler_Generic_Driver.H
* @brief Reusable pipeline driver that operates on any `Compiler_Frontend`.
*
* The generic driver owns only the reusable post-frontend stages:
*
* - execution through `Interpreter_Runtime.H`
* - lowering from IR to bytecode
* - validation of bytecode artifacts
* - emission of portable C from IR
*
* Language-specific concerns such as parsing, semantic analysis, and lowering
* into HIR/IR are delegated to a `Compiler_Frontend` implementation.
*
* @ingroup Utilities
*/
#ifndef COMPILER_GENERIC_DRIVER_H
#define COMPILER_GENERIC_DRIVER_H
#include <fstream>
#include <sstream>
#include <string>
#include <Bytecode.H>
#include <Compiler_Backend_C.H>
#include <Compiler_Frontend.H>
#include <Compiler_Module_Binder.H>
#include <Compiler_Module_Linker.H>
#include <Compiler_Module_Name_Table.H>
#include <Compiler_Module_Semantic_Environment.H>
namespace Aleph {
/** @brief Configuration shared by all runs of `Compiler_Generic_Driver`. */
struct Compiler_Generic_Driver_Options
{
Interpreter_Runtime_Options runtime_options; ///< Runtime limits used by `run`.
Compiler_C_Backend_Options c_backend_options; ///< Backend-C emission options used by `emit-c`.
};
/** @brief Reusable orchestration object built on top of `Compiler_Frontend`. */
class Compiler_Generic_Driver
{
Compiler_Frontend *frontend_ = nullptr;
Compiler_Generic_Driver_Options config_;
Compiler_Bytecode_Context bytecode_ctx_;
Interpreter_Runtime runtime_;
size_t arena_bytes_ = 0;
DynArray<Compiler_Driver_Artifact> artifacts_;
DynArray<std::string> errors_;
DynArray<std::string> warnings_;
Compiler_Bytecode_Module *bytecode_module_ = nullptr;
Compiler_C_Backend_Emission c_emission_;
Compiler_Driver_Run_Output run_output_;
Compiler_Driver_Action last_action_ = Compiler_Driver_Action::Parse_Only;
void append_error(const std::string &text)
{
errors_.append(text);
}
void record_text_artifact(const std::string &label, std::string text)
{
Compiler_Driver_Detail::append_artifact(artifacts_, label, std::move(text));
}
void collect_frontend_state()
{
const auto &frontend_errors = frontend_->errors();
for (size_t i = 0; i < frontend_errors.size(); ++i)
errors_.append(frontend_errors.access(i));
const auto &frontend_warnings = frontend_->warnings();
for (size_t i = 0; i < frontend_warnings.size(); ++i)
warnings_.append(frontend_warnings.access(i));
const auto &frontend_artifacts = frontend_->artifacts();
for (size_t i = 0; i < frontend_artifacts.size(); ++i)
artifacts_.append(frontend_artifacts.access(i));
}
void record_diagnostics_artifact()
{
const auto *dx = frontend_->diagnostic_engine();
if (dx == nullptr)
return;
std::ostringstream out;
dx->render_plain(out);
record_text_artifact("diagnostics", out.str());
}
void record_import_order_artifact()
{
if (frontend_->find_artifact("imports.order") != nullptr)
return;
const auto &modules = frontend_->module_descriptors();
const auto &order = frontend_->module_merge_order();
if (modules.is_empty() or order.is_empty())
return;
record_text_artifact("imports.order", compiler_render_module_order(order, modules));
}
void record_module_metadata_artifact()
{
if (frontend_->find_artifact("modules.surface") != nullptr)
return;
const auto &metadata = frontend_->module_metadata();
if (metadata.is_empty())
return;
record_text_artifact("modules.surface", compiler_render_module_metadata(metadata));
}
void record_module_linkage_artifact()
{
if (frontend_->find_artifact("modules.linkage") != nullptr)
return;
const auto &descriptors = frontend_->module_descriptors();
const auto &metadata = frontend_->module_metadata();
const auto &order = frontend_->module_merge_order();
if (descriptors.is_empty() or metadata.is_empty() or order.is_empty())
return;
const auto linkage = compiler_link_module_surfaces(descriptors, metadata, order);
record_text_artifact("modules.linkage", compiler_render_module_linkage(linkage));
}
void record_module_bindings_artifact()
{
if (frontend_->find_artifact("modules.binding") != nullptr)
return;
const auto &descriptors = frontend_->module_descriptors();
const auto &metadata = frontend_->module_metadata();
const auto &order = frontend_->module_merge_order();
if (descriptors.is_empty() or metadata.is_empty() or order.is_empty())
return;
const auto linkage = compiler_link_module_surfaces(descriptors, metadata, order);
const auto bindings = compiler_bind_module_surfaces(linkage);
record_text_artifact("modules.binding", compiler_render_module_bindings(bindings));
}
void record_module_name_table_artifact()
{
if (frontend_->find_artifact("modules.names") != nullptr)
return;
const auto &descriptors = frontend_->module_descriptors();
const auto &metadata = frontend_->module_metadata();
const auto &order = frontend_->module_merge_order();
if (descriptors.is_empty() or metadata.is_empty() or order.is_empty())
return;
const auto linkage = compiler_link_module_surfaces(descriptors, metadata, order);
const auto bindings = compiler_bind_module_surfaces(linkage);
const auto table = compiler_build_module_name_table(bindings);
record_text_artifact("modules.names", compiler_render_module_name_table(table));
}
void record_module_semantic_environment_artifact()
{
if (frontend_->find_artifact("modules.semantic") != nullptr)
return;
const auto &descriptors = frontend_->module_descriptors();
const auto &metadata = frontend_->module_metadata();
const auto &order = frontend_->module_merge_order();
if (descriptors.is_empty() or metadata.is_empty() or order.is_empty())
return;
const auto linkage = compiler_link_module_surfaces(descriptors, metadata, order);
const auto bindings = compiler_bind_module_surfaces(linkage);
const auto table = compiler_build_module_name_table(bindings);
const auto env = compiler_build_module_semantic_environment(table);
record_text_artifact("modules.semantic", compiler_render_module_semantic_environment(env));
}
void record_driver_messages_artifact()
{
record_text_artifact("driver.messages",
Compiler_Driver_Detail::render_messages(errors_, warnings_));
}
bool lower_bytecode()
{
Compiler_Bytecode_Lowering lowering(bytecode_ctx_);
bytecode_module_ = lowering.lower_module(frontend_->ir_module());
record_text_artifact("bytecode",
compiler_dump_bytecode_module(bytecode_module_, frontend_->type_context()));
if (bytecode_module_ == nullptr)
{
append_error("bytecode: null bytecode module produced by lowering");
return false;
}
const auto report = validate_bytecode_module(*bytecode_module_);
return Compiler_Driver_Detail::merge_report("bytecode", report, errors_, warnings_);
}
bool emit_c()
{
c_emission_ = compiler_emit_c_module(frontend_->ir_module(), config_.c_backend_options);
record_text_artifact("emit-c", c_emission_.source);
return Compiler_Driver_Detail::merge_report("emit-c", c_emission_, errors_, warnings_);
}
bool execute_hir_runtime()
{
run_output_ = {};
run_output_.executed = true;
run_output_.result = runtime_.evaluate_module(frontend_->hir_module());
if (run_output_.result.ok())
run_output_.value_text = interpreter_value_to_string(run_output_.result.value);
else
run_output_.value_text = "";
run_output_.globals_text = interpreter_dump_globals(runtime_);
record_text_artifact("run.result", Compiler_Driver_Detail::render_run_result(run_output_));
record_text_artifact("run.globals", run_output_.globals_text);
return run_output_.result.ok();
}
void append_run_failure_if_needed()
{
if (run_output_.result.ok())
return;
std::string message = "run: HIR runtime execution failed";
if (not run_output_.result.error.code.empty() or not run_output_.result.error.message.empty())
{
message += ":";
if (not run_output_.result.error.code.empty())
message += " " + run_output_.result.error.code;
if (not run_output_.result.error.message.empty())
{
if (not run_output_.result.error.code.empty())
message += " ";
message += run_output_.result.error.message;
}
}
errors_.append(message);
}
bool finalize(const Compiler_Driver_Action action)
{
last_action_ = action;
collect_frontend_state();
record_import_order_artifact();
record_module_metadata_artifact();
record_module_linkage_artifact();
record_module_bindings_artifact();
record_module_name_table_artifact();
record_module_semantic_environment_artifact();
record_driver_messages_artifact();
record_diagnostics_artifact();
return ok();
}
static bool read_file_text(const std::string &path, std::string &out_text)
{
std::ifstream in(path);
if (not in)
return false;
std::ostringstream out;
out << in.rdbuf();
out_text = out.str();
return true;
}
public:
/** @brief Builds one generic driver over a concrete frontend implementation.
*
* @param frontend_impl Frontend used for parse/sema/HIR/IR stages.
* @param options Runtime and backend configuration.
* @param arena_size Arena size used by bytecode lowering.
*/
explicit Compiler_Generic_Driver(Compiler_Frontend &frontend_impl,
const Compiler_Generic_Driver_Options &options = {},
const size_t arena_size = 1 << 20)
: frontend_(&frontend_impl), config_(options), bytecode_ctx_(arena_size),
runtime_(frontend_impl.diagnostic_engine(), options.runtime_options), arena_bytes_(arena_size)
{}
Compiler_Generic_Driver(const Compiler_Generic_Driver &) = delete;
Compiler_Generic_Driver &operator=(const Compiler_Generic_Driver &) = delete;
/** @brief Returns the immutable driver configuration. */
[[nodiscard]] const Compiler_Generic_Driver_Options &options() const noexcept
{
return config_;
}
/** @brief Returns the configured bytecode arena size. */
[[nodiscard]] size_t arena_size() const noexcept
{
return arena_bytes_;
}
/** @brief Clears all driver and frontend state while preserving host bindings. */
void clear() noexcept
{
artifacts_.clear();
errors_.clear();
warnings_.clear();
bytecode_module_ = nullptr;
c_emission_ = {};
run_output_ = {};
last_action_ = Compiler_Driver_Action::Parse_Only;
frontend_->clear();
runtime_.reset();
runtime_.set_diagnostics(frontend_->diagnostic_engine());
bytecode_ctx_.reset();
}
/** @brief Binds one host function into the persistent runtime prelude. */
bool bind_host_function(const std::string &name,
const Interpreter_Host_Function callback,
void *user_data = nullptr)
{
return runtime_.bind_host_function(name, callback, user_data);
}
/** @brief Runs the pipeline over in-memory sources. */
bool execute_sources(const DynArray<Compiler_Driver_Source> &inputs,
const Compiler_Driver_Action action = Compiler_Driver_Action::Run)
{
clear();
if (not frontend_->load_sources(inputs))
return finalize(action);
if (not frontend_->parse())
return finalize(action);
if (action == Compiler_Driver_Action::Parse_Only)
return finalize(action);
if (not frontend_->analyze())
return finalize(action);
if (action == Compiler_Driver_Action::Sema_Only)
return finalize(action);
if (not frontend_->lower_hir())
{
append_error("hir: failed to lower frontend program to HIR");
return finalize(action);
}
if (action == Compiler_Driver_Action::HIR)
return finalize(action);
if (action == Compiler_Driver_Action::Run)
{
if (not execute_hir_runtime())
append_run_failure_if_needed();
return finalize(action);
}
if (not frontend_->lower_ir())
return finalize(action);
if (action == Compiler_Driver_Action::IR)
return finalize(action);
switch (action)
{
case Compiler_Driver_Action::Emit_Bytecode:
(void) lower_bytecode();
return finalize(action);
case Compiler_Driver_Action::Emit_C:
(void) emit_c();
return finalize(action);
case Compiler_Driver_Action::Parse_Only:
case Compiler_Driver_Action::Sema_Only:
case Compiler_Driver_Action::HIR:
case Compiler_Driver_Action::IR:
case Compiler_Driver_Action::Run:
return finalize(action);
}
append_error("driver: reached unreachable action dispatch");
return finalize(action);
}
/** @brief Runs the pipeline over source files loaded from disk. */
bool execute_files(const DynArray<std::string> &paths,
const Compiler_Driver_Action action = Compiler_Driver_Action::Run)
{
DynArray<Compiler_Driver_Source> inputs;
for (size_t i = 0; i < paths.size(); ++i)
{
std::string text;
if (not read_file_text(paths.access(i), text))
{
clear();
append_error("driver: unable to read input file '" + paths.access(i) + "'");
return finalize(action);
}
inputs.append({paths.access(i), std::move(text)});
}
return execute_sources(inputs, action);
}
/** @brief Convenience overload for a single in-memory source. */
bool execute_source(const std::string &name,
const std::string &text,
const Compiler_Driver_Action action = Compiler_Driver_Action::Run)
{
DynArray<Compiler_Driver_Source> inputs;
inputs.append({name, text});
return execute_sources(inputs, action);
}
/** @brief Returns whether the last driver action finished successfully. */
[[nodiscard]] bool ok() const noexcept
{
const auto *dx = frontend_->diagnostic_engine();
return errors_.is_empty() and (dx == nullptr or not dx->has_errors());
}
/** @brief Returns the frontend used by this driver. */
[[nodiscard]] const Compiler_Frontend &frontend_impl() const noexcept
{
return *frontend_;
}
/** @brief Returns the last requested action. */
[[nodiscard]] Compiler_Driver_Action last_action() const noexcept
{
return last_action_;
}
/** @brief Returns the lowered bytecode module from the last run, when available. */
[[nodiscard]] const Compiler_Bytecode_Module *bytecode_module() const noexcept
{
return bytecode_module_;
}
/** @brief Returns the C emission payload from the last `emit-c` action. */
[[nodiscard]] const Compiler_C_Backend_Emission &c_emission() const noexcept
{
return c_emission_;
}
/** @brief Returns the run summary from the last `run` action. */
[[nodiscard]] const Compiler_Driver_Run_Output &run_output() const noexcept
{
return run_output_;
}
/** @brief Returns non-diagnostic driver-level hard errors. */
[[nodiscard]] const DynArray<std::string> &errors() const noexcept
{
return errors_;
}
/** @brief Returns non-fatal driver-level warnings. */
[[nodiscard]] const DynArray<std::string> &warnings() const noexcept
{
return warnings_;
}
/** @brief Returns all recorded artifacts from the last run. */
[[nodiscard]] const DynArray<Compiler_Driver_Artifact> &artifacts() const noexcept
{
return artifacts_;
}
/** @brief Finds one artifact by exact label. */
[[nodiscard]] const Compiler_Driver_Artifact *find_artifact(std::string_view label) const noexcept
{
for (size_t i = artifacts_.size(); i > 0; --i)
if (artifacts_.access(i - 1).label == label)
return &artifacts_.access(i - 1);
return nullptr;
}
/** @brief Renders diagnostics from the frontend as plain text. */
[[nodiscard]] std::string diagnostics_text() const
{
std::ostringstream out;
const auto *dx = frontend_->diagnostic_engine();
if (dx != nullptr)
dx->render_plain(out);
return out.str();
}
};
} // namespace Aleph
#endif