raz / src / Raz.raz

499 lines · 19.1 KiB · raw · history · last change 2b92b442

1(* Raz: the command line.
2
3 raz [-I dir]... [-o file] [-Werror] [-S] [-libc glibc|musl] [-base addr] [-bare] Main.raz
4 raz run [-I dir]... Main.raz [arg]...
5 raz -q check|words|def [-I dir]... Main.raz[:LINE:COL]
6 raz --version
7
8 Compiles the main module and every module it imports, writes the
9 entry point, links what it reaches, and writes the executable: by
10 default the main module's file without its .raz; with -S, it lists
11 the main module's code instead. raz run writes it to a memfd
12 instead, a file that lives only in memory, and executes it in raz's
13 place with the arguments after Main.raz, so its status is the
14 program's; its argv[0] is Main.raz. raz -q, for an editor, reads
15 the main module's text from standard input and stops once it is
16 checked: check writes its messages as rows, words the names that
17 can be typed at the cursor, and def where the name there is
18 declared (forEditor).
19
20 The program starts by saving argc and argv, runs every module's body
21 (those of the modules the program imports, imported modules first),
22 then the main module's main, and ends with Rt.exit and main's
23 status. A static program does this from its entry point. One that
24 uses C starts through the C library, __libc_start_main, which sets
25 C up and calls this as C's main; first it gives Rt C's exit, which
26 Rt.exit then ends the program with. The C library is glibc, or musl
27 on a machine that has musl's loader and not glibc's, unless -libc
28 names one. Under -bare, for the bare machine, it saves no argc and
29 argv and runs no body of Rt (Gen.entryPoint).
30
31 Depends on: everything else, Host for what is the host system's, and Version, a module the build makes
32 (build/src/Version.raz) from build/version.inc: what git describe
33 says, or the make's VERSION.
34 Leaves out: the work itself; the other units compile, link and
35 write, and this only reads the command line and runs them in order. *)
36module Raz;
37import Sys, Out, Str, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, Gen, Parse, Link, Exe;
38import SYSTEM;
39
40const
41 Report = "2026-11.0"; (* the version of doc/raz.md it follows *)
42
43var
44 links: [4]Gen.Link;
45 numLinks: INT;
46 cLinks: [3]Gen.Link; (* C's symbols the entry point gives the library, in a program that uses C *)
47 numCLinks: INT;
48
49proc say1(f, a: []const U8): []const U8;
50begin
51 return Diag.say(f, [Fmt.str(a)]);
52end;
53
54(* The number of the name s *)
55proc internStr(s: []const U8): INT;
56begin
57 return Scan.intern(SYSTEM.PTR(s), LEN(s));
58end;
59
60(* The modules the program uses: the main module, Rt, and every module
61 they import. A module read only for the interface check is not. *)
62proc use(m: ^Sym.Module);
63var i: ^Sym.Import;
64begin
65 if m^.used then return; end;
66 m^.used := true;
67 i := m^.imports;
68 while i # nil do
69 use(i^.home);
70 i := i^.next;
71 end;
72end;
73
74(* Whether the program uses C: if so, the libraries it needs go to
75 Exe, the C library first. *)
76proc usesC: BOOL;
77var m, st, c: ^Sym.Module; l: ^Sym.Lib;
78begin
79 st := nil; c := nil;
80 Exe.noLibs();
81 _ := Exe.needLib(internStr(Exe.libc));
82 m := Parse.firstModule;
83 while m # nil do
84 if m^.used and m^.linkStatic then st := m; end;
85 if m^.used and m^.usesC then c := m; end;
86 l := m^.libs;
87 while m^.used and (l # nil) do
88 if not Exe.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end;
89 l := l^.next;
90 end;
91 m := m^.next;
92 end;
93 if (st # nil) and (c # nil) then
94 Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))]));
95 end;
96 if c = nil then Exe.noLibs(); end;
97 return c # nil;
98end;
99
100(* The address s, a number as raz writes one: decimal digits, or
101 hexadecimal ones that start with a digit and end in H; and whether it
102 is one, and fits in 64 bits. Past high(INT) it is taken as a UINT,
103 whose bits it keeps: 0FFFFFFFF80000000H is -80000000H. *)
104proc address(s: []const U8): (INT, BOOL);
105var i, n, d, radix: INT; v: UINT;
106begin
107 n := LEN(s);
108 radix := 10;
109 if (n > 1) and (s[n - 1] = 'H') then radix := 16; DEC(n); end;
110 if (n = 0) or (s[0] < '0') or (s[0] > '9') then return 0, false; end;
111 v := 0;
112 for i := 0 to n - 1 do
113 if (s[i] >= '0') and (s[i] <= '9') then
114 d := INT(s[i]) - 48;
115 elsif (radix = 16) and (s[i] >= 'A') and (s[i] <= 'F') then
116 d := INT(s[i]) - 55;
117 else
118 return 0, false;
119 end;
120 if v > (UINT(0FFFFFFFFFFFFFFFFH) - UINT(d)) div UINT(radix) then return 0, false; end;
121 v := v * UINT(radix) + UINT(d);
122 end;
123 return INT(v), true;
124end;
125
126(* The file, line and column of raz -q words' FILE:LINE:COL; false if
127 it isn't one *)
128proc cursorAt(s: []const U8): ([]const U8, INT, INT, BOOL);
129var i, j: INT; line, col: I64; ok1, ok2: BOOL;
130begin
131 j := Str.findLast(s, ":");
132 if j <= 0 then return s, 0, 0, false; end;
133 i := Str.findLast(s[0..j], ":");
134 if i <= 0 then return s, 0, 0, false; end;
135 line, ok1 := Str.toInt(s[i + 1..j]);
136 col, ok2 := Str.toInt(s[j + 1..LEN(s)]);
137 return s[0..i], INT(line), INT(col), ok1 and ok2 and (line >= 1) and (col >= 1);
138end;
139
140(* raz -q, for an editor: the main module's text is standard input,
141 and messages are rows (check) or not given (words and def, whose
142 path names the cursor). The result is the main module's path. *)
143proc forEditor(query, path: []const U8): []const U8;
144var line, col: INT; ok: BOOL;
145begin
146 line := 0;
147 col := 0;
148 if query = "check" then
149 Diag.setForm(Diag.Form.rows);
150 elsif (query = "words") or (query = "def") then
151 path, line, col, ok := cursorAt(path);
152 if not ok then Diag.fatal(Diag.say("-q {} {}: expected FILE:LINE:COL", [Fmt.str(query), Fmt.str(path)])); end;
153 Diag.setForm(Diag.Form.silent);
154 Parse.setDefine(query = "def");
155 else
156 Diag.fatal(say1("-q {}: expected check, words or def", query));
157 end;
158 Scan.setStdin(path, line, col);
159 return path;
160end;
161
162(* What raz -h says *)
163proc usage;
164begin
165 Out.str("usage: raz [option]... Main.raz compiles Main.raz and the modules it imports\n");
166 Out.str(" raz run [option]... Main.raz [arg]... compiles it and runs it, with the args\n");
167 Out.str("options:\n");
168 Out.str(" -o file the program's file, Main without .raz if left out\n");
169 Out.str(" -I dir looks for imported modules in dir too, after Main.raz's own\n");
170 Out.str(" -lib dir the standard library is dir, not the lib beside raz; it is\n");
171 Out.str(" searched last, after -I and RAZ_PATH\n");
172 Out.str(" -Werror a warning counts as an error\n");
173 Out.str(" -S lists the main module's code, under each line of source\n");
174 Out.str(" -s strips symbols, line numbers, the places a failure is told\n");
175 Out.str(" by and the profiler: a failure says only its address\n");
176 Out.str(" -base addr loads the program at addr, not 400000H: a multiple of 4096\n");
177 Out.str(" in the low or the top 2 GB, as 0FFFFFFFF80000000H\n");
178 Out.str(" -noprofile leaves out the profiler, which RAZ_PROFILE turns on\n");
179 Out.str(" -bare for the bare machine, a kernel: reads no argc and argv, and\n");
180 Out.str(" runs no body of Rt, which sets the signals' handlers\n");
181 Out.str(" -libc name links a program that uses C against glibc or musl; by\n");
182 Out.str(" default glibc, or musl where only its loader is there\n");
183 Out.str(" -q check for an editor: checks Main.raz, its text read from standard\n");
184 Out.str(" input, and writes each message as a row (see raz(1))\n");
185 Out.str(" -q words with Main.raz:LINE:COL, writes the names that can be\n");
186 Out.str(" typed at the cursor there, one row each\n");
187 Out.str(" -q def with Main.raz:LINE:COL, writes where the name at the\n");
188 Out.str(" cursor is declared, and what it is\n");
189 Out.str(" -h, --help says this\n");
190 Out.str(" --version says the version, and the report it follows\n");
191 Out.str("see raz(1), and the report, doc/raz.md\n");
192 Out.flush();
193end;
194
195(* The module named n, or nil if the program has none *)
196proc moduleNamed(n: []const U8): ^Sym.Module;
197var m: ^Sym.Module;
198begin
199 m := Parse.firstModule;
200 while (m # nil) and (Scan.nameOf(m^.name) # n) do m := m^.next; end;
201 return m;
202end;
203
204(* What the library module m, found by name, declares as n *)
205proc objIn(m: ^Sym.Module; n: []const U8): ^Sym.Obj;
206var o: ^Sym.Obj;
207begin
208 o := Sym.find(m^.scope, internStr(n));
209 if o = nil then Diag.fatal(Diag.say("{} has no {}", [Fmt.str(Scan.nameOf(m^.name)), Fmt.str(n)])); end;
210 return o;
211end;
212
213(* Rt is given the address of chunk, in its variable v *)
214proc addLink(chunk: INT; v: ^Sym.Obj);
215begin
216 links[numLinks].chunk := chunk;
217 links[numLinks].into := v^.chunk;
218 INC(numLinks);
219end;
220
221(* Whether Rt declares a name n *)
222proc declares(rt: ^Sym.Module; n: []const U8): BOOL;
223begin
224 return Sym.find(rt^.scope, internStr(n)) # nil;
225end;
226
227(* Rt is given the address of its procedure p in its variable v, if it
228 declares both; neither is no link, and one alone is an error that
229 names the other, since the address is useless without its variable
230 and the variable would be left empty *)
231proc addPair(rt: ^Sym.Module; p, v: []const U8);
232begin
233 if declares(rt, p) and not declares(rt, v) then
234 Diag.fatal(Diag.say("Rt has {} but no {}", [Fmt.str(p), Fmt.str(v)]));
235 elsif declares(rt, v) and not declares(rt, p) then
236 Diag.fatal(Diag.say("Rt has {} but no {}", [Fmt.str(v), Fmt.str(p)]));
237 elsif declares(rt, p) then
238 addLink(objIn(rt, p)^.chunk, objIn(rt, v));
239 end;
240end;
241
242(* What Rt is given for telling where a failed check was, as far as it
243 declares it. The places table, which holds the line table a debugger
244 reads, is always made (Link.markLive keeps it); Rt is given its
245 address only if it has `places`, a variable for it. Rt's calls, place and
246 startProfile are linked to the variables teller, placer and profiler
247 (profiled: unless -noprofile or -bare). An Rt that declares none of
248 these, a kernel's, gets a failed check with only the raw address of
249 the failing call, as with -s, and still has the ELF's symbols and
250 lines. *)
251proc giveRtPlaces(rt: ^Sym.Module; profiled: BOOL);
252begin
253 Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1));
254 Chunk.setData(Link.placesChunk, nil, 0, 8);
255 if declares(rt, "places") then addLink(Link.placesChunk, objIn(rt, "places")); end;
256 addPair(rt, "calls", "teller");
257 addPair(rt, "place", "placer");
258 if profiled then addPair(rt, "startProfile", "profiler"); end;
259end;
260
261(* The library is given C's symbol sym, in its variable v *)
262proc addCLink(sym: []const U8; v: ^Sym.Obj);
263begin
264 cLinks[numCLinks].chunk := Chunk.externChunk(internStr(sym));
265 cLinks[numCLinks].into := v^.chunk;
266 INC(numCLinks);
267end;
268
269(* User libraries are source directories, not packages to discover
270 recursively. Read NAME=value entries so an empty RAZ_PATH differs
271 from an unset one; Sys.env alone gives "" for both. The slices and
272 their array live until the compiler exits, as command-line paths do. *)
273proc userLibraries;
274var path, s: []const U8; dirs: ^[]const U8; i, first, n: INT; more, found: BOOL;
275begin
276 i := 0;
277 repeat
278 s, more := Sys.envAt(i);
279 if not more then break; end;
280 if (LEN(s) >= 9) and (s[0..9] = "RAZ_PATH=") then
281 path := s[9..LEN(s)];
282 found := true;
283 break;
284 end;
285 INC(i);
286 until false;
287 if not found then
288 s := Sys.env("HOME");
289 if LEN(s) > 0 then
290 dirs := ^[]const U8(Scan.grab(SIZE([]const U8)));
291 dirs[0] := say1("{}/.raz/lib", s);
292 Parse.setUserDirs(dirs[0..1]);
293 end;
294 return;
295 end;
296 if LEN(path) = 0 then return; end;
297 n := 1;
298 for i := 0 to LEN(path) - 1 do
299 if path[i] = ':' then INC(n); end;
300 end;
301 dirs := ^[]const U8(Scan.grab(n * SIZE([]const U8)));
302 n := 0;
303 first := 0;
304 for i := 0 to LEN(path) do
305 if (i = LEN(path)) or (path[i] = ':') then
306 if i > first then
307 dirs[n] := path[first..i];
308 INC(n);
309 end;
310 first := i + 1;
311 end;
312 end;
313 Parse.setUserDirs(dirs[0..n]);
314end;
315
316proc main*: INT;
317var
318 path, outPath, s: []const U8;
319 i, first, entry, last, base: INT;
320 m, rt, thread: ^Sym.Module; mainObj: ^Sym.Obj;
321 run, noProfile, listing, dynamic, libcSaid, ok, bare: BOOL; err: ERROR;
322 libDir, query: []const U8;
323begin
324 path := "";
325 outPath := "";
326 libDir := "";
327 query := "";
328 noProfile := false;
329 bare := false;
330 listing := false;
331 libcSaid := false;
332 run := (Files.argCount() >= 2) and (Files.arg(1) = "run");
333 if run then i := 2; else i := 1; end;
334 while i < Files.argCount() do
335 s := Files.arg(i);
336 if s = "-I" then
337 INC(i);
338 if Parse.numInc > 15 then Diag.fatal("more than 16 -I directories"); end;
339 Parse.addIncDir(Files.arg(i));
340 elsif s = "-lib" then
341 INC(i);
342 libDir := Files.arg(i);
343 if (LEN(libDir) = 0) or (Sys.access(libDir, {}) # 0) then
344 Diag.fatal(say1("-lib {}: no such directory", libDir));
345 end;
346 elsif s = "-o" then
347 INC(i);
348 outPath := Files.arg(i);
349 elsif s = "-Werror" then
350 Diag.setWerror(true);
351 elsif s = "-S" then
352 listing := true;
353 Gen.setListing(true);
354 elsif s = "-s" then
355 Exe.setStripped(true);
356 elsif s = "-base" then
357 INC(i);
358 base, ok := address(Files.arg(i));
359 Link.setBase(base);
360 if not ok or (base mod Link.Page # 0) then
361 Diag.fatal(say1("-base {}: expected an address, a multiple of 4096 as raz writes it, as 0FFFFFFFF80000000H", Files.arg(i)));
362 end;
363 elsif s = "-q" then
364 INC(i);
365 query := Files.arg(i);
366 elsif s = "-noprofile" then
367 noProfile := true;
368 elsif s = "-bare" then
369 bare := true;
370 elsif s = "-libc" then
371 INC(i);
372 s := Files.arg(i);
373 if (s # "glibc") and (s # "musl") then Diag.fatal(say1("unknown C library {}: glibc or musl", s)); end;
374 Exe.setMusl(s = "musl");
375 libcSaid := true;
376 elsif (s = "-h") or (s = "--help") then
377 usage();
378 return 0;
379 elsif s = "--version" then
380 Out.str(Diag.say("raz {}, report {}\n", [Fmt.str(Version.Text), Fmt.str(Report)]));
381 Out.flush();
382 return 0;
383 elsif (LEN(s) > 0) and (s[0] = '-') then
384 Diag.fatal(say1("unknown option {}", s));
385 else
386 path := s;
387 first := i;
388 if run then break; end; (* the rest are the program's *)
389 end;
390 INC(i);
391 end;
392 if LEN(path) = 0 then
393 usage();
394 return 1;
395 end;
396 if LEN(query) > 0 then path := forEditor(query, path); end;
397 if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end;
398 if run then
399 (* asked now, before any source is read: its error is the refusal *)
400 outPath, err := Host.prepareRun();
401 if err # nil then Diag.fatal(MSG(err)); end;
402 end;
403 if not libcSaid then Exe.setMusl(Host.cLibrary() = Host.musl); end;
404 Parse.setVersion(Version.Text);
405 Parse.setTarget(Exe.Os, Gen.Arch);
406 if LEN(libDir) = 0 then libDir := Host.libraryDir(); end;
407 Parse.setLibDir(libDir);
408 userLibraries();
409 if LEN(outPath) = 0 then
410 outPath := path;
411 last := LEN(outPath);
412 if (last >= 4) and (outPath[last - 4..last] = ".raz") then
413 outPath := outPath[0..last - 4];
414 else
415 outPath := say1("{}.out", outPath);
416 end;
417 end;
418
419 m, err := Parse.compileMain(path);
420 if err # nil then
421 Diag.finish();
422 return 1;
423 end;
424 if Diag.errors > 0 then Diag.finish(); end;
425
426 use(m);
427 rt := moduleNamed("Rt");
428 if rt # nil then use(rt); end;
429
430 mainObj := Sym.find(m^.scope, internStr("main"));
431 if mainObj # nil then
432 if (mainObj^.cls # Sym.oProc) or not mainObj^.exported then
433 Diag.error(mainObj^.pos, "main must be an exported procedure");
434 elsif (mainObj^.typ^.len # 0) or ((mainObj^.typ^.base # nil) and (mainObj^.typ^.base # Sym.tInt)) then
435 Diag.error(mainObj^.pos, "main must be proc main* or proc main*: INT");
436 end;
437 if Diag.errors > 0 then Diag.finish(); end;
438 end;
439 Diag.finish();
440 if LEN(query) > 0 then return 0; end; (* checked: an editor wants no program *)
441
442 if rt = nil then Diag.fatal("can't find module Rt"); end;
443 (* what Rt is given: the places, which the linker makes, for Rt to say
444 where a failed check or a signal was (place), and the calls under
445 way then (calls); and the profiler, which needs them too: each
446 only if Rt declares it (giveRtPlaces). raz -s gives none,
447 -noprofile no profiler, and -bare no profiler, since Rt's body,
448 which starts it, doesn't run. *)
449 numLinks := 0;
450 if not Exe.stripped then giveRtPlaces(rt, not noProfile and not bare); end;
451 (* what a program that uses C is given of C: Rt its exit, and
452 Thread, if the program has it, the calls that make and join C's
453 threads, so that the C library knows of them *)
454 dynamic := usesC();
455 if dynamic and (Host.cLibrary() = Host.none) then Diag.fatal("this compiler host cannot make a program that uses C"); end;
456 if dynamic and bare then Diag.fatal("-bare: the program uses C, which needs Linux and its loader"); end;
457 numCLinks := 0;
458 if dynamic then
459 addCLink("exit", objIn(rt, "cExit"));
460 thread := moduleNamed("Thread");
461 if (thread # nil) and thread^.used then
462 addCLink("pthread_create", objIn(thread, "cCreate"));
463 addCLink("pthread_join", objIn(thread, "cJoin"));
464 end;
465 end;
466 entry := Gen.entryPoint(dynamic, bare, Parse.firstModule, mainObj, cLinks[0..numCLinks], numCLinks,
467 objIn(rt, "exit")^.chunk, links[0..numLinks], numLinks);
468
469 Link.markLive(entry);
470 (* what the target's Gen can't make yet stops a program that uses it *)
471 for i := 0 to Chunk.numChunks - 1 do
472 if Chunk.chunks[i].live and (LEN(Chunk.chunks[i].missing) > 0) then
473 Diag.error(Chunk.chunks[i].missingAt, Chunk.chunks[i].missing);
474 end;
475 end;
476 if not Parse.HasReals then
477 for i := 0 to Chunk.numChunks - 1 do
478 if Chunk.chunks[i].live and Chunk.chunks[i].reals then
479 Diag.error(Chunk.chunks[i].realsAt, "this target has no reals");
480 end;
481 end;
482 end;
483 if Diag.errors > 0 then Diag.finish(); end;
484 if listing then
485 Gen.list(m^.sname);
486 return 0;
487 end;
488
489 Exe.setMainPath(path);
490 if run then
491 Exe.write(outPath, entry);
492 _ := Host.execute(outPath, first); (* the program's argv is ours from Main.raz on *)
493 Diag.fatal(say1("can't run {}", path));
494 end;
495 Exe.write(outPath, entry);
496 return 0;
497end;
498
499end Raz.