(* Raz: the command line. raz [-I dir]... [-o file] [-Werror] [-S] [-libc glibc|musl] [-base addr] [-bare] Main.raz raz run [-I dir]... Main.raz [arg]... raz -q check|words|def [-I dir]... Main.raz[:LINE:COL] raz --version Compiles the main module and every module it imports, writes the entry point, links what it reaches, and writes the executable: by default the main module's file without its .raz; with -S, it lists the main module's code instead. raz run writes it to a memfd instead, a file that lives only in memory, and executes it in raz's place with the arguments after Main.raz, so its status is the program's; its argv[0] is Main.raz. raz -q, for an editor, reads the main module's text from standard input and stops once it is checked: check writes its messages as rows, words the names that can be typed at the cursor, and def where the name there is declared (forEditor). The program starts by saving argc and argv, runs every module's body (those of the modules the program imports, imported modules first), then the main module's main, and ends with Rt.exit and main's status. A static program does this from its entry point. One that uses C starts through the C library, __libc_start_main, which sets C up and calls this as C's main; first it gives Rt C's exit, which Rt.exit then ends the program with. The C library is glibc, or musl on a machine that has musl's loader and not glibc's, unless -libc names one. Under -bare, for the bare machine, it saves no argc and argv and runs no body of Rt (Gen.entryPoint). Depends on: everything else, Host for what is the host system's, and Version, a module the build makes (build/src/Version.raz) from build/version.inc: what git describe says, or the make's VERSION. Leaves out: the work itself; the other units compile, link and write, and this only reads the command line and runs them in order. *) module Raz; import Sys, Out, Str, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, Gen, Parse, Link, Exe; import SYSTEM; const Report = "2026-11.0"; (* the version of doc/raz.md it follows *) var links: [4]Gen.Link; numLinks: INT; cLinks: [3]Gen.Link; (* C's symbols the entry point gives the library, in a program that uses C *) numCLinks: INT; proc say1(f, a: []const U8): []const U8; begin return Diag.say(f, [Fmt.str(a)]); end; (* The number of the name s *) proc internStr(s: []const U8): INT; begin return Scan.intern(SYSTEM.PTR(s), LEN(s)); end; (* The modules the program uses: the main module, Rt, and every module they import. A module read only for the interface check is not. *) proc use(m: ^Sym.Module); var i: ^Sym.Import; begin if m^.used then return; end; m^.used := true; i := m^.imports; while i # nil do use(i^.home); i := i^.next; end; end; (* Whether the program uses C: if so, the libraries it needs go to Exe, the C library first. *) proc usesC: BOOL; var m, st, c: ^Sym.Module; l: ^Sym.Lib; begin st := nil; c := nil; Exe.noLibs(); _ := Exe.needLib(internStr(Exe.libc)); m := Parse.firstModule; while m # nil do if m^.used and m^.linkStatic then st := m; end; if m^.used and m^.usesC then c := m; end; l := m^.libs; while m^.used and (l # nil) do if not Exe.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end; l := l^.next; end; m := m^.next; end; if (st # nil) and (c # nil) then Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))])); end; if c = nil then Exe.noLibs(); end; return c # nil; end; (* The address s, a number as raz writes one: decimal digits, or hexadecimal ones that start with a digit and end in H; and whether it is one, and fits in 64 bits. Past high(INT) it is taken as a UINT, whose bits it keeps: 0FFFFFFFF80000000H is -80000000H. *) proc address(s: []const U8): (INT, BOOL); var i, n, d, radix: INT; v: UINT; begin n := LEN(s); radix := 10; if (n > 1) and (s[n - 1] = 'H') then radix := 16; DEC(n); end; if (n = 0) or (s[0] < '0') or (s[0] > '9') then return 0, false; end; v := 0; for i := 0 to n - 1 do if (s[i] >= '0') and (s[i] <= '9') then d := INT(s[i]) - 48; elsif (radix = 16) and (s[i] >= 'A') and (s[i] <= 'F') then d := INT(s[i]) - 55; else return 0, false; end; if v > (UINT(0FFFFFFFFFFFFFFFFH) - UINT(d)) div UINT(radix) then return 0, false; end; v := v * UINT(radix) + UINT(d); end; return INT(v), true; end; (* The file, line and column of raz -q words' FILE:LINE:COL; false if it isn't one *) proc cursorAt(s: []const U8): ([]const U8, INT, INT, BOOL); var i, j: INT; line, col: I64; ok1, ok2: BOOL; begin j := Str.findLast(s, ":"); if j <= 0 then return s, 0, 0, false; end; i := Str.findLast(s[0..j], ":"); if i <= 0 then return s, 0, 0, false; end; line, ok1 := Str.toInt(s[i + 1..j]); col, ok2 := Str.toInt(s[j + 1..LEN(s)]); return s[0..i], INT(line), INT(col), ok1 and ok2 and (line >= 1) and (col >= 1); end; (* raz -q, for an editor: the main module's text is standard input, and messages are rows (check) or not given (words and def, whose path names the cursor). The result is the main module's path. *) proc forEditor(query, path: []const U8): []const U8; var line, col: INT; ok: BOOL; begin line := 0; col := 0; if query = "check" then Diag.setForm(Diag.Form.rows); elsif (query = "words") or (query = "def") then path, line, col, ok := cursorAt(path); if not ok then Diag.fatal(Diag.say("-q {} {}: expected FILE:LINE:COL", [Fmt.str(query), Fmt.str(path)])); end; Diag.setForm(Diag.Form.silent); Parse.setDefine(query = "def"); else Diag.fatal(say1("-q {}: expected check, words or def", query)); end; Scan.setStdin(path, line, col); return path; end; (* What raz -h says *) proc usage; begin Out.str("usage: raz [option]... Main.raz compiles Main.raz and the modules it imports\n"); Out.str(" raz run [option]... Main.raz [arg]... compiles it and runs it, with the args\n"); Out.str("options:\n"); Out.str(" -o file the program's file, Main without .raz if left out\n"); Out.str(" -I dir looks for imported modules in dir too, after Main.raz's own\n"); Out.str(" -lib dir the standard library is dir, not the lib beside raz; it is\n"); Out.str(" searched last, after -I and RAZ_PATH\n"); Out.str(" -Werror a warning counts as an error\n"); Out.str(" -S lists the main module's code, under each line of source\n"); Out.str(" -s strips symbols, line numbers, the places a failure is told\n"); Out.str(" by and the profiler: a failure says only its address\n"); Out.str(" -base addr loads the program at addr, not 400000H: a multiple of 4096\n"); Out.str(" in the low or the top 2 GB, as 0FFFFFFFF80000000H\n"); Out.str(" -noprofile leaves out the profiler, which RAZ_PROFILE turns on\n"); Out.str(" -bare for the bare machine, a kernel: reads no argc and argv, and\n"); Out.str(" runs no body of Rt, which sets the signals' handlers\n"); Out.str(" -libc name links a program that uses C against glibc or musl; by\n"); Out.str(" default glibc, or musl where only its loader is there\n"); Out.str(" -q check for an editor: checks Main.raz, its text read from standard\n"); Out.str(" input, and writes each message as a row (see raz(1))\n"); Out.str(" -q words with Main.raz:LINE:COL, writes the names that can be\n"); Out.str(" typed at the cursor there, one row each\n"); Out.str(" -q def with Main.raz:LINE:COL, writes where the name at the\n"); Out.str(" cursor is declared, and what it is\n"); Out.str(" -h, --help says this\n"); Out.str(" --version says the version, and the report it follows\n"); Out.str("see raz(1), and the report, doc/raz.md\n"); Out.flush(); end; (* The module named n, or nil if the program has none *) proc moduleNamed(n: []const U8): ^Sym.Module; var m: ^Sym.Module; begin m := Parse.firstModule; while (m # nil) and (Scan.nameOf(m^.name) # n) do m := m^.next; end; return m; end; (* What the library module m, found by name, declares as n *) proc objIn(m: ^Sym.Module; n: []const U8): ^Sym.Obj; var o: ^Sym.Obj; begin o := Sym.find(m^.scope, internStr(n)); if o = nil then Diag.fatal(Diag.say("{} has no {}", [Fmt.str(Scan.nameOf(m^.name)), Fmt.str(n)])); end; return o; end; (* Rt is given the address of chunk, in its variable v *) proc addLink(chunk: INT; v: ^Sym.Obj); begin links[numLinks].chunk := chunk; links[numLinks].into := v^.chunk; INC(numLinks); end; (* Whether Rt declares a name n *) proc declares(rt: ^Sym.Module; n: []const U8): BOOL; begin return Sym.find(rt^.scope, internStr(n)) # nil; end; (* Rt is given the address of its procedure p in its variable v, if it declares both; neither is no link, and one alone is an error that names the other, since the address is useless without its variable and the variable would be left empty *) proc addPair(rt: ^Sym.Module; p, v: []const U8); begin if declares(rt, p) and not declares(rt, v) then Diag.fatal(Diag.say("Rt has {} but no {}", [Fmt.str(p), Fmt.str(v)])); elsif declares(rt, v) and not declares(rt, p) then Diag.fatal(Diag.say("Rt has {} but no {}", [Fmt.str(v), Fmt.str(p)])); elsif declares(rt, p) then addLink(objIn(rt, p)^.chunk, objIn(rt, v)); end; end; (* What Rt is given for telling where a failed check was, as far as it declares it. The places table, which holds the line table a debugger reads, is always made (Link.markLive keeps it); Rt is given its address only if it has `places`, a variable for it. Rt's calls, place and startProfile are linked to the variables teller, placer and profiler (profiled: unless -noprofile or -bare). An Rt that declares none of these, a kernel's, gets a failed check with only the raw address of the failing call, as with -s, and still has the ELF's symbols and lines. *) proc giveRtPlaces(rt: ^Sym.Module; profiled: BOOL); begin Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1)); Chunk.setData(Link.placesChunk, nil, 0, 8); if declares(rt, "places") then addLink(Link.placesChunk, objIn(rt, "places")); end; addPair(rt, "calls", "teller"); addPair(rt, "place", "placer"); if profiled then addPair(rt, "startProfile", "profiler"); end; end; (* The library is given C's symbol sym, in its variable v *) proc addCLink(sym: []const U8; v: ^Sym.Obj); begin cLinks[numCLinks].chunk := Chunk.externChunk(internStr(sym)); cLinks[numCLinks].into := v^.chunk; INC(numCLinks); end; (* User libraries are source directories, not packages to discover recursively. Read NAME=value entries so an empty RAZ_PATH differs from an unset one; Sys.env alone gives "" for both. The slices and their array live until the compiler exits, as command-line paths do. *) proc userLibraries; var path, s: []const U8; dirs: ^[]const U8; i, first, n: INT; more, found: BOOL; begin i := 0; repeat s, more := Sys.envAt(i); if not more then break; end; if (LEN(s) >= 9) and (s[0..9] = "RAZ_PATH=") then path := s[9..LEN(s)]; found := true; break; end; INC(i); until false; if not found then s := Sys.env("HOME"); if LEN(s) > 0 then dirs := ^[]const U8(Scan.grab(SIZE([]const U8))); dirs[0] := say1("{}/.raz/lib", s); Parse.setUserDirs(dirs[0..1]); end; return; end; if LEN(path) = 0 then return; end; n := 1; for i := 0 to LEN(path) - 1 do if path[i] = ':' then INC(n); end; end; dirs := ^[]const U8(Scan.grab(n * SIZE([]const U8))); n := 0; first := 0; for i := 0 to LEN(path) do if (i = LEN(path)) or (path[i] = ':') then if i > first then dirs[n] := path[first..i]; INC(n); end; first := i + 1; end; end; Parse.setUserDirs(dirs[0..n]); end; proc main*: INT; var path, outPath, s: []const U8; i, first, entry, last, base: INT; m, rt, thread: ^Sym.Module; mainObj: ^Sym.Obj; run, noProfile, listing, dynamic, libcSaid, ok, bare: BOOL; err: ERROR; libDir, query: []const U8; begin path := ""; outPath := ""; libDir := ""; query := ""; noProfile := false; bare := false; listing := false; libcSaid := false; run := (Files.argCount() >= 2) and (Files.arg(1) = "run"); if run then i := 2; else i := 1; end; while i < Files.argCount() do s := Files.arg(i); if s = "-I" then INC(i); if Parse.numInc > 15 then Diag.fatal("more than 16 -I directories"); end; Parse.addIncDir(Files.arg(i)); elsif s = "-lib" then INC(i); libDir := Files.arg(i); if (LEN(libDir) = 0) or (Sys.access(libDir, {}) # 0) then Diag.fatal(say1("-lib {}: no such directory", libDir)); end; elsif s = "-o" then INC(i); outPath := Files.arg(i); elsif s = "-Werror" then Diag.setWerror(true); elsif s = "-S" then listing := true; Gen.setListing(true); elsif s = "-s" then Exe.setStripped(true); elsif s = "-base" then INC(i); base, ok := address(Files.arg(i)); Link.setBase(base); if not ok or (base mod Link.Page # 0) then Diag.fatal(say1("-base {}: expected an address, a multiple of 4096 as raz writes it, as 0FFFFFFFF80000000H", Files.arg(i))); end; elsif s = "-q" then INC(i); query := Files.arg(i); elsif s = "-noprofile" then noProfile := true; elsif s = "-bare" then bare := true; elsif s = "-libc" then INC(i); s := Files.arg(i); if (s # "glibc") and (s # "musl") then Diag.fatal(say1("unknown C library {}: glibc or musl", s)); end; Exe.setMusl(s = "musl"); libcSaid := true; elsif (s = "-h") or (s = "--help") then usage(); return 0; elsif s = "--version" then Out.str(Diag.say("raz {}, report {}\n", [Fmt.str(Version.Text), Fmt.str(Report)])); Out.flush(); return 0; elsif (LEN(s) > 0) and (s[0] = '-') then Diag.fatal(say1("unknown option {}", s)); else path := s; first := i; if run then break; end; (* the rest are the program's *) end; INC(i); end; if LEN(path) = 0 then usage(); return 1; end; if LEN(query) > 0 then path := forEditor(query, path); end; if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end; if run then (* asked now, before any source is read: its error is the refusal *) outPath, err := Host.prepareRun(); if err # nil then Diag.fatal(MSG(err)); end; end; if not libcSaid then Exe.setMusl(Host.cLibrary() = Host.musl); end; Parse.setVersion(Version.Text); Parse.setTarget(Exe.Os, Gen.Arch); if LEN(libDir) = 0 then libDir := Host.libraryDir(); end; Parse.setLibDir(libDir); userLibraries(); if LEN(outPath) = 0 then outPath := path; last := LEN(outPath); if (last >= 4) and (outPath[last - 4..last] = ".raz") then outPath := outPath[0..last - 4]; else outPath := say1("{}.out", outPath); end; end; m, err := Parse.compileMain(path); if err # nil then Diag.finish(); return 1; end; if Diag.errors > 0 then Diag.finish(); end; use(m); rt := moduleNamed("Rt"); if rt # nil then use(rt); end; mainObj := Sym.find(m^.scope, internStr("main")); if mainObj # nil then if (mainObj^.cls # Sym.oProc) or not mainObj^.exported then Diag.error(mainObj^.pos, "main must be an exported procedure"); elsif (mainObj^.typ^.len # 0) or ((mainObj^.typ^.base # nil) and (mainObj^.typ^.base # Sym.tInt)) then Diag.error(mainObj^.pos, "main must be proc main* or proc main*: INT"); end; if Diag.errors > 0 then Diag.finish(); end; end; Diag.finish(); if LEN(query) > 0 then return 0; end; (* checked: an editor wants no program *) if rt = nil then Diag.fatal("can't find module Rt"); end; (* what Rt is given: the places, which the linker makes, for Rt to say where a failed check or a signal was (place), and the calls under way then (calls); and the profiler, which needs them too: each only if Rt declares it (giveRtPlaces). raz -s gives none, -noprofile no profiler, and -bare no profiler, since Rt's body, which starts it, doesn't run. *) numLinks := 0; if not Exe.stripped then giveRtPlaces(rt, not noProfile and not bare); end; (* what a program that uses C is given of C: Rt its exit, and Thread, if the program has it, the calls that make and join C's threads, so that the C library knows of them *) dynamic := usesC(); if dynamic and (Host.cLibrary() = Host.none) then Diag.fatal("this compiler host cannot make a program that uses C"); end; if dynamic and bare then Diag.fatal("-bare: the program uses C, which needs Linux and its loader"); end; numCLinks := 0; if dynamic then addCLink("exit", objIn(rt, "cExit")); thread := moduleNamed("Thread"); if (thread # nil) and thread^.used then addCLink("pthread_create", objIn(thread, "cCreate")); addCLink("pthread_join", objIn(thread, "cJoin")); end; end; entry := Gen.entryPoint(dynamic, bare, Parse.firstModule, mainObj, cLinks[0..numCLinks], numCLinks, objIn(rt, "exit")^.chunk, links[0..numLinks], numLinks); Link.markLive(entry); (* what the target's Gen can't make yet stops a program that uses it *) for i := 0 to Chunk.numChunks - 1 do if Chunk.chunks[i].live and (LEN(Chunk.chunks[i].missing) > 0) then Diag.error(Chunk.chunks[i].missingAt, Chunk.chunks[i].missing); end; end; if not Parse.HasReals then for i := 0 to Chunk.numChunks - 1 do if Chunk.chunks[i].live and Chunk.chunks[i].reals then Diag.error(Chunk.chunks[i].realsAt, "this target has no reals"); end; end; end; if Diag.errors > 0 then Diag.finish(); end; if listing then Gen.list(m^.sname); return 0; end; Exe.setMainPath(path); if run then Exe.write(outPath, entry); _ := Host.execute(outPath, first); (* the program's argv is ours from Main.raz on *) Diag.fatal(say1("can't run {}", path)); end; Exe.write(outPath, entry); return 0; end; end Raz.