/
convergec.cv
772 lines (571 loc) · 30.6 KB
/
convergec.cv
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
// Copyright (c) 2003-2006 King's College London, created by Laurence Tratt
//
// 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.
import Builtins, Curses, Exceptions, File, Parse_Args, Platform::Properties, Strings, Sys, Time, VM
import Compiler::Code_Gen, Compiler::Core, Compiler::BC_Exec, Compiler::BC_Lib, Compiler::BC_Mod, Compiler::Parser, Compiler::BC_Pkg, Compiler::IMod_Gen, Compiler::Link, Compiler::Targets, Compiler::Tokenizer
class Compiler:
////////////////////////////////////////////////////////////////////////////////////////////////
// Compiler start up
//
func from_cmd_line(self):
options := []
options.append(Parse_Args::Opt_Spec.new("output", "o", Parse_Args::MANDATORY, Parse_Args::TYPE_ANY, Parse_Args::FREQUENCY_ZERO_OR_ONE))
options.append(Parse_Args::Opt_Spec.new("includes", "I", Parse_Args::MANDATORY, Parse_Args::TYPE_ANY, Parse_Args::FREQUENCY_ZERO_OR_MORE))
options.append(Parse_Args::Opt_Spec.new("make", "m", Parse_Args::NONE, Parse_Args::TYPE_ANY, Parse_Args::FREQUENCY_ZERO_OR_ONE))
options.append(Parse_Args::Opt_Spec.new("fresh", "f", Parse_Args::NONE, Parse_Args::TYPE_ANY, Parse_Args::FREQUENCY_ZERO_OR_ONE))
options.append(Parse_Args::Opt_Spec.new("optimise", "O", Parse_Args::NONE))
options.append(Parse_Args::Opt_Spec.new("target", "T", Parse_Args::MANDATORY, Parse_Args::TYPE_ANY, Parse_Args::FREQUENCY_ZERO_OR_ONE))
options.append(Parse_Args::Opt_Spec.new("verbose", "v", Parse_Args::NONE, Parse_Args::TYPE_ANY, Parse_Args::FREQUENCY_ZERO_OR_MORE))
self._init_curses()
self.mk_mode := 0
self.mk_fresh := 0
self.output_path := null
self.start_includes := []
self.verbosity := 0
target_name := Strings::format("%dbit", Properties::word_bits)
internal_target_name := Strings::format("%dbit", Properties::word_bits)
parsed, extra := Parse_Args::parse(self._usage_callback, options)
for option_name, option_val := parsed.iter():
ndif option_name == "output":
self.output_path := option_val
elif option_name == "includes":
self.start_includes.extend(option_val)
elif option_name == "make":
self.mk_mode := 1
elif option_name == "fresh":
self.mk_fresh := 1
elif option_name == "target":
target_name := option_val
elif option_name == "verbose":
self.verbosity += 1
if extra.len() == 0:
self._usage_callback("Not enough arguments.")
elif extra.len() > 1:
self._usage_callback("Too many arguments.")
if self.mk_fresh == 1 & self.mk_mode == 0:
self._usage_callback("-f makes no sense without -m.")
if self.output_path is null:
if self.mk_mode == 1:
main, ext := File::split_ext(extra[0])
if ext != Core::SRC_EXT:
self._usage_callback(Strings::format("-o can not be left out if input file does not end in '.%s'.", Core::SRC_EXT))
if File::exists(main):
// If there already exists a file with the name we want to write to, check that
// it really is a Converge executeable. If it isn't, we refuse to carry on.
file := File::open(main, "r")
bc := file.read()
file.close()
if bc.len() > 0 & not BC_Exec::is_bc_exec(bc):
self._usage_callback(Strings::format("-o can not be left out as '%s' can not be overwritten as it does not appear to be a Converge executeable.", main))
self.output_path := main
else:
self._usage_callback("-o option must be specified.")
self.target := self._target_name_to_target(target_name)
self.internal_target := self._target_name_to_target(internal_target_name)
self.end_includes := []
for lib_path := Core::get_std_libraries(self).iter():
lib_file := File::open(lib_path, "r")
bc := lib_file.read()
lib_file.close()
if not BC_Lib::is_bc_lib(bc):
self.error(Strings::format("File '%s' is not a library.", lib_path))
bc_lib := BC_Lib::BC_Lib.new(self.internal_target)
bc_lib.deserialize(bc)
self.end_includes.append(bc_lib)
self.src_paths_to_mod_ids := Dict{}
if self.mk_mode == 1:
self._make(extra[0])
else:
bc_mod := self._compile_path(extra[0])
output_file := File::open(self.output_path, "w")
output_file.write(bc_mod.serialize())
output_file.close()
func from_mk_mode(self, mod_id, src_path, start_includes, end_includes, verbosity, mk_fresh, target, internal_target, mk_done_bc_mods, mk_mtime_map):
self.mk_mode := 1
self.mk_fresh := mk_fresh
self.output_path := null
self.start_includes := start_includes
self.end_includes := end_includes
self.verbosity := verbosity
self.target := target
self.internal_target := internal_target
self._init_curses()
self.src_paths_to_mod_ids := Dict{}
self.mk_done_bc_mods := mk_done_bc_mods
bc_mod := self._compile_path(src_path)
self._write_cache_cvb(src_path, bc_mod.serialize())
mk_done_bc_mods[mod_id] := [src_path, bc_mod]
mk_mtime_map[mod_id] := Time::current()
return bc_mod
////////////////////////////////////////////////////////////////////////////////////////////////
// "Public" functions
//
func error(self, msg, src_infos := null):
self._print_msg("Error", msg, src_infos)
Sys::exit(1)
func warning(self, msg, src_infos := null):
// Some consoles (e.g. Windows) are very bad about flushing output, and messages between
// stdout and stderr can get horribly confused with each other. By flushing stdout then
// printing our message, then flushing stderr, we make a decent attempt at making sure
// that messages are both ordered correctly and printed fairly promptly.
Sys::stdout.flush()
self._print_msg("Warning", msg, src_infos)
Sys::stderr.flush()
func info(self, msg):
// Some consoles (e.g. Windows) are very bad about flushing output, and messages between
// stdout and stderr can get horribly confused with each other. By flushing stdout then
// printing our message, then flushing stderr, we make a decent attempt at making sure
// that messages are both ordered correctly and printed fairly promptly.
Sys::stdout.flush()
Sys::stderr.writeln(Strings::format("===> %s%s", " " * ((Core::num_compilers() - 1) * 2), msg))
Sys::stderr.flush()
func get_bc_mod(self, mod_id, src_path, src_infos := null):
if self.mk_mode == 1:
if bc_src_path, bc_mod := self.mk_done_bc_mods.find(mod_id) & not bc_mod is null:
return bc_mod
if not(self.mk_mode == 1 & self.mk_fresh == 1):
if bc_mod, mtime := self._read_cache_cvb(src_path):
if mod_id == bc_mod.get_mod_id():
return bc_mod
if self.mk_mode == 0:
self.error(Strings::format("Can not find compiled version of '%s'.", src_path), src_infos)
compiler := Compiler.new()
Core::push_compiler(compiler)
bc_mod := compiler.from_mk_mode(mod_id, src_path, self.start_includes, self.end_includes, self.verbosity, self.mk_fresh, self.target, self.internal_target, self.mk_done_bc_mods, self.mk_mtime_map)
Core::pop_compiler()
if self.verbosity > 0:
self.info(Strings::format("Returning to compile of %s...", self.src_path))
return bc_mod
func find_import_location(self, import_name_list):
func match_path(i, dir):
cnd_path := File::join_names(dir, import_name_list[i])
if File::exists(cnd_path) & File::is_dir(cnd_path):
if i + 1 == import_name_list.len():
return [cnd_path, i]
else:
return match_path(i + 1, cnd_path)
cnd_file_path := File::join_ext(cnd_path, Core::SRC_EXT)
if File::exists(cnd_file_path) & File::is_file(cnd_file_path):
return [cnd_file_path, i]
fail
for include := self.includes.iter():
if Builtins::String.instantiated(include):
if matched_path, extra_pos := match_path(0, include):
import_extras := import_name_list[extra_pos + 1 : ]
src_path := File::canon_path(matched_path)
if mod_id := self.src_paths_to_mod_ids.find(src_path):
break
if (self.mk_mode == 0 | (self.mk_mode == 1 & self.mk_fresh == 0)) & \
cvb_path := Core::get_cache_path(src_path) & File::exists(cvb_path):
f := File::open(cvb_path, "r")
bc := f.read()
if BC_Mod::is_bc_mod(bc):
bc_mod := BC_Mod::BC_Mod.new(self.internal_target)
else:
bc_mod := BC_Pkg::BC_Pkg.new(self.internal_target)
bc_mod.deserialize_str(bc)
f.close()
mod_id := bc_mod.get_mod_id()
else:
mod_id := Core::mk_mod_id(src_path)
self.src_paths_to_mod_ids[src_path] := mod_id
break
else:
assert BC_Lib::BC_Lib.instantiated(include)
cnd := include.get_main_pkg()
if import_name_list[0] != "Stdlib" & cnd.get_name() == "Stdlib":
if mod_id, src_path := cnd.get_entries().find(import_name_list[0]):
if not cnd := include.find_mod_id(mod_id):
raise "XXX"
if import_name_list[0] == cnd.get_name():
i := 1
while i < import_name_list.len() & not BC_Mod::BC_Mod.instantiated(cnd):
mod_id, src_path := cnd.get_entries()[import_name_list[i]]
if not cnd := include.find_mod_id(mod_id):
raise "XXX"
i += 1
mod_id := cnd.get_mod_id()
src_path := cnd.get_src_path()
import_extras := import_name_list[i : ]
break
exhausted:
// If the first part of the import references a builtin, then looking up that module ID
// will succeed.
if VM::find_module(import_name_list[0]):
mod_id := src_path := import_name_list[0]
import_extras := import_name_list[1 : ]
else:
fail
return [mod_id, src_path, import_extras]
////////////////////////////////////////////////////////////////////////////////////////////////
// Internal functions
//
func _init_curses(self):
self._use_curses := 1
try:
Curses::setupterm(null, Sys::stderr)
Curses::tigetstr("sgr0")
catch Curses::Curses_Exception:
// If we can't initialise curses, we ignore the error and resort to "plain" output.
self._use_curses := 0
func _compile_path(self, src_path):
if not File::exists(src_path):
self.error(Strings::format("Source file '%s' not found.", src_path))
if File::is_dir(src_path):
return self._compile_pkg(src_path)
else:
return self._compile_mod(src_path)
func _compile_pkg(self, src_path):
if self.verbosity > 0:
self.info(Strings::format("Compiling %s...", src_path))
src_path := File::canon_path(src_path)
pkg_entries := Dict{}
for leaf := File::iter_dir_entries(src_path):
defn_name, ext := File::split_ext(leaf)
if not (ext == "" | ext == Core::SRC_EXT):
continue
entry_path := File::canon_path(File::join_names(src_path, leaf))
entry_mod_id := Core::mk_mod_id(entry_path)
pkg_entries[defn_name] := [entry_mod_id, entry_path]
bc_pkg := BC_Pkg::BC_Pkg.new(self.target)
bc_pkg.set_name(File::split_leaf(src_path)[1])
bc_pkg.set_mod_id(Core::mk_mod_id(File::canon_path(src_path)))
bc_pkg.set_src_path(src_path)
bc_pkg.set_entries(pkg_entries)
if self.verbosity > 0:
self.info(Strings::format("Finished compiling %s.", src_path))
return bc_pkg
func _compile_mod(self, src_path):
if self.verbosity > 0:
self.info(Strings::format("Compiling %s...", src_path))
self.src_path := File::canon_path(src_path)
self.mod_id := Core::mk_mod_id(self.src_path)
self.includes := self.start_includes[ : ]
if (input_file_dir := File::split_leaf(self.src_path)[0]) == "":
self.includes.insert(0, ".")
else:
self.includes.insert(0, input_file_dir)
self.includes.extend(self.end_includes)
// For the moment, we assume the compiled module name is simply the leaf name (minus its
// extension). On platforms with non-case preserving filesystems, perhaps there is a need
// for a more sophisticated mechanism?
self.src_module_name := File::split_ext(File::split_leaf(self.src_path)[1])[0]
src_file := File::open(self.src_path, "r")
src_data := src_file.read()
src_file.close()
// If there's a UNIX shell "#!" line at the beginning of the file, we completely ignore it.
// Note that this behaviour happens on all platforms, even though it might seem it should be
// restricted to UNIX machines. This is because UNIX scripts often end up being
// transferred to non-UNIX machines, and it's not feasible to have people take out and put in
// "#!" lines continuously.
src_offset := 0
if src_data.prefixed_by("#!"):
while src_offset < src_data.len() & not ["\n", "\r"].find(src_data[src_offset]):
src_offset += 1
src_data := src_data[src_offset : ]
self.tokenizer := Tokenizer::Tokenizer.new()
parse_tree := Parser::parse(src_data, src_offset)
self.newlines := self.tokenizer.newlines
imodule := IMod_Gen::IMod_Gen.new().gen(parse_tree)
bc := Code_Gen::Code_Gen.new().generate(self.target, imodule)
if self.verbosity > 0:
self.info(Strings::format("Finished compiling %s.", src_path))
return bc
//
// Compile 'src_path', and its dependencies, in a make-like fashion.
//
func _make(self, src_path):
// This function has more to it than it might first appear. The basic strategy is this: we
// compile the given module and all its obvious imports. Life becomes trickier because of
// CTMP. This means that when we're half way through compiling x.cv, we realise we need
// to compile y.cv in order that x.cv can execute CTMP. This means that we have to start
// up sub-compiler(s).
if not self.output_path.prefixed_by("/dev/fd/") & File::exists(self.output_path):
if File::mtime(self.output_path) < File::mtime(src_path):
do_link := 1
else:
do_link := 0
else:
do_link := 1
main_mod_id := Core::mk_mod_id(File::canon_path(src_path))
// mk_done_bc_mods is a map from mod ids to [src path, BC_Mod instance].
self.mk_done_bc_mods := Dict{main_mod_id : [File::canon_path(src_path), null]}
// Now we read in any libraries that are part of the includes; we are very careful not to
// re-compile anything that is referenced in a library (this can happen if a machine has
// both the .cv and .cvb files referenced in a .cvl).
included_mod_ids := Set{}
for include := (self.start_includes + self.end_includes).iter():
ndif Builtins::String.instantiated(include):
continue
elif BC_Lib::BC_Lib.instantiated(include):
for bc_obj := include.iter_bc_mods():
included_mod_ids.add(bc_obj.get_mod_id())
self.mk_done_bc_mods[bc_obj.get_mod_id()] := [null, bc_obj]
// The main loop. Basically we keep on going around this, reading in cached files or
// compiling new files; and updating any modules who are older than their import
// dependencies to ensure that any CTMP works on the latest version of the module available.
// Assuming there are no circular imports this will eventually hit a fixed point (possibly
// having compiled the same module multiple times), and the loop is finished. Although this
// is not as efficient as a customised Makefile with static dependencies could be, it is
// easier to use and is (hopefully) guaranteed to make sure everything is upto date.
self.mk_mtime_map := Dict{} // module id : mtime
while 1:
again := 0 // Set to 1 to force another round of the loop.
mod_ids := []
for mod_ids.append(self.mk_done_bc_mods.iter_keys())
for mod_id := mod_ids.iter():
mod_src_path, bc_mod := self.mk_done_bc_mods[mod_id]
if included_mod_ids.find(mod_id):
continue
// We update the src path -> mod id map regardless of whether an entry already
// existed or it pointed to a different mod id.
self.src_paths_to_mod_ids[mod_src_path] := mod_id
compile := 0
if bc_mod is null:
if self.mk_fresh == 1:
compile := 1
else:
// We haven't previously encountered this module, so try seeing if we can
// read in a cached version.
if bc_mod, mtime := self._read_cache_cvb(mod_src_path):
assert mod_id == bc_mod.get_mod_id()
self.mk_done_bc_mods[mod_id] := [mod_src_path, bc_mod]
self.mk_mtime_map[mod_id] := mtime
else:
compile := 1
if not bc_mod is null:
mtime := self.mk_mtime_map[mod_id]
ndif BC_Mod::BC_Mod.instantiated(bc_mod):
// We check to see whether this module is "stale" i.e. is older than any of its
// import dependencies.
for imp_mod_id, imp_src_path := bc_mod.get_imports().iter():
if Core::BUILTIN_MODULES.find(imp_mod_id):
continue
if not self.mk_done_bc_mods.find(imp_mod_id):
self.mk_done_bc_mods[imp_mod_id] := [imp_src_path, null]
again := 1
elif mtime < self.mk_mtime_map.find(imp_mod_id):
compile := 1
elif BC_Pkg::BC_Pkg.instantiated(bc_mod):
// We check to see whether this package is "stale" i.e. is older than any of its
// entries.
for defn_name, t := bc_mod.get_entries().iter():
entry_mod_id, entry_src_path := t
if not self.mk_done_bc_mods.find(entry_mod_id):
self.mk_done_bc_mods[entry_mod_id] := [entry_src_path, null]
again := 1
elif mtime < self.mk_mtime_map.find(entry_mod_id):
compile := 1
if compile == 1:
// Compilation has been forced.
bc_mod := self._compile_path(mod_src_path)
self._write_cache_cvb(mod_src_path, bc_mod.serialize())
self.mk_done_bc_mods[mod_id][1] := bc_mod
self.mk_mtime_map[mod_id] := Time::current()
again := 1
do_link := 1
if again == 0:
break
// Everything is compiled. If anything has been updated, then we need to link things.
if do_link == 1 | self.mk_fresh == 1:
// Create the list of modules to link, including all library modules.
main_mod := self.mk_done_bc_mods[main_mod_id][1]
bc_mods := [main_mod]
for src_path, mod := self.mk_done_bc_mods.iter_vals():
if not mod is main_mod:
bc_mods.append(mod)
if self.verbosity > 0:
self.info("Linking.")
self.mod_id := main_mod_id
self.src_path := main_mod.get_src_path()
linked_bc_mods := Linker.new().link(self.target, bc_mods)
ser := BC_Exec::serialize(self.target, linked_bc_mods)
output_file := File::open(self.output_path, "w")
output_file.write(ser)
output_file.close()
try:
File::chmod(self.output_path, 493)
catch Exceptions::File_Exception:
pass
func _usage_callback(self, msg):
if not msg is null:
Sys::stderr.writeln(Strings::format("Error: %s", msg))
Sys::stderr.writeln("Usage: convergec [-bm] [-I <include> [-I <include> ...]] [-O] [-T <target bit size>] -o <output> <input>")
if not msg is null:
Sys::exit(1)
func _print_msg(self, pre_msg, msg, src_infos := null):
if not src_infos is null:
assert src_infos.len() > 0
Sys::stderr.writeln(Strings::format("%s:", pre_msg))
for src_info := src_infos.iter():
if src_info[0] == self.mod_id:
newlines := self.tokenizer.newlines
else:
if not mod := VM::find_module(src_info[0]):
raise "XXX"
newlines := []
for newlines.append(mod.iter_newlines())
src_offset := src_info[1]
line := 0
while line < newlines.len():
if src_offset < newlines[line]:
break
line += 1
ls_off := newlines[line - 1] // Line start offset
assert line < newlines.len()
col := src_offset - ls_off
le_off := newlines[line] - 1
src_len := src_info[2]
// If we have a file on the local machine which matches the src info, we now try
// and print out the appropriate line of source code.
//
// If this succeeds otherwise d contains the appropriate line of source code.
if local_src_path := self._mod_id_to_local_src_path(src_info[0]):
try:
f := File::open(local_src_path, "r")
f.seek(ls_off)
d := f.read(le_off - ls_off)
f.close()
catch Exceptions::IO_Exception:
d := local_src_path := null
if local_src_path is null:
entry := Strings::format(""" Mod id "%s", line %d, column %d, length %d:""", \
src_info[0], line, col, src_len)
Sys::stderr.writeln(entry)
else:
entry := Strings::format(""" File "%s", line %d, column %d, length %d:""", \
local_src_path, line, col, src_len)
Sys::stderr.writeln(entry)
// If we read in less bytes than we expected (presumably the user has changed
// the file since it was compiled), we don't add the contents of this file to
// the backtrace.
if d.len() == le_off - ls_off:
Sys::stderr.write(" ")
if self._use_curses == 1:
dls := d.lstripped()
dls_diff := d.len() - dls.len()
Sys::stderr.write(dls[ : col - dls_diff])
Sys::stderr.write(Curses::tigetstr("smul"))
Sys::stderr.write(Curses::tigetstr("bold"))
if src_len > le_off - ls_off - col:
Sys::stderr.writeln(Strings::format("%s...%s", \
dls[col - dls_diff : ], Curses::tigetstr("sgr0")))
else:
Sys::stderr.writeln(Strings::format("%s%s%s", \
dls[col - dls_diff : col - dls_diff + src_len], \
Curses::tigetstr("sgr0"), dls[col - dls_diff + src_len : ]))
else:
Sys::stderr.writeln(d.lstripped())
Sys::stderr.writeln(msg)
else:
Sys::stderr.writeln(Strings::format("%s: %s", pre_msg, msg))
//
// If 'mod_id' refers to a module with a corresponding source file on the local machine, this
// function returns the source files path name. Otherwise it fails.
//
func _mod_id_to_local_src_path(self, mod_id):
if mod := VM::find_module(mod_id):
return mod.src_path
for compiler := Core::iter_compilers():
if compiler.mod_id == mod_id:
return compiler.src_path
fail
func _target_name_to_target(self, target_name):
if not Targets::Available::TARGETS.find(target_name):
self.error(Strings::format("No support yet for target '%s'.", target_name))
return Targets::Available::TARGETS[target_name].new()
//
// Attempt to read the bytecode file matching 'src_path' if it exists. If nothing can be read,
// this method fails.
//
func _read_cache_cvb(self, src_path):
if (cvb_path := Core::get_cache_path(src_path)) & File::exists(cvb_path):
cvb_mtime := File::mtime(cvb_path)
if cvb_mtime > File::mtime(src_path):
cvb_file := File::open(cvb_path, "r")
bc := cvb_file.read()
cvb_file.close()
if BC_Mod::is_bc_mod(bc):
mod := BC_Mod::BC_Mod.new(self.internal_target)
mod.deserialize_str(bc)
return [mod, cvb_mtime]
fail
//
// Attempt to write the bytecode 'bc' to the correct cached location for the src file 'src_path'.
// No exception is raised if it is unable to do so.
//
func _write_cache_cvb(self, src_path, bc):
if cvb_path := Core::get_cache_path(src_path):
can_write := 1
if File::exists(cvb_path):
cvb_file := File::open(cvb_path, "r")
old_bc := cvb_file.read()
cvb_file.close()
if not (BC_Mod::is_bc_mod(old_bc) | BC_Pkg::is_bc_pkg(old_bc)):
can_write := 0
if can_write == 1:
try:
cvb_file := File::open(cvb_path, "w")
cvb_file.write(bc)
cvb_file.close()
catch Exceptions::File_Exception:
// Whatever the file exception was, we intentionally ignore it.
pass
func _locate_cv_files(self, path):
cv_files := []
for leaf := File::iter_dir_entries(path):
entry_path := File::join_names(path, leaf)
if File::is_file(entry_path) & File::split_ext(leaf)[1] == Core::SRC_EXT:
cv_files.append(entry_path)
elif File::is_dir(entry_path):
cv_files.extend(self._locate_cv_files(entry_path))
return cv_files
//
// This linker class is used when we're running in make mode only.
//
class Linker:
func link(self, target, mods):
self.target := target
self.mods := mods
return Link::link_min_pkgs(self, mods)
func error(self, msg, src_infos := null):
self.print_msg("Error", msg, src_infos)
Sys::exit(1)
func warning(self, msg, src_infos := null):
self.print_msg("Warning", msg, src_infos)
func print_msg(self, pre_msg, msg, src_infos := null):
if not src_infos is null:
Sys::stderr.writeln(Strings::format("%s:", pre_msg))
for src_info := src_infos.iter():
for bc_mod := self.mods.iter():
if bc_mod.get_mod_id() == src_info[0]:
break
exhausted:
raise "XXX"
mod := Builtins::Module.new(bc_mod.serialize())
line, col := mod.src_offset_to_line_column(src_info[1])
Sys::stderr.writeln(Strings::format(" %s, line %d, column %d", src_info[0], line, col))
Sys::stderr.writeln(msg)
else:
Sys::stderr.writeln(Strings::format("%s: %s", pre_msg, msg))
func main():
compiler := Compiler.new()
Core::push_compiler(compiler)
compiler.from_cmd_line()
Core::pop_compiler()