| 1 | (* Parse: the parser. |
| 2 | |
| 3 | Reads modules by recursive descent and has Gen emit code as it goes: |
| 4 | one pass, no tree. Importing a module that isn't compiled yet |
| 5 | compiles it there and then, so modules are finished in an order where |
| 6 | each comes after the modules it imports; that is the order in which |
| 7 | their bodies run. |
| 8 | |
| 9 | A module may come in one file per target (Name.linux-x86_64.raz and |
| 10 | so on). The file for this target is compiled; the others beside it |
| 11 | are read for their declarations only, and must export the same |
| 12 | interface. |
| 13 | |
| 14 | Depends on: Scan, Sym, Chunk for data, Item and Gen for code. |
| 15 | Leaves out: linking; a module only records the libraries it names, |
| 16 | and whether it uses C or says link static. |
| 17 | |
| 18 | The seed's errors ended in a jump back to the statement or |
| 19 | declaration being read (Scan.mark, longjmp). Here every routine that |
| 20 | can find an error returns an ERROR as its last result, and the ones |
| 21 | that call it pass it up with try, as Item does; the statement or |
| 22 | declaration that is a recovery point (guard) looks at what comes back |
| 23 | and reads on. What has been made by then is what the seed had made |
| 24 | when it jumped. A seed `var` that only gave a value back is a result |
| 25 | where that is shorter; the others stay as they were. A set of |
| 26 | Scan.Sym is a chain of tests, since it has more names than a set |
| 27 | holds. *) |
| 28 | module Parse; |
| 29 | import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap, Out, Rt; |
| 30 | import SYSTEM; |
| 31 | |
| 32 | type |
| 33 | PType = ^Sym.Type; |
| 34 | PObj = ^Sym.Obj; |
| 35 | PModule = ^Sym.Module; |
| 36 | TItem = Item.Item; |
| 37 | |
| 38 | (* The innermost loop: the chain of its breaks, the chain of its |
| 39 | continues, and the deferred statements in force outside it *) |
| 40 | Loop = record |
| 41 | brk: INT; |
| 42 | cont: INT; |
| 43 | base: INT; |
| 44 | end; |
| 45 | PLoop = ^Loop; |
| 46 | |
| 47 | (* A generic module's import whose instance isn't made yet (deferred, |
| 48 | numDeferred); not to be confused with a defer statement (defers) *) |
| 49 | Deferred = record |
| 50 | o: PObj; (* the name it imports as *) |
| 51 | home: PModule; (* the module that imports it *) |
| 52 | mname: INT; (* the generic module *) |
| 53 | args: Scan.State; (* at the "(" of its arguments *) |
| 54 | at: Diag.Pos; (* the import *) |
| 55 | end; |
| 56 | |
| 57 | (* A type a type section names before it declares it (report, 4): |
| 58 | a pointer's base, or a procedure type's parameter or result. A |
| 59 | placeholder stands for it in its owner until the section's end, |
| 60 | when resolveLaters puts the type declared in its place. *) |
| 61 | Later = record |
| 62 | name: INT; (* the name of the type *) |
| 63 | at: Diag.Pos; (* where it is named *) |
| 64 | held: PType; (* the placeholder, a type of form fNone *) |
| 65 | owner: PType; (* the pointer or procedure type that holds it *) |
| 66 | end; |
| 67 | |
| 68 | const |
| 69 | (* Whether the target has reals (report, appendix A): x86-64 always has |
| 70 | SSE2. Without them, used code that computes with one is an error, |
| 71 | which Raz reports once it knows what the program uses. *) |
| 72 | HasReals* = true; |
| 73 | |
| 74 | MaxNames = 64; (* names in one declaration, and the like *) |
| 75 | MaxLater = 256; (* types named before they are declared *) |
| 76 | MaxDefers = 64; (* defer statements in force *) |
| 77 | MaxDoubts = 4096; (* places to warn of, noted while a module is read *) |
| 78 | MaxDeferred = 64; (* generic imports not yet made *) |
| 79 | MaxLabels = 1024; (* labels of one match *) |
| 80 | MaxElements = 1024; (* elements of an array literal *) |
| 81 | MaxFixes = 4096; (* addresses in one constant *) |
| 82 | MaxPending = 64; (* modules being compiled at once *) |
| 83 | MaxFors = 256; (* for loops of a procedure whose limit may go in a register *) |
| 84 | MaxNest = 256; (* statements, expressions and types nested; each level is a few recursive calls of the parser *) |
| 85 | |
| 86 | var |
| 87 | libDir*, mainDir: []const U8; |
| 88 | incDirs*: [16][]const U8; |
| 89 | numInc*: INT; |
| 90 | userDirs: [][]const U8; (* RAZ_PATH, or HOME/.raz/lib; set by the driver *) |
| 91 | thisVersion: []const U8; (* the compiler's version; set by the driver *) |
| 92 | targetOs, targetArch: []const U8; (* the target's names, Exe.Os and Gen.Arch; set by the driver *) |
| 93 | originNote: []const U8; (* for the module about to be opened, see libraryNote *) |
| 94 | firstModule*, lastModule*: PModule; (* in the order they were finished *) |
| 95 | |
| 96 | checkMode: BOOL; (* reading a file only for its interface *) |
| 97 | define: BOOL; (* raz -q def: the cursor asks where its name is declared *) |
| 98 | inTypes: BOOL; (* in a type section: ^T, and a procedure type, may name a later type *) |
| 99 | laters: [MaxLater]Later; |
| 100 | numLater: INT; |
| 101 | lastCalled: PObj; (* the procedure the last call was of, if it had a name *) |
| 102 | passOn: BOOL; (* the next factor may be a call with several results, for return *) |
| 103 | curProc: PObj; (* the procedure being compiled, or nil *) |
| 104 | declExported: BOOL; (* the export mark of the declaration being read *) |
| 105 | curLoop: PLoop; (* the innermost loop, or nil *) |
| 106 | defers: [MaxDefers]INT; (* the defer statements in force, their code's addresses *) |
| 107 | nest: INT; (* statements, expressions and types being read, one inside the other *) |
| 108 | numDefers: INT; |
| 109 | deferring: BOOL; (* compiling a defer statement's statement *) |
| 110 | directDefer: BOOL; (* ... as the statement itself, not in a list *) |
| 111 | deferSlot: I64; (* keeps a result while deferred statements run *) |
| 112 | curResult: PType; (* the result type of the procedure being compiled *) |
| 113 | inExtern: BOOL; (* reading an extern's signature: ... allowed *) |
| 114 | tArgv, tBodySig: PType; |
| 115 | nameRt, nameFail, nameBody, nameStatic, nameCheck, nameOff, nameAdr, nameCas, nameXchg, nameXadd: INT; |
| 116 | declaring: [MaxNames]INT; (* the names the declaration being read declares *) |
| 117 | numDeclaring: INT; |
| 118 | skipped: BOOL; (* the last statement had an error and was skipped *) |
| 119 | deferred: [MaxDeferred]Deferred; (* generic imports not yet made, not defer statements *) |
| 120 | numDeferred: INT; |
| 121 | making: BOOL; (* reading an instance's arguments, at its first use *) |
| 122 | stray: BOOL; (* an "end" in this procedure stood left of its statement's line *) |
| 123 | strayAt: Diag.Pos; (* ... the first such statement *) |
| 124 | elseIf: BOOL; (* an "else if" in this procedure *) |
| 125 | doubts: [MaxDoubts]record |
| 126 | at: Diag.Pos; (* a place the module's end warns of *) |
| 127 | n: INT; (* a call standing on its own that drops this many results, or *) |
| 128 | msg, hint: []const U8; (* any other doubt, in words (msg is empty for a drop) *) |
| 129 | end; |
| 130 | numDoubts: INT; (* the module being compiled has those from its |
| 131 | first one, saved by compileFile, to here *) |
| 132 | bareBoolRel: BOOL; (* the relation just read is an = or # of two BOOLs, |
| 133 | not in parentheses *) |
| 134 | ends: BOOL; (* the statements just read never go on past |
| 135 | their end: each way through them returns *) |
| 136 | useAt: Diag.Pos; (* ... which is here *) |
| 137 | guards: INT; (* the recovery points open *) |
| 138 | (* A variable register no variable took, for the limits of the |
| 139 | procedure's innermost for loops that aren't constant: compared |
| 140 | each round, they would be read from the frame. limitK is its place |
| 141 | in VarRegs, or -1; limitIn says which for loops, by their order |
| 142 | in the procedure (chooseRegs); numFors counts them as compiled. *) |
| 143 | limitK, numFors: INT; |
| 144 | limitIn: [MaxFors]BOOL; |
| 145 | (* For a body that is only return e (inlined): where the body's first |
| 146 | return statement ends, its ";" with it, or -1; whether a try was |
| 147 | read; and the calls made, which an inlined one doesn't count *) |
| 148 | returnEnd: INT; |
| 149 | sawTry: BOOL; |
| 150 | numCalls: INT; |
| 151 | |
| 152 | proc expression(var x: TItem; want: PType): ERROR; forward; |
| 153 | proc parseType: (PType, ERROR); forward; |
| 154 | proc typeBody: (PType, ERROR); forward; |
| 155 | proc statements: ERROR; forward; |
| 156 | proc statement: ERROR; forward; |
| 157 | |
| 158 | (* Little helpers *) |
| 159 | |
| 160 | proc setLibDir*(dir: []const U8); |
| 161 | begin |
| 162 | libDir := dir; |
| 163 | end; |
| 164 | |
| 165 | proc addIncDir*(dir: []const U8); |
| 166 | begin |
| 167 | incDirs[numInc] := dir; |
| 168 | INC(numInc); |
| 169 | end; |
| 170 | |
| 171 | (* The driver's user library directories, kept until compilation ends *) |
| 172 | proc setUserDirs*(dirs: [][]const U8); |
| 173 | begin |
| 174 | userDirs := dirs; |
| 175 | end; |
| 176 | |
| 177 | (* The target's operating system and machine, as the suffixes of a |
| 178 | module's files say them: Exe.Os and Gen.Arch, which the driver gives *) |
| 179 | proc setTarget*(os, arch: []const U8); |
| 180 | begin |
| 181 | targetOs := os; |
| 182 | targetArch := arch; |
| 183 | end; |
| 184 | |
| 185 | (* The driver's version of the compiler, which a library's note names *) |
| 186 | proc setVersion*(v: []const U8); |
| 187 | begin |
| 188 | thisVersion := v; |
| 189 | end; |
| 190 | |
| 191 | (* raz -q def, not words: the cursor asks where its name is declared *) |
| 192 | proc setDefine*(yes: BOOL); |
| 193 | begin |
| 194 | define := yes; |
| 195 | end; |
| 196 | |
| 197 | proc nameOf(n: INT): []const U8; |
| 198 | begin |
| 199 | return Scan.nameOf(n); |
| 200 | end; |
| 201 | |
| 202 | (* The name number of s, which isn't empty *) |
| 203 | proc internName(s: []const U8): INT; |
| 204 | begin |
| 205 | return Scan.intern(SYSTEM.PTR(s), LEN(s)); |
| 206 | end; |
| 207 | |
| 208 | proc say1(f, a: []const U8): []const U8; |
| 209 | begin |
| 210 | return Diag.say(f, [Fmt.str(a)]); |
| 211 | end; |
| 212 | |
| 213 | proc say2(f, a, b: []const U8): []const U8; |
| 214 | begin |
| 215 | return Diag.say(f, [Fmt.str(a), Fmt.str(b)]); |
| 216 | end; |
| 217 | |
| 218 | proc say3(f, a, b, c: []const U8): []const U8; |
| 219 | begin |
| 220 | return Diag.say(f, [Fmt.str(a), Fmt.str(b), Fmt.str(c)]); |
| 221 | end; |
| 222 | |
| 223 | (* More than n of what, as a message *) |
| 224 | proc tooMany(n: INT; what: []const U8): []const U8; |
| 225 | begin |
| 226 | return Diag.say("more than {} {}", [Fmt.int(n), Fmt.str(what)]); |
| 227 | end; |
| 228 | |
| 229 | (* The error for a statement or an expression nested too deep: the parser calls itself |
| 230 | for each level, so its depth is bounded to keep the stack well inside 8 MiB *) |
| 231 | proc tooDeep: ERROR; |
| 232 | begin |
| 233 | return Scan.mark(tooMany(MaxNest, "statements, expressions and types nested")); |
| 234 | end; |
| 235 | |
| 236 | (* After an error at p: if a comment closed just before it, it most |
| 237 | likely quoted the characters that end one, and ended early; where it |
| 238 | ended is shown. *) |
| 239 | proc commentNote(p: Diag.Pos); |
| 240 | var closed: Diag.Pos; ok: BOOL; |
| 241 | begin |
| 242 | if p.f # Scan.tokPos().f then return; end; |
| 243 | closed, ok := Scan.commentClosed(p.a); |
| 244 | if ok then |
| 245 | Diag.note(closed, "a comment ended here"); |
| 246 | Diag.help("a comment that quotes *) writes it apart: * )"); |
| 247 | end; |
| 248 | end; |
| 249 | |
| 250 | (* After an error at at about the symbol found: that symbol, if at is |
| 251 | above it with a comment between, as a missing symbol's place may |
| 252 | be (with only blanks between, the two are seen together); and the |
| 253 | comment, if it ended just before the symbol. *) |
| 254 | proc foundNotes(at: Diag.Pos); |
| 255 | begin |
| 256 | if (at.a # Scan.tokPos().a) and Scan.commentBetween() then |
| 257 | Diag.note(Scan.tokPos(), say1("found here: {}", Scan.found())); |
| 258 | end; |
| 259 | commentNote(Scan.tokPos()); |
| 260 | end; |
| 261 | |
| 262 | (* A missing symbol is reported just after the one before it. *) |
| 263 | proc expected(what: []const U8): ERROR; |
| 264 | var at: Diag.Pos; |
| 265 | begin |
| 266 | if Scan.tok = Scan.sBlank then |
| 267 | return Scan.mark("_ isn't a name: it is the blank, which stands only left of :="); |
| 268 | end; |
| 269 | at := Scan.missingPos(); |
| 270 | Diag.error(at, say2("expected {}, found {}", what, Scan.found())); |
| 271 | foundNotes(at); |
| 272 | return Scan.Failed; |
| 273 | end; |
| 274 | |
| 275 | proc expect(s: Scan.Sym): ERROR; |
| 276 | begin |
| 277 | if (Scan.tok = Scan.sLbrace) and ((s = Scan.sThen) or (s = Scan.sDo)) then |
| 278 | return Scan.markHelp(Scan.missingPos(), say2("expected {}, found {}", Scan.symText(s), Scan.found()), |
| 279 | say1("a block is written {} ... end", Scan.symText(s))); |
| 280 | end; |
| 281 | if Scan.tok # s then return expected(Scan.symText(s)); end; |
| 282 | Scan.next; |
| 283 | return nil; |
| 284 | end; |
| 285 | |
| 286 | (* The end of a block statement at start, whose line is indented to |
| 287 | ind. An "end" left of that was most likely meant for a block around |
| 288 | the statement, which leaves the statement's own "end" missing: the |
| 289 | first such is kept for endMissing. *) |
| 290 | proc closeEnd(start: Diag.Pos; ind: INT): ERROR; |
| 291 | begin |
| 292 | if (Scan.tok = Scan.sEnd) and not stray and (Scan.indent() < ind) then |
| 293 | stray := true; |
| 294 | strayAt := start; |
| 295 | end; |
| 296 | return expect(Scan.sEnd); |
| 297 | end; |
| 298 | |
| 299 | (* The error of a procedure or module whose own "end" isn't where it |
| 300 | should be, with what closeEnd saw *) |
| 301 | proc endMissing(p: Diag.Pos; msg: []const U8): ERROR; |
| 302 | begin |
| 303 | Diag.error(p, msg); |
| 304 | foundNotes(p); |
| 305 | if stray then Diag.note(strayAt, "is this statement's \"end\" missing? one further left closes it"); end; |
| 306 | if elseIf then Diag.help("raz writes elsif: \"else if\" begins an if that needs its own \"end\""); end; |
| 307 | return Scan.Failed; |
| 308 | end; |
| 309 | |
| 310 | (* A name being declared, and whether it is exported; at is the name *) |
| 311 | proc identDef(var n: INT; var exp: BOOL; var at: Diag.Pos): ERROR; |
| 312 | begin |
| 313 | if Scan.tok # Scan.sIdent then return expected("a name"); end; |
| 314 | n := Scan.id; |
| 315 | at := Scan.tokPos(); |
| 316 | Scan.next; |
| 317 | exp := false; |
| 318 | if Scan.tok = Scan.sTimes then |
| 319 | exp := true; |
| 320 | Scan.next; |
| 321 | end; |
| 322 | return nil; |
| 323 | end; |
| 324 | |
| 325 | (* Declares o in the innermost scope. Its module keeps its declarations |
| 326 | in order: its own, for the interface check, and its procedures', to |
| 327 | warn of those never used. *) |
| 328 | proc declare(o: PObj): ERROR; |
| 329 | var m: PModule; |
| 330 | begin |
| 331 | m := Sym.curModule; |
| 332 | try Sym.insert(o, Sym.topScope()); |
| 333 | if Sym.topScope() = m^.scope then |
| 334 | if m^.last = nil then m^.first := o; else m^.last^.chain := o; end; |
| 335 | m^.last := o; |
| 336 | else |
| 337 | if m^.lastLocal = nil then m^.locals := o; else m^.lastLocal^.chain := o; end; |
| 338 | m^.lastLocal := o; |
| 339 | end; |
| 340 | return nil; |
| 341 | end; |
| 342 | |
| 343 | (* o is named: a procedure naming itself doesn't count *) |
| 344 | proc named(o: PObj); |
| 345 | begin |
| 346 | if o # curProc then |
| 347 | o^.used := true; |
| 348 | o^.read := true; |
| 349 | end; |
| 350 | end; |
| 351 | |
| 352 | (* Recovery |
| 353 | |
| 354 | After an error the parser goes on with the next statement or |
| 355 | declaration, so that one run reports every error. Each statement and |
| 356 | declaration is a recovery point: it notes the state of the scanner |
| 357 | and the parser where it starts, and when what it read comes back with |
| 358 | an error, the state is put back, the scanner reads the construct |
| 359 | again from its start, skipping to its end, and the parser carries on |
| 360 | after it. Nothing is generated after an error, so the code half made |
| 361 | for the construct does no harm. A name that isn't declared is |
| 362 | declared where it is used, with type tPoison, and what follows from |
| 363 | it is not reported again; so are the names of a declaration that had |
| 364 | an error. |
| 365 | |
| 366 | Skipping counts the words that open and close blocks. A symbol at |
| 367 | the start of a line is taken to start a declaration of the module, |
| 368 | as layout has it: a statement skipped up to one gives up its |
| 369 | procedure, and the procedure is skipped up to its end. *) |
| 370 | |
| 371 | type |
| 372 | Recover = record |
| 373 | scan: Scan.State; |
| 374 | scopes, depth, pushed, numDefers, nest: INT; |
| 375 | guards: INT; |
| 376 | loop: PLoop; |
| 377 | result: PType; |
| 378 | deferring, directDefer, quiet: BOOL; |
| 379 | end; |
| 380 | |
| 381 | proc guard(var r: Recover); |
| 382 | begin |
| 383 | Scan.saveScan(r.scan); |
| 384 | r.guards := guards; |
| 385 | r.scopes := Sym.scopeDepth(); r.depth := Gen.depth; r.pushed := Gen.pushed; r.numDefers := numDefers; r.nest := nest; |
| 386 | r.loop := curLoop; r.result := curResult; |
| 387 | r.deferring := deferring; r.directDefer := directDefer; r.quiet := Diag.quiet; |
| 388 | INC(guards); |
| 389 | Diag.setQuiet(false); |
| 390 | end; |
| 391 | |
| 392 | proc unguard(var r: Recover); |
| 393 | begin |
| 394 | guards := r.guards; |
| 395 | Diag.setQuiet(r.quiet); |
| 396 | Scan.setSkipping(false); |
| 397 | end; |
| 398 | |
| 399 | (* After an error: the state as it was at the start of r's construct, |
| 400 | whose first symbol is again the current one *) |
| 401 | proc restore(var r: Recover); |
| 402 | begin |
| 403 | Scan.restoreScan(r.scan); |
| 404 | Scan.setSkipping(true); |
| 405 | Sym.cutScopes(r.scopes); |
| 406 | Gen.resetStack(r.depth, r.pushed); |
| 407 | numDefers := r.numDefers; nest := r.nest; |
| 408 | curLoop := r.loop; curResult := r.result; |
| 409 | deferring := r.deferring; directDefer := r.directDefer; |
| 410 | inTypes := false; declExported := false; inExtern := false; making := false; |
| 411 | end; |
| 412 | |
| 413 | (* Gives up the construct r is for, and the one around it: the error |
| 414 | goes on up to the next recovery point, or ends the compile if there |
| 415 | is none *) |
| 416 | proc giveUp(var r: Recover): ERROR; |
| 417 | begin |
| 418 | unguard(r); |
| 419 | if guards = 0 then Diag.finish(); end; |
| 420 | return Scan.Failed; |
| 421 | end; |
| 422 | |
| 423 | (* Reads to the end of a statement or declaration, from its first |
| 424 | symbol: up to the ";" that ends it, not read, or to the "end", |
| 425 | "else", "elsif", "until" or "|" of the statement around it (an arm's |
| 426 | "|" comes after a ";", the operator's after an operand). False if it |
| 427 | stopped at a symbol that starts a line, or the end of the file. *) |
| 428 | proc skipConstruct: BOOL; |
| 429 | var d, p: INT; prev: Scan.Sym; |
| 430 | begin |
| 431 | d := 0; p := 0; prev := Scan.sSemicolon; |
| 432 | repeat |
| 433 | match Scan.tok of |
| 434 | | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d); |
| 435 | | sEnd, sUntil: |
| 436 | if d = 0 then return true; end; |
| 437 | DEC(d); |
| 438 | | sElse, sElsif: if (d = 0) and (p = 0) then return true; end; |
| 439 | | sBar: if (d = 0) and (p = 0) and (prev = Scan.sSemicolon) then return true; end; |
| 440 | | sLparen, sLbrak, sLbrace: INC(p); |
| 441 | | sRparen, sRbrak, sRbrace: if p > 0 then DEC(p); end; |
| 442 | | sSemicolon: if (d = 0) and (p = 0) then return true; end; |
| 443 | | sEof: return false; |
| 444 | | else: |
| 445 | end; |
| 446 | prev := Scan.tok; |
| 447 | Scan.next; |
| 448 | until Scan.atLineStart(); |
| 449 | return false; |
| 450 | end; |
| 451 | |
| 452 | (* Declares n where it is used, after it was reported as not declared, |
| 453 | or after the declaration of it had an error *) |
| 454 | proc poison(n: INT); |
| 455 | var o: PObj; |
| 456 | begin |
| 457 | o := Sym.newObj(Sym.oConst, n, Sym.tPoison); |
| 458 | _ := Sym.insert(o, Sym.topScope()); (* n isn't in this scope, so it can't be twice *) |
| 459 | end; |
| 460 | |
| 461 | proc willDeclare(n: INT); |
| 462 | begin |
| 463 | if numDeclaring < MaxNames then declaring[numDeclaring] := n; end; |
| 464 | INC(numDeclaring); |
| 465 | end; |
| 466 | |
| 467 | (* After a declaration had an error: its names are poison, and reading |
| 468 | goes on after it *) |
| 469 | proc skipDeclaration; |
| 470 | var i: INT; |
| 471 | begin |
| 472 | for i := 0 to numDeclaring - 1 do |
| 473 | if (i < MaxNames) and (Sym.find(Sym.topScope(), declaring[i]) = nil) then |
| 474 | poison(declaring[i]); |
| 475 | end; |
| 476 | end; |
| 477 | if skipConstruct() and (Scan.tok = Scan.sSemicolon) then Scan.next; end; |
| 478 | end; |
| 479 | |
| 480 | proc constValue(var x: TItem): (I64, ERROR); |
| 481 | begin |
| 482 | if x.mode # Item.mConst then return 0, Scan.markAt(x.pos, "expected a constant"); end; |
| 483 | return x.val, nil; |
| 484 | end; |
| 485 | |
| 486 | proc constExpr: (I64, ERROR); |
| 487 | var x: TItem; |
| 488 | begin |
| 489 | try expression(x, nil); |
| 490 | if not Sym.isInt(x.typ) then |
| 491 | return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x))); |
| 492 | end; |
| 493 | return constValue(x); |
| 494 | end; |
| 495 | |
| 496 | (* Help after a name that isn't found: o, the closest name in reach *) |
| 497 | proc didYouMean(o: PObj); |
| 498 | begin |
| 499 | if o # nil then Diag.help(say1("did you mean {}?", nameOf(o^.name))); end; |
| 500 | end; |
| 501 | |
| 502 | (* Where module n is found, if it is: dir and the file in it *) |
| 503 | proc moduleFile(n: INT): ([]const U8, []const U8, BOOL); forward; |
| 504 | |
| 505 | (* name in lower case, in memory that is never freed, as messages are *) |
| 506 | proc lowerCase(s: []const U8): []const U8; |
| 507 | var p: ^U8; i: INT; |
| 508 | begin |
| 509 | if LEN(s) = 0 then return ""; end; |
| 510 | p := Scan.grab(LEN(s)); |
| 511 | for i := 0 to LEN(s) - 1 do |
| 512 | if (s[i] >= 'A') and (s[i] <= 'Z') then p[i] := s[i] + 32; else p[i] := s[i]; end; |
| 513 | end; |
| 514 | return p[0..LEN(s)]; |
| 515 | end; |
| 516 | |
| 517 | (* Whether s is a hexadecimal number but for the digit it must start |
| 518 | with, as FFFDH is: capitals A to F and digits, then H *) |
| 519 | proc hexLike(s: []const U8): BOOL; |
| 520 | var i: INT; |
| 521 | begin |
| 522 | if (LEN(s) < 2) or (s[LEN(s) - 1] # 'H') then return false; end; |
| 523 | for i := 0 to LEN(s) - 2 do |
| 524 | if (Str.hexVal(s[i]) < 0) or (s[i] >= 'a') then return false; end; |
| 525 | end; |
| 526 | return true; |
| 527 | end; |
| 528 | |
| 529 | (* Reports name n at p as not declared, with what it may have meant *) |
| 530 | proc notDeclared(p: Diag.Pos; n: INT); |
| 531 | var found: BOOL; low: []const U8; |
| 532 | begin |
| 533 | Diag.error(p, say1("{} isn't declared", nameOf(n))); |
| 534 | commentNote(p); |
| 535 | _, _, found := moduleFile(n); |
| 536 | low := lowerCase(nameOf(n)); |
| 537 | if found then Diag.help(say2("{} is a module: import {}", nameOf(n), nameOf(n))); |
| 538 | elsif (nameOf(n) = "elif") or (nameOf(n) = "elseif") then Diag.help("raz writes elsif"); |
| 539 | elsif Scan.reserved(internName(low)) then Diag.help(say1("a reserved word is written in lower case: {}", low)); |
| 540 | elsif hexLike(nameOf(n)) then Diag.help(say1("a hexadecimal number starts with a digit: 0{}", nameOf(n))); |
| 541 | else didYouMean(Sym.closest(n, -1)); |
| 542 | end; |
| 543 | end; |
| 544 | |
| 545 | proc firstUse(o: PObj; at: Diag.Pos): ERROR; forward; |
| 546 | proc instancesFor(wholeRest: BOOL): ERROR; forward; |
| 547 | proc addImport(m, im: PModule); forward; |
| 548 | |
| 549 | (* The name of the enumeration t that the current symbol is, after |
| 550 | "t.": Elem.bold (report section 5.7). *) |
| 551 | proc enumName(t: PType): (PObj, ERROR); |
| 552 | var o: PObj; |
| 553 | begin |
| 554 | if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; |
| 555 | o := t^.fields; |
| 556 | while (o # nil) and (o^.name # Scan.id) do o := o^.next; end; |
| 557 | if o = nil then |
| 558 | return nil, Scan.mark(say2("{} has no name {}", Sym.typeName(t), nameOf(Scan.id))); |
| 559 | end; |
| 560 | Scan.next; |
| 561 | return o, nil; |
| 562 | end; |
| 563 | |
| 564 | (* An error at at: o, a name of an enumeration, is a name of another of |
| 565 | its scope too, so it is written with its type. *) |
| 566 | proc twinError(o: PObj; at: Diag.Pos): ERROR; |
| 567 | var a, b: []const U8; |
| 568 | begin |
| 569 | a := Sym.typeName(o^.typ); b := Sym.typeName(o^.twin^.typ); |
| 570 | return Scan.markHelp(at, Diag.say("{} is a name of {} and of {}", |
| 571 | [Fmt.str(nameOf(o^.name)), Fmt.str(a), Fmt.str(b)]), |
| 572 | Diag.say("write it with its type: {}.{} or {}.{}", |
| 573 | [Fmt.str(a), Fmt.str(nameOf(o^.name)), Fmt.str(b), Fmt.str(nameOf(o^.name))])); |
| 574 | end; |
| 575 | |
| 576 | (* raz -q words or def: the current symbol is the cursor, where a name |
| 577 | of scope s is written, or of any scope open if s < 0. words writes |
| 578 | the names that start with what is typed there; def where the name |
| 579 | written there is declared, its place and what it is: a module's |
| 580 | place is its name in its own file, and the language's own names |
| 581 | have none. Then the compile ends. *) |
| 582 | proc answer(s: INT); |
| 583 | var b: Buf.Buf; o: PObj; |
| 584 | begin |
| 585 | Buf.init(b, Heap.heap); |
| 586 | if not define then |
| 587 | Sym.offer(s, Scan.prefix, b); |
| 588 | else |
| 589 | if s < 0 then o := Sym.lookup(internName(Scan.word)); else o := Sym.find(s, internName(Scan.word)); end; |
| 590 | if (o # nil) and (o^.typ # Sym.tPoison) then |
| 591 | if (o^.cls = Sym.oModule) and (o^.home # nil) and (o^.home^.path # "") then |
| 592 | Diag.writePlace(b, o^.home^.at); |
| 593 | elsif (o^.scope = 0) or (o^.cls = Sym.oBuiltin) then |
| 594 | Diag.writePlace(b, {f: MAX(INT), a: 0, b: 0}); |
| 595 | else |
| 596 | Diag.writePlace(b, o^.pos); |
| 597 | end; |
| 598 | Buf.add(b, '\t'); |
| 599 | Sym.describe(o, b); |
| 600 | Buf.add(b, '\n'); |
| 601 | end; |
| 602 | end; |
| 603 | Out.str(Buf.bytes(b)); |
| 604 | Out.flush(); |
| 605 | Rt.exit(0); |
| 606 | end; |
| 607 | |
| 608 | proc qualIdent: (PObj, ERROR); |
| 609 | var o: PObj; m: PModule; at: Diag.Pos; |
| 610 | begin |
| 611 | if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; |
| 612 | if Scan.id = Scan.atCursor then answer(-1); end; |
| 613 | at := Scan.tokPos(); |
| 614 | o := Sym.lookup(Scan.id); |
| 615 | if o = nil then |
| 616 | if not making then poison(Scan.id); end; (* it may yet be declared *) |
| 617 | Diag.setQuiet(false); |
| 618 | notDeclared(at, Scan.id); |
| 619 | if making then Diag.note(useAt, "the instance is made here, where it is first used"); end; |
| 620 | return nil, Scan.Failed; |
| 621 | end; |
| 622 | if o^.typ = Sym.tPoison then Diag.setQuiet(true); end; |
| 623 | named(o); |
| 624 | Scan.next; |
| 625 | if o^.cls = Sym.oModule then |
| 626 | if o^.home = nil then try firstUse(o, at); end; |
| 627 | try expect(Scan.sPeriod); |
| 628 | if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; |
| 629 | m := o^.home; |
| 630 | if Scan.id = Scan.atCursor then answer(m^.scope); end; |
| 631 | o := Sym.find(m^.scope, Scan.id); |
| 632 | if (o = nil) or not o^.exported then |
| 633 | Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name))); |
| 634 | if o # nil then Diag.note(o^.pos, say1("{} is declared here, without a *", nameOf(Scan.id))); |
| 635 | else didYouMean(Sym.closest(Scan.id, m^.scope)); |
| 636 | end; |
| 637 | return nil, Scan.Failed; |
| 638 | end; |
| 639 | Scan.next; |
| 640 | end; |
| 641 | if (o^.cls = Sym.oType) and (o^.typ^.form = Sym.fEnum) and (Scan.tok = Scan.sPeriod) then |
| 642 | Scan.next; |
| 643 | o := try enumName(o^.typ); |
| 644 | elsif o^.twin # nil then |
| 645 | return nil, twinError(o, at); |
| 646 | end; |
| 647 | return o, nil; |
| 648 | end; |
| 649 | |
| 650 | (* The field of record type t named by the current symbol *) |
| 651 | proc fieldOf(t: PType): (PObj, ERROR); |
| 652 | var f: PObj; |
| 653 | begin |
| 654 | f := Sym.find(t^.scope, Scan.id); |
| 655 | if f = nil then |
| 656 | Diag.error(Scan.tokPos(), say2("{} has no field {}", Sym.typeName(t), nameOf(Scan.id))); |
| 657 | didYouMean(Sym.closest(Scan.id, t^.scope)); |
| 658 | return nil, Scan.Failed; |
| 659 | end; |
| 660 | if not f^.exported and (t^.home # Sym.curModule) then |
| 661 | Diag.error(Scan.tokPos(), say2("field {} of {} isn't exported", nameOf(Scan.id), Sym.typeName(t))); |
| 662 | Diag.note(f^.pos, say1("{} is declared here, without a *", nameOf(Scan.id))); |
| 663 | return nil, Scan.Failed; |
| 664 | end; |
| 665 | return f, nil; |
| 666 | end; |
| 667 | |
| 668 | proc newPtr(base: PType; vol: BOOL): PType; |
| 669 | var t: PType; |
| 670 | begin |
| 671 | t := Sym.newType(Sym.fPtr, 8, 8); |
| 672 | t^.base := base; |
| 673 | t^.vol := vol; |
| 674 | return t; |
| 675 | end; |
| 676 | |
| 677 | (* Types *) |
| 678 | |
| 679 | (* Lays the results t holds out as C would, each field at its offset; |
| 680 | again by resolveLaters, if one names a type declared later. *) |
| 681 | proc layOut(t: PType); |
| 682 | var f: PObj; off: I64; |
| 683 | begin |
| 684 | off := 0; |
| 685 | t^.align := 1; |
| 686 | f := t^.fields; |
| 687 | while f # nil do |
| 688 | off := Sym.alignUp(off, f^.typ^.align); |
| 689 | f^.val := off; |
| 690 | off := off + f^.typ^.size; |
| 691 | if f^.typ^.align > t^.align then t^.align := f^.typ^.align; end; |
| 692 | f := f^.next; |
| 693 | end; |
| 694 | t^.size := Sym.alignUp(off, t^.align); |
| 695 | end; |
| 696 | |
| 697 | (* A type that owner, a pointer or a procedure type, holds. In a type |
| 698 | section it may name a type not declared yet (report, 4): a |
| 699 | placeholder of its own stands for it, noted in laters, and |
| 700 | resolveLaters puts the type in its place at the section's end. A |
| 701 | pointer is a word and a procedure value an address, so neither's |
| 702 | size waits for it. *) |
| 703 | proc laterType(owner: PType): (PType, ERROR); |
| 704 | var held: PType; |
| 705 | begin |
| 706 | if not inTypes or (Scan.tok # Scan.sIdent) or (Sym.lookup(Scan.id) # nil) then return parseType(); end; |
| 707 | if numLater >= MaxLater then return nil, Scan.mark(tooMany(MaxLater, "types named before they are declared")); end; |
| 708 | held := Sym.newType(Sym.fNone, 0, 1); |
| 709 | laters[numLater].name := Scan.id; |
| 710 | laters[numLater].at := Scan.tokPos(); |
| 711 | laters[numLater].held := held; |
| 712 | laters[numLater].owner := owner; |
| 713 | INC(numLater); |
| 714 | Scan.next; |
| 715 | return held, nil; |
| 716 | end; |
| 717 | |
| 718 | (* Gives t to each of the list f whose type is the placeholder held *) |
| 719 | proc putFor(f: PObj; held, t: PType); |
| 720 | begin |
| 721 | while f # nil do |
| 722 | if f^.typ = held then f^.typ := t; end; |
| 723 | f := f^.next; |
| 724 | end; |
| 725 | end; |
| 726 | |
| 727 | (* Puts in place of each placeholder of laters the type it names, now |
| 728 | that the type section is read: in a pointer's base, a procedure |
| 729 | type's parameters and result, and its results, laid out again as |
| 730 | their sizes are now known. A name that isn't a type is poison. *) |
| 731 | proc resolveLaters; |
| 732 | var i: INT; o: PObj; held, t, owner: PType; |
| 733 | begin |
| 734 | for i := 0 to numLater - 1 do |
| 735 | held := laters[i].held; |
| 736 | owner := laters[i].owner; |
| 737 | o := Sym.lookup(laters[i].name); |
| 738 | if (o # nil) and (o^.typ = Sym.tPoison) then |
| 739 | t := Sym.tPoison; (* its declaration had an error, told already *) |
| 740 | elsif (o = nil) or (o^.cls # Sym.oType) then |
| 741 | notDeclared(laters[i].at, laters[i].name); |
| 742 | t := Sym.tPoison; |
| 743 | else |
| 744 | t := o^.typ; |
| 745 | named(o); |
| 746 | end; |
| 747 | if owner^.base = held then owner^.base := t; end; |
| 748 | if owner^.form = Sym.fProc then |
| 749 | putFor(owner^.fields, held, t); |
| 750 | if (owner^.base # nil) and owner^.base^.tuple then |
| 751 | putFor(owner^.base^.fields, held, t); |
| 752 | layOut(owner^.base); |
| 753 | end; |
| 754 | end; |
| 755 | end; |
| 756 | numLater := 0; |
| 757 | end; |
| 758 | |
| 759 | proc recordType: (PType, ERROR); |
| 760 | var |
| 761 | t, ft: PType; f, last: PObj; names: [MaxNames]INT; |
| 762 | exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos; |
| 763 | n, i: INT; off, a, maxA: I64; |
| 764 | begin |
| 765 | t := Sym.newType(Sym.fRecord, 0, 1); |
| 766 | if Scan.tok = Scan.sPacked then t^.packd := true; Scan.next; end; |
| 767 | try expect(Scan.sRecord); |
| 768 | t^.scope := Sym.newScope(); |
| 769 | off := 0; maxA := 1; last := nil; |
| 770 | while Scan.tok = Scan.sIdent do |
| 771 | n := 0; |
| 772 | repeat |
| 773 | if n >= MaxNames then return nil, Scan.mark(tooMany(MaxNames, "names in one declaration")); end; |
| 774 | try identDef(names[n], exps[n], poss[n]); |
| 775 | INC(n); |
| 776 | if Scan.tok # Scan.sComma then break; end; |
| 777 | Scan.next; |
| 778 | until false; |
| 779 | try expect(Scan.sColon); |
| 780 | ft := try parseType(); |
| 781 | if t^.packd then a := 1; else a := ft^.align; end; |
| 782 | for i := 0 to n - 1 do |
| 783 | off := Sym.alignUp(off, a); |
| 784 | f := Sym.newObj(Sym.oField, names[i], ft); |
| 785 | f^.exported := exps[i]; |
| 786 | f^.pos := poss[i]; |
| 787 | f^.val := off; |
| 788 | try Sym.insert(f, t^.scope); |
| 789 | if last = nil then t^.fields := f; else last^.next := f; end; |
| 790 | last := f; |
| 791 | off := off + ft^.size; |
| 792 | end; |
| 793 | if a > maxA then maxA := a; end; |
| 794 | try expect(Scan.sSemicolon); |
| 795 | end; |
| 796 | try expect(Scan.sEnd); |
| 797 | t^.align := maxA; |
| 798 | t^.size := Sym.alignUp(off, maxA); |
| 799 | return t, nil; |
| 800 | end; |
| 801 | |
| 802 | proc variantType: (PType, ERROR); |
| 803 | var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: I64; |
| 804 | begin |
| 805 | try expect(Scan.sVariant); |
| 806 | t := Sym.newType(Sym.fVariant, 8, 8); |
| 807 | tag := 0; maxSize := 8; lastC := nil; |
| 808 | while Scan.tok = Scan.sIdent do |
| 809 | c := Sym.newObj(Sym.oCase, Scan.id, t); |
| 810 | c^.val := tag; |
| 811 | c^.exported := declExported; |
| 812 | try declare(c); |
| 813 | if lastC = nil then t^.fields := c; else lastC^.next := c; end; |
| 814 | lastC := c; |
| 815 | Scan.next; |
| 816 | off := 8; |
| 817 | if Scan.tok = Scan.sLparen then |
| 818 | Scan.next; |
| 819 | lastF := nil; |
| 820 | repeat |
| 821 | repeat |
| 822 | if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; |
| 823 | f := Sym.newObj(Sym.oField, Scan.id, nil); |
| 824 | f^.exported := true; |
| 825 | if lastF = nil then c^.fields := f; else lastF^.next := f; end; |
| 826 | lastF := f; |
| 827 | Scan.next; |
| 828 | if Scan.tok # Scan.sComma then break; end; |
| 829 | Scan.next; |
| 830 | until false; |
| 831 | try expect(Scan.sColon); |
| 832 | ft := try parseType(); |
| 833 | f := c^.fields; |
| 834 | while f^.typ # nil do f := f^.next; end; |
| 835 | while f # nil do |
| 836 | f^.typ := ft; |
| 837 | off := Sym.alignUp(off, ft^.align); |
| 838 | f^.val := off; |
| 839 | off := off + ft^.size; |
| 840 | f := f^.next; |
| 841 | end; |
| 842 | if ft^.align > t^.align then t^.align := ft^.align; end; |
| 843 | if Scan.tok # Scan.sSemicolon then break; end; |
| 844 | Scan.next; |
| 845 | until false; |
| 846 | try expect(Scan.sRparen); |
| 847 | end; |
| 848 | if off > maxSize then maxSize := off; end; |
| 849 | try expect(Scan.sSemicolon); |
| 850 | INC(tag); |
| 851 | end; |
| 852 | try expect(Scan.sEnd); |
| 853 | t^.len := tag; |
| 854 | t^.size := Sym.alignUp(maxSize, t^.align); |
| 855 | return t, nil; |
| 856 | end; |
| 857 | |
| 858 | (* The results of the procedure type sig: a record of them, laid out |
| 859 | as C would, and returned in rax and rdx if they are two words |
| 860 | (inTwoRegs), or else through a hidden pointer. One alone in |
| 861 | parentheses is the result itself. *) |
| 862 | proc results(sig: PType): (PType, ERROR); |
| 863 | var t: PType; f, last: PObj; |
| 864 | begin |
| 865 | Scan.next; |
| 866 | t := Sym.newType(Sym.fRecord, 0, 1); |
| 867 | t^.tuple := true; |
| 868 | last := nil; |
| 869 | repeat |
| 870 | f := Sym.newObj(Sym.oField, -1, try laterType(sig)); |
| 871 | if last = nil then t^.fields := f; else last^.next := f; end; |
| 872 | last := f; |
| 873 | INC(t^.len); |
| 874 | if Scan.tok # Scan.sComma then break; end; |
| 875 | Scan.next; |
| 876 | until false; |
| 877 | try expect(Scan.sRparen); |
| 878 | if t^.len = 1 then return t^.fields^.typ, nil; end; |
| 879 | layOut(t); |
| 880 | return t, nil; |
| 881 | end; |
| 882 | |
| 883 | proc signature: (PType, ERROR); |
| 884 | var |
| 885 | t, pt: PType; p, first, last: PObj; isVar, isConst: BOOL; n: INT; |
| 886 | begin |
| 887 | t := Sym.newType(Sym.fProc, 8, 8); |
| 888 | last := nil; n := 0; |
| 889 | if Scan.tok = Scan.sLparen then |
| 890 | Scan.next; |
| 891 | if Scan.tok # Scan.sRparen then |
| 892 | repeat |
| 893 | if Scan.tok = Scan.sEllipsis then |
| 894 | if not inExtern then return nil, Scan.mark("... is only for extern procedures"); end; |
| 895 | Scan.next; t^.variadic := true; break; |
| 896 | end; |
| 897 | isVar := Scan.tok = Scan.sVar; |
| 898 | isConst := Scan.tok = Scan.sConst; |
| 899 | if isVar or isConst then Scan.next; end; |
| 900 | first := nil; |
| 901 | repeat |
| 902 | if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; |
| 903 | p := Sym.newObj(Sym.oVar, Scan.id, nil); |
| 904 | (* a const parameter goes by address, as a var one *) |
| 905 | p^.isVar := isVar or isConst; |
| 906 | p^.isConst := isConst; |
| 907 | p^.lev := 1; |
| 908 | if last = nil then t^.fields := p; else last^.next := p; end; |
| 909 | last := p; |
| 910 | if first = nil then first := p; end; |
| 911 | INC(n); |
| 912 | Scan.next; |
| 913 | if Scan.tok # Scan.sComma then break; end; |
| 914 | Scan.next; |
| 915 | until false; |
| 916 | try expect(Scan.sColon); |
| 917 | pt := try laterType(t); |
| 918 | while first # nil do first^.typ := pt; first := first^.next; end; |
| 919 | if Scan.tok # Scan.sSemicolon then break; end; |
| 920 | Scan.next; |
| 921 | until false; |
| 922 | end; |
| 923 | try expect(Scan.sRparen); |
| 924 | end; |
| 925 | t^.len := n; |
| 926 | if Scan.tok = Scan.sColon then |
| 927 | Scan.next; |
| 928 | if Scan.tok = Scan.sLparen then t^.base := try results(t); else t^.base := try laterType(t); end; |
| 929 | end; |
| 930 | return t, nil; |
| 931 | end; |
| 932 | |
| 933 | proc enumType: (PType, ERROR); |
| 934 | var t: PType; o, last: PObj; start: Diag.Pos; |
| 935 | begin |
| 936 | start := Scan.tokPos(); |
| 937 | t := Sym.newType(Sym.fEnum, 1, 1); |
| 938 | last := nil; |
| 939 | repeat |
| 940 | Scan.next; |
| 941 | if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; |
| 942 | o := Sym.newObj(Sym.oConst, Scan.id, t); |
| 943 | o^.val := t^.len; |
| 944 | o^.ofEnum := true; |
| 945 | o^.exported := declExported; |
| 946 | o^.used := true; (* an enumeration's names are its type's, warned of with it *) |
| 947 | try declare(o); |
| 948 | if last = nil then t^.fields := o; else last^.next := o; end; |
| 949 | last := o; |
| 950 | INC(t^.len); |
| 951 | Scan.next; |
| 952 | until Scan.tok # Scan.sComma; |
| 953 | try expect(Scan.sRparen); |
| 954 | if t^.len > 256 then return nil, Scan.markAt(Scan.spanFrom(start), "an enumeration has at most 256 names"); end; |
| 955 | return t, nil; |
| 956 | end; |
| 957 | |
| 958 | proc setOf(e: PType; at: Diag.Pos): (PType, ERROR); |
| 959 | var t: PType; |
| 960 | begin |
| 961 | if (e^.form # Sym.fEnum) or (e^.len > 64) then |
| 962 | return nil, Scan.markAt(at, say1("a set needs an enumeration of at most 64 names, found {}", Sym.typeName(e))); |
| 963 | end; |
| 964 | t := Sym.newType(Sym.fSet, 8, 8); |
| 965 | if e^.len <= 8 then t^.size := 1; |
| 966 | elsif e^.len <= 16 then t^.size := 2; |
| 967 | elsif e^.len <= 32 then t^.size := 4; |
| 968 | end; |
| 969 | t^.align := t^.size; |
| 970 | t^.base := e; |
| 971 | t^.len := e^.len; |
| 972 | return t, nil; |
| 973 | end; |
| 974 | |
| 975 | (* A type, read as typeBody does, counted as one more level of nesting, so that |
| 976 | a type of types of types ... can't overflow the stack *) |
| 977 | proc parseType: (PType, ERROR); |
| 978 | var t: PType; err: ERROR; |
| 979 | begin |
| 980 | INC(nest); |
| 981 | if nest > MaxNest then return nil, tooDeep(); end; |
| 982 | t, err := typeBody(); |
| 983 | DEC(nest); |
| 984 | return t, err; |
| 985 | end; |
| 986 | |
| 987 | proc typeBody: (PType, ERROR); |
| 988 | var t: PType; o: PObj; n: I64; vol: BOOL; start: Diag.Pos; |
| 989 | begin |
| 990 | start := Scan.tokPos(); |
| 991 | match Scan.tok of |
| 992 | | sIdent: |
| 993 | o := try qualIdent(); |
| 994 | if o^.cls # Sym.oType then |
| 995 | return nil, Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type", nameOf(o^.name))); |
| 996 | end; |
| 997 | t := o^.typ; |
| 998 | | sLbrak: |
| 999 | Scan.next; |
| 1000 | if Scan.tok = Scan.sRbrak then |
| 1001 | Scan.next; |
| 1002 | t := Sym.newType(Sym.fSlice, 16, 8); |
| 1003 | if Scan.tok = Scan.sConst then Scan.next; t^.rdonly := true; end; (* []const T *) |
| 1004 | t^.base := try parseType(); |
| 1005 | else |
| 1006 | start := Scan.tokPos(); |
| 1007 | n := try constExpr(); |
| 1008 | if (n <= 0) or (n > (I64(1) shl 40)) then |
| 1009 | return nil, Scan.markAt(Scan.spanFrom(start), Diag.say("an array's length is from 1 to 2^40, found {}", [Fmt.int(n)])); |
| 1010 | end; |
| 1011 | try expect(Scan.sRbrak); |
| 1012 | t := Sym.newType(Sym.fArray, 0, 1); |
| 1013 | t^.len := n; |
| 1014 | t^.base := try parseType(); |
| 1015 | t^.size := n * t^.base^.size; |
| 1016 | t^.align := t^.base^.align; |
| 1017 | end; |
| 1018 | | sArrow: |
| 1019 | Scan.next; |
| 1020 | vol := Scan.tok = Scan.sVolatile; |
| 1021 | if vol then Scan.next; end; |
| 1022 | t := newPtr(nil, vol); |
| 1023 | t^.base := try laterType(t); |
| 1024 | | sPacked, sRecord: t := try recordType(); |
| 1025 | | sVariant: t := try variantType(); |
| 1026 | | sProc: Scan.next; t := try signature(); |
| 1027 | | sLparen: t := try enumType(); |
| 1028 | | sSet: |
| 1029 | Scan.next; |
| 1030 | try expect(Scan.sOf); |
| 1031 | start := Scan.tokPos(); |
| 1032 | t := try setOf(try parseType(), start); |
| 1033 | | else: return nil, expected("a type"); |
| 1034 | end; |
| 1035 | return t, nil; |
| 1036 | end; |
| 1037 | |
| 1038 | (* Expressions *) |
| 1039 | |
| 1040 | (* Inlining a procedure that only returns |
| 1041 | |
| 1042 | A call of a procedure whose body is only return e, with no locals, is |
| 1043 | made in place: e is read again from where it begins, the scanner put |
| 1044 | back there, as a while loop reads its condition again. The arguments, |
| 1045 | read and converted as for a call and left on Gen's stack as the call |
| 1046 | would take them, go to temporaries, the last on top first, so each is |
| 1047 | evaluated once and in order; a scope names the parameters as them. |
| 1048 | e is read in the procedure's own module's scope, with its module's |
| 1049 | checks, so it means what it means there. For |
| 1050 | |
| 1051 | proc isLower(c: U8): BOOL; begin return U8(c - 97) < 26; end; |
| 1052 | ... if isLower(s[i]) then ... |
| 1053 | |
| 1054 | the code was, before, |
| 1055 | |
| 1056 | movzx edi, byte [s + i]; call isLower |
| 1057 | mov r8, rax; movzx r8d, r8b; test r8, r8; je else |
| 1058 | (isLower: push rbp ... cmp r8, 26; setb r8b; movzx r8d, r8b; |
| 1059 | mov rax, r8; leave; ret) |
| 1060 | |
| 1061 | and is now, after, |
| 1062 | |
| 1063 | movzx r8d, byte [s + i]; mov [rbp - t], r8b |
| 1064 | movzx r8d, byte [rbp - t]; sub r8, 97; movzx r8d, r8b |
| 1065 | cmp r8, 26; jae else |
| 1066 | |
| 1067 | A parameter by address (var, const, a record or an array) is a slot |
| 1068 | holding the address the call would have passed (ind), a slice its two |
| 1069 | words, any other its value. A failed check in e is told at e's own |
| 1070 | line, in its own file (Gen's check notes the place while e is read); |
| 1071 | the procedure isn't in the trap report's list, nor in a debugger's |
| 1072 | backtrace, as it has no frame. The procedure itself is still |
| 1073 | compiled, for a call through a procedure value or before its body |
| 1074 | is read. *) |
| 1075 | proc inlined(var c: Gen.CallInfo; var x: TItem): ERROR; |
| 1076 | var |
| 1077 | p: PObj; inl: ^Sym.Inline; q, o: PObj; params: [64]PObj; n, i: INT; t: I64; |
| 1078 | st: Scan.State; saved: [Sym.MaxDepth]INT; d, path, doubts0: INT; home: PModule; |
| 1079 | checks: BOOL; res: PType; err: ERROR; |
| 1080 | begin |
| 1081 | p := c.obj; inl := p^.ret; res := c.sig^.base; |
| 1082 | n := 0; |
| 1083 | q := c.sig^.fields; |
| 1084 | while q # nil do |
| 1085 | o := Sym.newObj(Sym.oVar, q^.name, q^.typ); |
| 1086 | o^.pos := q^.pos; o^.lev := 1; o^.param := true; |
| 1087 | o^.isVar := q^.isVar; o^.isConst := q^.isConst; |
| 1088 | params[n] := o; |
| 1089 | INC(n); |
| 1090 | q := q^.next; |
| 1091 | end; |
| 1092 | for i := n - 1 to 0 by -1 do |
| 1093 | o := params[i]; |
| 1094 | if o^.isVar or (Sym.isAggregate(o^.typ) and (o^.typ^.form # Sym.fSlice)) then |
| 1095 | t := Gen.allocTemp(8, 8); |
| 1096 | Gen.popVar(Item.frameAdr(t), 8); |
| 1097 | o^.ind := true; |
| 1098 | elsif o^.typ^.form = Sym.fSlice then |
| 1099 | t := Gen.allocTemp(16, 8); |
| 1100 | Gen.popVar(Item.frameAdr(t + 8), 8); (* the length, on top *) |
| 1101 | Gen.popVar(Item.frameAdr(t), 8); |
| 1102 | else |
| 1103 | t := Gen.allocTemp(o^.typ^.size, o^.typ^.align); |
| 1104 | Gen.popVar(Item.frameAdr(t), Item.scalarSize(o^.typ)); |
| 1105 | end; |
| 1106 | o^.val := t; |
| 1107 | end; |
| 1108 | (* e in the procedure's module, and back; what it notes for warnings |
| 1109 | was noted when the procedure was compiled *) |
| 1110 | Scan.saveScan(st); |
| 1111 | d := Sym.saveScopes(saved[0..Sym.MaxDepth]); |
| 1112 | home := Sym.curModule; path := Chunk.curFilePath(); checks := Item.checks; doubts0 := numDoubts; |
| 1113 | Sym.setCurModule(p^.home); Chunk.setCurFile(inl^.path); Item.setChecks(inl^.checks); |
| 1114 | err := Sym.openScope(p^.home^.scope); |
| 1115 | if err = nil then err := Sym.openScope(Sym.newScope()); end; |
| 1116 | for i := 0 to n - 1 do |
| 1117 | if err = nil then err := Sym.insert(params[i], Sym.topScope()); end; |
| 1118 | end; |
| 1119 | Scan.restoreScan(inl^.at); |
| 1120 | Scan.next; (* past the return *) |
| 1121 | inl^.busy := true; |
| 1122 | if err = nil then err := expression(x, res); end; |
| 1123 | (* a condition stays one, for if and while to jump on; anything else |
| 1124 | is loaded, as a call's result is, and widens as one does (made) *) |
| 1125 | if (err = nil) and (x.mode # Item.mCond) then |
| 1126 | err := Item.coerce(x, res); |
| 1127 | if err = nil then err := Item.value(x); end; |
| 1128 | x.made := false; |
| 1129 | end; |
| 1130 | inl^.busy := false; |
| 1131 | numDoubts := doubts0; |
| 1132 | Sym.setCurModule(home); Chunk.setCurFile(path); Item.setChecks(checks); |
| 1133 | Sym.restoreScopes(d, saved[0..Sym.MaxDepth]); |
| 1134 | Scan.restoreScan(st); |
| 1135 | return err; |
| 1136 | end; |
| 1137 | |
| 1138 | proc call(var x: TItem): ERROR; |
| 1139 | var c: Gen.CallInfo; a: TItem; want: PType; |
| 1140 | begin |
| 1141 | try Item.beginCall(c, x); |
| 1142 | try expect(Scan.sLparen); |
| 1143 | if Scan.tok # Scan.sRparen then |
| 1144 | repeat |
| 1145 | if c.param # nil then want := c.param^.typ; else want := nil; end; |
| 1146 | try expression(a, want); |
| 1147 | try Item.passArg(c, a); |
| 1148 | if Scan.tok # Scan.sComma then break; end; |
| 1149 | Scan.next; |
| 1150 | until false; |
| 1151 | end; |
| 1152 | try expect(Scan.sRparen); |
| 1153 | if (c.param = nil) and (c.obj # nil) and (c.obj^.ret # nil) and not c.obj^.ret^.busy |
| 1154 | and (Gen.codeChunk >= 0) then |
| 1155 | return inlined(c, x); |
| 1156 | end; |
| 1157 | INC(numCalls); |
| 1158 | return Item.endCall(c, x); |
| 1159 | end; |
| 1160 | |
| 1161 | (* Whether an atomic built-in, which, works on a variable of type t: |
| 1162 | an INT or a UINT, or for CAS and XCHG a pointer *) |
| 1163 | proc atomicType(t: PType; which: INT): BOOL; |
| 1164 | begin |
| 1165 | return Item.isWord(t) or ((t^.form = Sym.fPtr) and (which # Sym.bXadd)); |
| 1166 | end; |
| 1167 | |
| 1168 | (* The name of the atomic built-in which, for a message *) |
| 1169 | proc atomicName(which: INT): []const U8; |
| 1170 | begin |
| 1171 | if which = Sym.bCas then return "CAS"; end; |
| 1172 | if which = Sym.bXchg then return "XCHG"; end; |
| 1173 | return "XADD"; |
| 1174 | end; |
| 1175 | |
| 1176 | (* CAS(v, old, new), XCHG(v, x) or XADD(v, x) (report 6.8): v is a |
| 1177 | variable, whose address goes on the stack, as ADR's would. Before |
| 1178 | report 2026-10.37 they took a pointer to it, ADR(v): the error says |
| 1179 | so. *) |
| 1180 | proc atomic(var x: TItem; which: INT): ERROR; |
| 1181 | var p, a: TItem; t: PType; i, n: INT; |
| 1182 | begin |
| 1183 | try expression(p, nil); |
| 1184 | if (p.mode # Item.mVar) or not p.isVar then |
| 1185 | if p.typ^.form = Sym.fPtr then |
| 1186 | return Scan.markHelp(p.pos, say1("{} takes a variable, not a pointer to it", atomicName(which)), |
| 1187 | "give it the variable itself: XADD(n, 1), or XADD(p^, 1) through a pointer"); |
| 1188 | end; |
| 1189 | return Scan.markAt(p.pos, say1("expected a variable, found {}", Item.what(p))); |
| 1190 | end; |
| 1191 | t := p.typ; |
| 1192 | if not atomicType(t, which) then |
| 1193 | if (t^.form = Sym.fPtr) and atomicType(t^.base, which) then |
| 1194 | return Scan.markHelp(p.pos, say1("{} works on an INT or a UINT variable, not a pointer", atomicName(which)), |
| 1195 | say1("for what the pointer points at, write {}^", Diag.source(p.pos))); |
| 1196 | elsif which = Sym.bXadd then |
| 1197 | return Scan.markAt(p.pos, say1("expected an INT or a UINT variable, found {}", Item.what(p))); |
| 1198 | end; |
| 1199 | return Scan.markAt(p.pos, say1("expected an INT, a UINT or a pointer variable, found {}", Item.what(p))); |
| 1200 | end; |
| 1201 | try Item.notReadOnly(p); |
| 1202 | if p.odd then return Scan.markAt(p.pos, "a field of a packed record has no address"); end; |
| 1203 | if p.view then return Item.noAddress(p, "an atomic can't take a view"); end; |
| 1204 | try Item.address(p); |
| 1205 | if which = Sym.bCas then n := 2; else n := 1; end; |
| 1206 | for i := 1 to n do |
| 1207 | try expect(Scan.sComma); |
| 1208 | try expression(a, t); |
| 1209 | try Item.coerce(a, t); |
| 1210 | try Item.value(a); |
| 1211 | end; |
| 1212 | Gen.atomic(which); |
| 1213 | Item.makeConst(x, t, 0); |
| 1214 | if which = Sym.bCas then x.typ := Sym.tBool; end; |
| 1215 | x.mode := Item.mStack; |
| 1216 | return nil; |
| 1217 | end; |
| 1218 | |
| 1219 | (* NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil. |
| 1220 | a is a ^Mem.Allocator, the one interface the compiler knows. *) |
| 1221 | proc new_(var x: TItem): ERROR; |
| 1222 | var y, z: TItem; t: PType; f: PObj; s: I64; c: Gen.CallInfo; |
| 1223 | begin |
| 1224 | try expression(x, nil); |
| 1225 | try Item.notReadOnly(x); |
| 1226 | if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fPtr) then |
| 1227 | return Scan.markAt(x.pos, "NEW needs a pointer variable"); |
| 1228 | end; |
| 1229 | t := x.typ^.base; |
| 1230 | try expect(Scan.sComma); |
| 1231 | try expression(y, nil); |
| 1232 | if (y.typ^.form # Sym.fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.home = nil) |
| 1233 | or (nameOf(y.typ^.base^.obj^.name) # "Allocator") |
| 1234 | or (nameOf(y.typ^.base^.obj^.home^.name) # "Mem") then |
| 1235 | return Scan.markAt(y.pos, say1("NEW needs a ^Mem.Allocator, found {}", Item.what(y))); |
| 1236 | end; |
| 1237 | f := Sym.find(y.typ^.base^.scope, internName("alloc")); |
| 1238 | s := try Item.toSlot(y); |
| 1239 | Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord); |
| 1240 | Item.makeConst(z, f^.typ, 0); |
| 1241 | z.mode := Item.mVar; z.base := Gen.bStack; z.off := f^.val; |
| 1242 | try Item.beginCall(c, z); |
| 1243 | Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord); |
| 1244 | Item.makeConst(z, y.typ, 0); |
| 1245 | z.mode := Item.mStack; |
| 1246 | try Item.passArg(c, z); |
| 1247 | Item.makeConst(z, Sym.tInt, t^.size); |
| 1248 | try Item.passArg(c, z); |
| 1249 | Item.makeConst(z, Sym.tInt, t^.align); |
| 1250 | try Item.passArg(c, z); |
| 1251 | try Item.endCall(c, z); |
| 1252 | Gen.zeroNew(t^.size); |
| 1253 | z.typ := x.typ; |
| 1254 | try Item.assign(x, z); |
| 1255 | Item.makeConst(x, Sym.tNone, 0); |
| 1256 | x.mode := Item.mNone; |
| 1257 | return nil; |
| 1258 | end; |
| 1259 | |
| 1260 | proc incOrDec(which: INT): []const U8; |
| 1261 | begin |
| 1262 | if which = Sym.bDec then return "DEC"; end; |
| 1263 | return "INC"; |
| 1264 | end; |
| 1265 | |
| 1266 | (* PTR(x): the item x, a slice, an array or a string, made the address |
| 1267 | its elements start at by Item's startOf. Anything else is an error |
| 1268 | that says what PTR is for, and for a pointer what to write. *) |
| 1269 | proc ptrOf(var x: TItem): ERROR; |
| 1270 | var e: PType; s: []const U8; |
| 1271 | begin |
| 1272 | if x.mode = Item.mStr then |
| 1273 | e := Sym.tU8; |
| 1274 | elsif x.typ^.form in {Sym.fSlice, Sym.fArray} then |
| 1275 | e := x.typ^.base; |
| 1276 | else |
| 1277 | s := say1("PTR needs a slice or an array, found {}", Item.what(x)); |
| 1278 | if (x.typ^.form = Sym.fPtr) and (x.typ^.base # nil) and (x.typ^.base^.form = Sym.fArray) then |
| 1279 | return Scan.markHelp(x.pos, s, Diag.say("write PTR({}^) for the address of the array's first element, a ^{}", |
| 1280 | [Fmt.str(Diag.source(x.pos)), Fmt.str(Sym.typeName(x.typ^.base^.base))])); |
| 1281 | elsif x.typ^.form = Sym.fPtr then |
| 1282 | return Scan.markHelp(x.pos, s, say1("{} is a pointer already, which is what PTR gives of a slice or an array", |
| 1283 | Diag.source(x.pos))); |
| 1284 | end; |
| 1285 | return Scan.markAt(x.pos, s); |
| 1286 | end; |
| 1287 | return Item.startOf(x, newPtr(e, false)); |
| 1288 | end; |
| 1289 | |
| 1290 | (* The field f of SIZE(T.f) or OFFSET(T, f), at its name, of the type |
| 1291 | t written at at. T is a record type: a variant's cases share their |
| 1292 | place, so have none of their own. f is one name, not a path a.b, |
| 1293 | which would be a field of f's type, asked of that type. *) |
| 1294 | proc typeField(t: PType; at: Diag.Pos; isOffset: BOOL): (PObj, ERROR); |
| 1295 | var f: PObj; what, s, hint, g: []const U8; dot: Diag.Pos; |
| 1296 | begin |
| 1297 | if isOffset then what := "OFFSET"; else what := "SIZE(T.f)"; end; |
| 1298 | if t^.form # Sym.fRecord then |
| 1299 | s := say2("{} needs a record type, found {}", what, Sym.typeName(t)); |
| 1300 | if t^.form = Sym.fVariant then |
| 1301 | return nil, Scan.markHelp(at, s, "a variant's cases share one place, so have no offset or size of their own"); |
| 1302 | end; |
| 1303 | return nil, Scan.markAt(at, s); |
| 1304 | end; |
| 1305 | if Scan.tok # Scan.sIdent then return nil, expected("a field"); end; |
| 1306 | f := try fieldOf(t); |
| 1307 | Scan.next; |
| 1308 | if Scan.tok = Scan.sPeriod then |
| 1309 | dot := Scan.tokPos(); |
| 1310 | Scan.next; |
| 1311 | if Scan.tok = Scan.sIdent then g := nameOf(Scan.id); else g := "g"; end; |
| 1312 | if isOffset then |
| 1313 | hint := Diag.say("add the offset within {}'s type: OFFSET({}, {}) + OFFSET({}, {})", |
| 1314 | [Fmt.str(nameOf(f^.name)), Fmt.str(Sym.typeName(t)), Fmt.str(nameOf(f^.name)), |
| 1315 | Fmt.str(Sym.typeName(f^.typ)), Fmt.str(g)]); |
| 1316 | else |
| 1317 | hint := Diag.say("ask {}'s type: SIZE({}.{})", [Fmt.str(nameOf(f^.name)), Fmt.str(Sym.typeName(f^.typ)), Fmt.str(g)]); |
| 1318 | end; |
| 1319 | return nil, Scan.markHelp(dot, say1("{} takes one field name, not a path", what), hint); |
| 1320 | end; |
| 1321 | return f, nil; |
| 1322 | end; |
| 1323 | |
| 1324 | proc builtin(var x: TItem): ERROR; |
| 1325 | var which, n, start: INT; y: TItem; t: PType; f: PObj; at: Diag.Pos; |
| 1326 | begin |
| 1327 | which := INT(x.obj^.val); |
| 1328 | if (x.obj^.home # Sym.system) |
| 1329 | and ((which = Sym.bAdr) or (which = Sym.bPtr) or (which = Sym.bSyscall) or (which = Sym.bArgv)) then |
| 1330 | return Scan.markHelp(x.pos, say2("{} is SYSTEM's, and written SYSTEM.{}", nameOf(x.obj^.name), nameOf(x.obj^.name)), |
| 1331 | "say import SYSTEM after the module's imports, and write the name after SYSTEM."); |
| 1332 | end; |
| 1333 | if (which = Sym.bFence) or (which = Sym.bArgc) or (which = Sym.bArgv) then |
| 1334 | if Scan.tok = Scan.sLparen then Scan.next; try expect(Scan.sRparen); end; |
| 1335 | Item.makeConst(x, Sym.tNone, 0); |
| 1336 | match which of |
| 1337 | | Sym.bFence: Gen.fence(); x.mode := Item.mNone; |
| 1338 | | Sym.bArgc: |
| 1339 | Gen.pushVar(Item.globalAdr(Gen.argcChunk), 8, false, Gen.kWord); |
| 1340 | x.typ := Sym.tInt; x.mode := Item.mStack; |
| 1341 | | else: |
| 1342 | Gen.pushVar(Item.globalAdr(Gen.argvChunk), 8, false, Gen.kWord); |
| 1343 | x.typ := tArgv; x.mode := Item.mStack; |
| 1344 | end; |
| 1345 | return nil; |
| 1346 | end; |
| 1347 | try expect(Scan.sLparen); |
| 1348 | match which of |
| 1349 | | Sym.bSize: |
| 1350 | (* SIZE(T) or SIZE(T.f): parseType reads M.T whole, since the |
| 1351 | name before a "." there must be a module's; so a "." past the |
| 1352 | type is always a field's *) |
| 1353 | start := Scan.tokStart(); |
| 1354 | t := try parseType(); |
| 1355 | if Scan.tok = Scan.sPeriod then |
| 1356 | at := Scan.spanFromAt(start); |
| 1357 | Scan.next; |
| 1358 | f := try typeField(t, at, false); |
| 1359 | Item.makeConst(x, Sym.tConst, f^.typ^.size); |
| 1360 | else |
| 1361 | Item.makeConst(x, Sym.tConst, t^.size); |
| 1362 | end; |
| 1363 | | Sym.bOffset: |
| 1364 | start := Scan.tokStart(); |
| 1365 | t := try parseType(); |
| 1366 | at := Scan.spanFromAt(start); |
| 1367 | try expect(Scan.sComma); |
| 1368 | f := try typeField(t, at, true); |
| 1369 | Item.makeConst(x, Sym.tConst, f^.val); (* a field's val is its offset *) |
| 1370 | | Sym.bAdr: |
| 1371 | try expression(y, nil); |
| 1372 | try Item.notReadOnly(y); |
| 1373 | if (y.mode # Item.mVar) or not y.isVar then return Scan.markAt(y.pos, "ADR needs a variable"); end; |
| 1374 | if y.odd then return Scan.markAt(y.pos, "a field of a packed record has no address"); end; |
| 1375 | if y.view then return Item.noAddress(y, "ADR can't take a view"); end; |
| 1376 | t := newPtr(y.typ, y.vol); |
| 1377 | try Item.address(y); |
| 1378 | Item.makeConst(x, t, 0); |
| 1379 | x.mode := Item.mStack; |
| 1380 | | Sym.bLen: |
| 1381 | try expression(y, nil); |
| 1382 | if y.mode = Item.mStr then |
| 1383 | Item.makeConst(x, Sym.tConst, y.val); |
| 1384 | elsif y.typ^.form = Sym.fArray then |
| 1385 | try Item.discard(y); |
| 1386 | Item.makeConst(x, Sym.tConst, y.typ^.len); |
| 1387 | elsif (y.typ^.form = Sym.fSlice) and (y.mode = Item.mVar) then |
| 1388 | (* its length, the word after its pointer *) |
| 1389 | y.off := y.off + 8; |
| 1390 | y.typ := Sym.tInt; |
| 1391 | try Item.value(y); |
| 1392 | x := y; |
| 1393 | else |
| 1394 | return Scan.markAt(y.pos, say1("LEN needs an array or a slice, found {}", Item.what(y))); |
| 1395 | end; |
| 1396 | | Sym.bPtr: |
| 1397 | if Scan.tok = Scan.sLbrak then |
| 1398 | (* a literal takes its type from where it stands, and here nothing gives one *) |
| 1399 | return Scan.markHelp(Scan.tokPos(), "PTR can't take an array literal, which has no type here", |
| 1400 | "PTR([]) would be nil, the empty slice's pointer; give any other literal a variable first"); |
| 1401 | end; |
| 1402 | try expression(y, nil); |
| 1403 | try ptrOf(y); |
| 1404 | x := y; |
| 1405 | | Sym.bBytes: |
| 1406 | try expression(y, nil); |
| 1407 | try Item.bytesOf(y); |
| 1408 | x := y; |
| 1409 | | Sym.bSyscall: |
| 1410 | n := 0; |
| 1411 | repeat |
| 1412 | if n > 0 then Scan.next; end; |
| 1413 | try expression(y, nil); |
| 1414 | if not (Sym.isScalar(y.typ) and (y.typ^.form # Sym.fReal)) then |
| 1415 | return Scan.markAt(y.pos, say1("expected an integer or a pointer, found {}", Item.what(y))); |
| 1416 | end; |
| 1417 | if y.typ^.form = Sym.fConst then try Item.coerce(y, Sym.tInt); end; |
| 1418 | try Item.value(y); |
| 1419 | INC(n); |
| 1420 | until (Scan.tok # Scan.sComma) or (n = 7); |
| 1421 | Gen.sysCall(n); |
| 1422 | Item.makeConst(x, Sym.tInt, 0); |
| 1423 | x.mode := Item.mStack; |
| 1424 | | Sym.bCas, Sym.bXchg, Sym.bXadd: try atomic(x, which); |
| 1425 | | Sym.bMsg: |
| 1426 | try expression(x, Sym.tError); |
| 1427 | try Item.msg(x); |
| 1428 | | Sym.bInc, Sym.bDec: |
| 1429 | try expression(x, nil); |
| 1430 | try Item.notReadOnly(x); |
| 1431 | if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fInt) then |
| 1432 | return Scan.markAt(x.pos, say1("{} needs an integer variable", incOrDec(which))); |
| 1433 | end; |
| 1434 | if x.base # Gen.bReg then try Item.address(x); end; |
| 1435 | if Scan.tok = Scan.sComma then |
| 1436 | Scan.next; |
| 1437 | try expression(y, x.typ); |
| 1438 | else |
| 1439 | Item.makeConst(y, x.typ, 1); |
| 1440 | end; |
| 1441 | try Item.incDec(x, y, which = Sym.bDec); |
| 1442 | Item.makeConst(x, Sym.tNone, 0); |
| 1443 | x.mode := Item.mNone; |
| 1444 | | Sym.bNew: try new_(x); |
| 1445 | | Sym.bRol, Sym.bRor: |
| 1446 | try expression(x, nil); |
| 1447 | try Item.rotand(x, which = Sym.bRol); |
| 1448 | try expect(Scan.sComma); |
| 1449 | try expression(y, nil); |
| 1450 | try Item.rotate(x, y, which = Sym.bRol); |
| 1451 | | Sym.bMin, Sym.bMax: |
| 1452 | at := Scan.tokPos(); |
| 1453 | t := try parseType(); |
| 1454 | try Item.limit(x, t, which = Sym.bMax, Scan.spanFrom(at)); |
| 1455 | | Sym.bAbs: |
| 1456 | try expression(x, nil); |
| 1457 | try Item.absolute(x); |
| 1458 | | Sym.bClz, Sym.bCtz, Sym.bPopcount: |
| 1459 | try expression(x, nil); |
| 1460 | try Item.countBits(x, which); |
| 1461 | | Sym.bCopy: |
| 1462 | try expression(x, nil); |
| 1463 | try Item.copyDest(x); |
| 1464 | try expect(Scan.sComma); |
| 1465 | try expression(y, nil); |
| 1466 | try Item.copyFrom(x, y); |
| 1467 | Item.makeConst(x, Sym.tNone, 0); |
| 1468 | x.mode := Item.mNone; |
| 1469 | | Sym.bFill: |
| 1470 | try expression(x, nil); |
| 1471 | t := x.typ; |
| 1472 | try Item.fillDest(x); |
| 1473 | try expect(Scan.sComma); |
| 1474 | try expression(y, x.typ^.base); |
| 1475 | try Item.fillWith(x, y, t); |
| 1476 | Item.makeConst(x, Sym.tNone, 0); |
| 1477 | x.mode := Item.mNone; |
| 1478 | | else: |
| 1479 | end; |
| 1480 | return expect(Scan.sRparen); |
| 1481 | end; |
| 1482 | |
| 1483 | proc constructCase(var x: TItem; c: PObj; at: Diag.Pos): ERROR; |
| 1484 | var f: PObj; a: TItem; |
| 1485 | begin |
| 1486 | Item.construct(x, c); |
| 1487 | f := c^.fields; |
| 1488 | if Scan.tok = Scan.sLparen then |
| 1489 | Scan.next; |
| 1490 | while f # nil do |
| 1491 | try expression(a, f^.typ); |
| 1492 | try Item.setField(x, f, a); |
| 1493 | f := f^.next; |
| 1494 | if f # nil then try expect(Scan.sComma); end; |
| 1495 | end; |
| 1496 | return expect(Scan.sRparen); |
| 1497 | elsif f # nil then |
| 1498 | return Scan.markAt(at, say1("{} needs its fields", nameOf(c^.name))); |
| 1499 | end; |
| 1500 | return nil; |
| 1501 | end; |
| 1502 | |
| 1503 | (* x, before ".", has no fields; tok is what follows. Other languages |
| 1504 | write p.f through a pointer and s.len for a length. *) |
| 1505 | proc fieldOfWhat(x: TItem): ERROR; |
| 1506 | var msg, f: []const U8; |
| 1507 | begin |
| 1508 | msg := say1("expected a record, found {}", Item.what(x)); |
| 1509 | if Scan.tok = Scan.sIdent then f := nameOf(Scan.id); else f := ""; end; |
| 1510 | if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fRecord) then |
| 1511 | return Scan.markHelp(x.pos, msg, say2("through a pointer, write {}^.{}", Diag.source(x.pos), f)); |
| 1512 | elsif ((x.typ^.form = Sym.fArray) or (x.typ^.form = Sym.fSlice)) |
| 1513 | and ((f = "len") or (f = "length") or (f = "size") or (f = "count")) then |
| 1514 | return Scan.markHelp(x.pos, msg, say1("its length is LEN({})", Diag.source(x.pos))); |
| 1515 | end; |
| 1516 | return Scan.markAt(x.pos, msg); |
| 1517 | end; |
| 1518 | |
| 1519 | (* A designator, with any selectors and calls after it. called tells |
| 1520 | whether the last thing done was a call. *) |
| 1521 | (* Whether a view, ".(", is next: a "." and, past it, a "(". *) |
| 1522 | proc viewNext: BOOL; |
| 1523 | var st: Scan.State; yes: BOOL; |
| 1524 | begin |
| 1525 | if Scan.tok # Scan.sPeriod then return false; end; |
| 1526 | Scan.saveScan(st); |
| 1527 | Scan.next; |
| 1528 | yes := Scan.tok = Scan.sLparen; |
| 1529 | Scan.restoreScan(st); |
| 1530 | return yes; |
| 1531 | end; |
| 1532 | |
| 1533 | (* The "(" T ")" of a view, at the "(": T. *) |
| 1534 | proc viewType: (PType, ERROR); |
| 1535 | var t: PType; |
| 1536 | begin |
| 1537 | Scan.next; |
| 1538 | t := try parseType(); |
| 1539 | try expect(Scan.sRparen); |
| 1540 | return t, nil; |
| 1541 | end; |
| 1542 | |
| 1543 | proc designator(var x: TItem; var called: BOOL): ERROR; |
| 1544 | var o, f: PObj; y, z: TItem; t: PType; start: INT; |
| 1545 | begin |
| 1546 | start := Scan.tokStart(); |
| 1547 | o := try qualIdent(); |
| 1548 | called := false; |
| 1549 | if o^.cls = Sym.oModule then |
| 1550 | return Scan.markAt(Scan.spanFromAt(start), say1("{} is a module, not a value", nameOf(o^.name))); |
| 1551 | end; |
| 1552 | try Item.makeItem(x, o); |
| 1553 | if x.mode = Item.mBuiltin then |
| 1554 | x.pos := Scan.spanFromAt(start); (* its name, for a message *) |
| 1555 | try builtin(x); |
| 1556 | called := true; |
| 1557 | elsif x.mode = Item.mCase then |
| 1558 | try constructCase(x, o, Scan.spanFromAt(start)); |
| 1559 | end; |
| 1560 | repeat |
| 1561 | x.pos := Scan.spanFromAt(start); |
| 1562 | match Scan.tok of |
| 1563 | | sPeriod: |
| 1564 | Scan.next; |
| 1565 | if Scan.tok = Scan.sLparen then |
| 1566 | t := try viewType(); |
| 1567 | x.pos := Scan.spanFromAt(start); |
| 1568 | try Item.view(x, t); |
| 1569 | else |
| 1570 | if (x.mode # Item.mVar) or (x.typ^.form # Sym.fRecord) then return fieldOfWhat(x); end; |
| 1571 | if Scan.tok # Scan.sIdent then return expected("a field"); end; |
| 1572 | f := try fieldOf(x.typ); |
| 1573 | Scan.next; |
| 1574 | try Item.field(x, f); |
| 1575 | end; |
| 1576 | called := false; |
| 1577 | | sArrow: |
| 1578 | Scan.next; |
| 1579 | try Item.deref(x); |
| 1580 | called := false; |
| 1581 | | sLbrak: |
| 1582 | Scan.next; |
| 1583 | try Item.indexPrep(x); |
| 1584 | try expression(y, nil); |
| 1585 | if Scan.tok = Scan.sUpto then |
| 1586 | Scan.next; |
| 1587 | try Item.sliceLo(y); |
| 1588 | try expression(z, nil); |
| 1589 | try Item.slice(x, y, z); |
| 1590 | try expect(Scan.sRbrak); |
| 1591 | else |
| 1592 | (* a[i].(T), a view of an element, is checked against the |
| 1593 | end of a, not of the element: so the parser looks past |
| 1594 | the "]" for ".(" before the index is made *) |
| 1595 | try expect(Scan.sRbrak); |
| 1596 | if viewNext() then |
| 1597 | Scan.next; |
| 1598 | t := try viewType(); |
| 1599 | x.pos := Scan.spanFromAt(start); |
| 1600 | try Item.indexView(x, y, t); |
| 1601 | else |
| 1602 | try Item.index(x, y); |
| 1603 | end; |
| 1604 | end; |
| 1605 | called := false; |
| 1606 | | sLparen: |
| 1607 | if x.mode = Item.mType then |
| 1608 | t := x.typ; |
| 1609 | Scan.next; |
| 1610 | try expression(x, nil); |
| 1611 | try expect(Scan.sRparen); |
| 1612 | try Item.convert(x, t); |
| 1613 | else |
| 1614 | if x.mode = Item.mProc then lastCalled := x.obj; else lastCalled := nil; end; |
| 1615 | try call(x); |
| 1616 | called := true; |
| 1617 | end; |
| 1618 | | else: break; |
| 1619 | end; |
| 1620 | until false; |
| 1621 | x.pos := Scan.spanFromAt(start); |
| 1622 | Item.nilTest(x); |
| 1623 | return nil; |
| 1624 | end; |
| 1625 | |
| 1626 | proc arrayLiteral(var x: TItem; want: PType): ERROR; |
| 1627 | var |
| 1628 | et, at: PType; e: TItem; slots: [MaxElements]I64; n, i: INT; |
| 1629 | off, es: I64; start: Diag.Pos; |
| 1630 | begin |
| 1631 | start := Scan.tokPos(); |
| 1632 | if (want = nil) or not ((want^.form = Sym.fArray) or (want^.form = Sym.fSlice)) then |
| 1633 | return Scan.mark("an array literal needs a known array or slice type"); |
| 1634 | end; |
| 1635 | et := want^.base; |
| 1636 | es := et^.size; |
| 1637 | Scan.next; |
| 1638 | n := 0; |
| 1639 | if Scan.tok # Scan.sRbrak then |
| 1640 | repeat |
| 1641 | if n >= MaxElements then return Scan.mark(tooMany(MaxElements, "elements")); end; |
| 1642 | try expression(e, et); |
| 1643 | try Item.coerce(e, et); |
| 1644 | if Sym.isScalar(et) then |
| 1645 | slots[n] := try Item.toSlot(e); |
| 1646 | else |
| 1647 | if e.isVar or e.vol or (e.mode # Item.mVar) or (e.base # Gen.bFrame) then try Item.copyToTemp(e); end; |
| 1648 | slots[n] := e.off; |
| 1649 | end; |
| 1650 | INC(n); |
| 1651 | if Scan.tok # Scan.sComma then break; end; |
| 1652 | Scan.next; |
| 1653 | until false; |
| 1654 | end; |
| 1655 | try expect(Scan.sRbrak); |
| 1656 | if (want^.form = Sym.fArray) and (I64(n) # want^.len) then |
| 1657 | return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(want^.len), Fmt.int(n)])); |
| 1658 | end; |
| 1659 | if n = 0 then |
| 1660 | Gen.pushConst(Gen.kWord, 0); |
| 1661 | Item.sliceOf(x, want, 0); |
| 1662 | return nil; |
| 1663 | end; |
| 1664 | if want^.form = Sym.fArray then |
| 1665 | at := want; |
| 1666 | off := Gen.allocTemp(at^.size, at^.align); |
| 1667 | else |
| 1668 | at := Sym.newType(Sym.fArray, I64(n) * es, et^.align); |
| 1669 | at^.len := n; |
| 1670 | at^.base := et; |
| 1671 | off := Gen.allocPerm(at^.size, at^.align); (* lives as long as the call *) |
| 1672 | end; |
| 1673 | for i := 0 to n - 1 do |
| 1674 | if Sym.isScalar(et) then |
| 1675 | Gen.pushVar(Item.frameAdr(slots[i]), 8, false, Gen.kindOf(et)); |
| 1676 | Gen.popVar(Item.frameAdr(off + I64(i) * es), Item.scalarSize(et)); |
| 1677 | else |
| 1678 | Gen.pushAdr(Item.frameAdr(slots[i])); |
| 1679 | Gen.copyTo(Item.frameAdr(off + I64(i) * es), es); |
| 1680 | end; |
| 1681 | end; |
| 1682 | Item.tempItem(x, at, off); |
| 1683 | return nil; |
| 1684 | end; |
| 1685 | |
| 1686 | (* The padding of the record type t, the bytes between its fields and |
| 1687 | after the last, cleared in x: a word at a time, so a few stores *) |
| 1688 | proc clearPadding(const x: TItem; t: PType); |
| 1689 | var f: PObj; at, lo, hi: I64; |
| 1690 | begin |
| 1691 | at := 0; |
| 1692 | f := t^.fields; |
| 1693 | while true do |
| 1694 | if f # nil then hi := f^.val; else hi := t^.size; end; |
| 1695 | if hi > at then |
| 1696 | lo := at - at mod 8; |
| 1697 | hi := Sym.alignUp(hi, 8); |
| 1698 | if hi > t^.size then hi := t^.size; end; |
| 1699 | Item.zeroRange(x, lo, hi - lo); |
| 1700 | end; |
| 1701 | if f = nil then break; end; |
| 1702 | at := f^.val + f^.typ^.size; |
| 1703 | f := f^.next; |
| 1704 | end; |
| 1705 | end; |
| 1706 | |
| 1707 | (* The fields of the record type t that a literal left out, of which seen |
| 1708 | are the n names it gave, cleared in x *) |
| 1709 | proc clearMissing(const x: TItem; t: PType; const seen: [MaxNames]INT; n: INT); |
| 1710 | var f: PObj; i: INT; given: BOOL; |
| 1711 | begin |
| 1712 | f := t^.fields; |
| 1713 | while f # nil do |
| 1714 | given := false; |
| 1715 | for i := 0 to n - 1 do |
| 1716 | if seen[i] = f^.name then given := true; end; |
| 1717 | end; |
| 1718 | if not given then Item.zeroRange(x, f^.val, f^.typ^.size); end; |
| 1719 | f := f^.next; |
| 1720 | end; |
| 1721 | end; |
| 1722 | |
| 1723 | (* A record literal: a temporary, or the result's place, with the fields |
| 1724 | named filled in and the rest zero. The temporary is cleared where the |
| 1725 | fields won't write: the padding first, then what the literal left out. *) |
| 1726 | proc recordLiteral(var x: TItem; t: PType): ERROR; |
| 1727 | var f: PObj; a: TItem; seen: [MaxNames]INT; n, i, fields: INT; |
| 1728 | begin |
| 1729 | Scan.next; |
| 1730 | Item.tempOf(x, t); |
| 1731 | n := 0; |
| 1732 | fields := 0; |
| 1733 | f := t^.fields; |
| 1734 | while f # nil do INC(fields); f := f^.next; end; |
| 1735 | if fields > MaxNames then Item.zeroRange(x, 0, t^.size); (* more than seen has room for *) |
| 1736 | else clearPadding(x, t); end; |
| 1737 | if Scan.tok # Scan.sRbrace then |
| 1738 | repeat |
| 1739 | if Scan.tok # Scan.sIdent then return expected("a field"); end; |
| 1740 | f := try fieldOf(t); |
| 1741 | for i := 0 to n - 1 do |
| 1742 | if seen[i] = Scan.id then |
| 1743 | return Scan.mark(say1("field {} is given twice", nameOf(Scan.id))); |
| 1744 | end; |
| 1745 | end; |
| 1746 | if n < MaxNames then seen[n] := Scan.id; INC(n); end; |
| 1747 | Scan.next; |
| 1748 | try expect(Scan.sColon); |
| 1749 | try expression(a, f^.typ); |
| 1750 | try Item.setField(x, f, a); |
| 1751 | if Scan.tok # Scan.sComma then break; end; |
| 1752 | Scan.next; |
| 1753 | until false; |
| 1754 | end; |
| 1755 | if fields <= MaxNames then clearMissing(x, t, seen, n); end; |
| 1756 | return expect(Scan.sRbrace); |
| 1757 | end; |
| 1758 | |
| 1759 | (* A set literal: the bits of the constant names, or'd at run time with |
| 1760 | those of the others. *) |
| 1761 | proc setLiteral(var x: TItem; t: PType): ERROR; |
| 1762 | var e: TItem; bits, slot: I64; start: Diag.Pos; s: []const U8; |
| 1763 | begin |
| 1764 | start := Scan.tokPos(); |
| 1765 | Scan.next; |
| 1766 | if (t # nil) and (t^.form # Sym.fSet) then |
| 1767 | return Scan.markAt(Scan.spanFrom(start), say1("expected a set type, found {}", Sym.typeName(t))); |
| 1768 | end; |
| 1769 | bits := 0; |
| 1770 | slot := 0; |
| 1771 | if Scan.tok # Scan.sRbrace then |
| 1772 | repeat |
| 1773 | if t = nil then try expression(e, nil); else try expression(e, t^.base); end; |
| 1774 | if t = nil then |
| 1775 | if e.typ^.form # Sym.fEnum then |
| 1776 | return Scan.markAt(e.pos, say1("a set holds names of an enumeration, found {}", Item.what(e))); |
| 1777 | end; |
| 1778 | t := try setOf(e.typ, e.pos); |
| 1779 | end; |
| 1780 | if not Sym.same(e.typ, t^.base) then |
| 1781 | if e.obj # nil then s := nameOf(e.obj^.name); else s := Item.what(e); end; |
| 1782 | return Scan.markAt(e.pos, say2("{} isn't a name of {}", s, Sym.typeName(t^.base))); |
| 1783 | end; |
| 1784 | if e.mode = Item.mConst then |
| 1785 | bits := bits | (I64(1) shl e.val); |
| 1786 | else |
| 1787 | if slot = 0 then |
| 1788 | slot := Gen.allocTemp(8, 8); |
| 1789 | Gen.pushConst(Gen.kWord, 0); |
| 1790 | Gen.popVar(Item.frameAdr(slot), 8); |
| 1791 | end; |
| 1792 | try Item.value(e); |
| 1793 | Gen.pushConst(Gen.kWord, 1); |
| 1794 | Gen.swap(); |
| 1795 | Gen.op(Scan.sShl, Gen.kWord, 8, false); |
| 1796 | Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); |
| 1797 | Gen.op(Scan.sBar, Gen.kWord, 8, false); |
| 1798 | Gen.popVar(Item.frameAdr(slot), 8); |
| 1799 | end; |
| 1800 | if Scan.tok # Scan.sComma then break; end; |
| 1801 | Scan.next; |
| 1802 | until false; |
| 1803 | end; |
| 1804 | try expect(Scan.sRbrace); |
| 1805 | if t = nil then return Scan.markAt(Scan.spanFrom(start), "{} needs a known set type"); end; |
| 1806 | Item.makeConst(x, t, bits); |
| 1807 | if slot # 0 then |
| 1808 | Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); |
| 1809 | Gen.pushConst(Gen.kWord, bits); |
| 1810 | Gen.op(Scan.sBar, Gen.kWord, 8, false); |
| 1811 | x.mode := Item.mStack; |
| 1812 | end; |
| 1813 | return nil; |
| 1814 | end; |
| 1815 | |
| 1816 | proc runDefers(base: INT); forward; |
| 1817 | |
| 1818 | (* The type of the last result of t, the results of a procedure: t if |
| 1819 | it has one, else the last of its several. *) |
| 1820 | proc lastResult(t: PType): PType; |
| 1821 | var f: PObj; |
| 1822 | begin |
| 1823 | if not t^.tuple then return t; end; |
| 1824 | f := t^.fields; |
| 1825 | while f^.next # nil do f := f^.next; end; |
| 1826 | return f^.typ; |
| 1827 | end; |
| 1828 | |
| 1829 | (* The results of the tuple t but the last: the same fields, one fewer *) |
| 1830 | proc withoutLast(t: PType): PType; |
| 1831 | var r: PType; |
| 1832 | begin |
| 1833 | r := Sym.newType(Sym.fRecord, t^.size, t^.align); |
| 1834 | r^.tuple := true; |
| 1835 | r^.fields := t^.fields; |
| 1836 | r^.len := t^.len - 1; |
| 1837 | return r; |
| 1838 | end; |
| 1839 | |
| 1840 | (* try c (the report, 7.8): the call c, then the error it returned, its |
| 1841 | last result: if that isn't nil, the procedure returns it, and a zero |
| 1842 | for each of its other results, after running the deferred statements |
| 1843 | in force. x is left c's other results: none (mNone), one (a value) or |
| 1844 | several (a tuple, for a multiple assignment). The error is kept in a |
| 1845 | slot of the frame, and tested there; the code for it, out of line, |
| 1846 | is made with the stack of values as it stands, and leaves it so, |
| 1847 | since what follows is the code for an error that is nil. *) |
| 1848 | proc tryCall(var x: TItem): ERROR; |
| 1849 | var |
| 1850 | called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT; direct: BOOL; |
| 1851 | begin |
| 1852 | start := Scan.tokPos(); |
| 1853 | Scan.next; |
| 1854 | sawTry := true; |
| 1855 | if deferring then return Scan.markAt(Scan.spanFrom(start), "try can't leave a deferred statement"); end; |
| 1856 | if curResult = nil then |
| 1857 | return Scan.markAt(Scan.spanFrom(start), "try needs a procedure that ends in an ERROR result, and this returns nothing"); |
| 1858 | elsif lastResult(curResult) # Sym.tError then |
| 1859 | return Scan.markAt(Scan.spanFrom(start), |
| 1860 | say1("try needs a procedure that ends in an ERROR result, and this returns {}", Sym.typeName(curResult))); |
| 1861 | end; |
| 1862 | try designator(x, called); |
| 1863 | if not called and ((x.mode = Item.mProc) |
| 1864 | or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc))) then |
| 1865 | (* a procedure without parameters, written without parentheses *) |
| 1866 | at := x.pos; |
| 1867 | try Item.beginCall(c, x); |
| 1868 | try Item.endCall(c, x); |
| 1869 | x.pos := at; |
| 1870 | called := true; |
| 1871 | end; |
| 1872 | if not called then return Scan.markAt(x.pos, say1("try needs a call, found {}", Item.what(x))); end; |
| 1873 | if x.mode = Item.mNone then |
| 1874 | return Scan.markAt(x.pos, "try needs a call that returns an ERROR last, and this returns nothing"); |
| 1875 | end; |
| 1876 | if lastResult(x.typ) # Sym.tError then |
| 1877 | return Scan.markAt(x.pos, say1("try needs a call that returns an ERROR last, and this returns {}", Sym.typeName(x.typ))); |
| 1878 | end; |
| 1879 | res := x.typ; |
| 1880 | direct := false; |
| 1881 | if x.mode = Item.mStack then |
| 1882 | (* an ERROR alone *) |
| 1883 | direct := numDefers = 0; |
| 1884 | if not direct then |
| 1885 | slot := Gen.allocTemp(8, 8); |
| 1886 | Gen.popVar(Item.frameAdr(slot), 8); |
| 1887 | end; |
| 1888 | x.mode := Item.mNone; x.typ := Sym.tNone; |
| 1889 | elsif x.mode = Item.mWords then |
| 1890 | (* two words, the error on top *) |
| 1891 | direct := numDefers = 0; |
| 1892 | if not direct then |
| 1893 | slot := Gen.allocTemp(8, 8); |
| 1894 | Gen.popVar(Item.frameAdr(slot), 8); |
| 1895 | end; |
| 1896 | x.mode := Item.mStack; x.typ := res^.fields^.typ; |
| 1897 | else |
| 1898 | (* several, in a temporary: the error is where it is *) |
| 1899 | last := res^.fields; |
| 1900 | while last^.next # nil do last := last^.next; end; |
| 1901 | slot := x.off + last^.val; |
| 1902 | if res^.len = 2 then try Item.field(x, res^.fields); else x.typ := withoutLast(res); end; |
| 1903 | end; |
| 1904 | ok := Gen.NoLabel; |
| 1905 | if direct then |
| 1906 | (* nothing to defer: the error is tested and returned from the |
| 1907 | register it is in, with no slot *) |
| 1908 | Gen.tryReturnFrom(Gen.tryTest(ok)); |
| 1909 | else |
| 1910 | Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); |
| 1911 | Gen.jumpIf(ok, false); |
| 1912 | if numDefers > 0 then Gen.tryAlign(); end; |
| 1913 | runDefers(0); |
| 1914 | Gen.tryReturn(slot); |
| 1915 | end; |
| 1916 | Gen.fix(ok); |
| 1917 | x.pos := Scan.spanFrom(start); |
| 1918 | return nil; |
| 1919 | end; |
| 1920 | |
| 1921 | (* A doubt other than a drop, to be warned of at p with msg and hint. |
| 1922 | Text read twice, as a while's condition is, is noted once. *) |
| 1923 | proc noteDoubt(p: Diag.Pos; msg, hint: []const U8); |
| 1924 | var i: INT; |
| 1925 | begin |
| 1926 | for i := 0 to numDoubts - 1 do |
| 1927 | if (doubts[i].at.f = p.f) and (doubts[i].at.a = p.a) then return; end; |
| 1928 | end; |
| 1929 | if numDoubts < MaxDoubts then |
| 1930 | doubts[numDoubts].at := p; |
| 1931 | doubts[numDoubts].msg := msg; |
| 1932 | doubts[numDoubts].hint := hint; |
| 1933 | INC(numDoubts); |
| 1934 | end; |
| 1935 | end; |
| 1936 | |
| 1937 | (* Notes the string at the scanner if it has a \0 before a digit *) |
| 1938 | proc noteZeroDigit; |
| 1939 | var at: Diag.Pos; yes: BOOL; |
| 1940 | begin |
| 1941 | at, yes := Scan.zeroDigit(); |
| 1942 | if yes then |
| 1943 | noteDoubt(at, "\\0 is a zero byte and the digit after it is itself", |
| 1944 | "write \\x00 to keep them apart"); |
| 1945 | end; |
| 1946 | end; |
| 1947 | |
| 1948 | proc factor(var x: TItem; want: PType): ERROR; |
| 1949 | var called, vol, several: BOOL; t: PType; start: INT; s: []const U8; |
| 1950 | begin |
| 1951 | INC(nest); |
| 1952 | if nest > MaxNest then return tooDeep(); end; |
| 1953 | several := passOn; |
| 1954 | passOn := false; |
| 1955 | start := Scan.tokStart(); |
| 1956 | match Scan.tok of |
| 1957 | | sInt, sChar: |
| 1958 | (* only a hex number can be above high(I64), and it is a U64 *) |
| 1959 | if Scan.ival < 0 then Item.makeConst(x, Sym.tU64, Scan.ival); else Item.makeConst(x, Sym.tConst, Scan.ival); end; |
| 1960 | Scan.next; |
| 1961 | | sReal: |
| 1962 | Item.makeReal(x, Scan.rval); |
| 1963 | Item.usesReals(Scan.tokPos()); |
| 1964 | Scan.next; |
| 1965 | | sString: |
| 1966 | Item.makeStr(x); |
| 1967 | noteZeroDigit(); |
| 1968 | Scan.next; |
| 1969 | | sIdent: |
| 1970 | try designator(x, called); |
| 1971 | if x.mode = Item.mNone then |
| 1972 | if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end; |
| 1973 | return Scan.markAt(x.pos, say1("{} returns nothing", s)); |
| 1974 | end; |
| 1975 | if x.typ^.tuple and not several then |
| 1976 | if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end; |
| 1977 | return Scan.markHelp(x.pos, say1("{} returns several results", s), |
| 1978 | say1("they go to variables: a, b := {}(...)", s)); |
| 1979 | end; |
| 1980 | | sLparen: |
| 1981 | Scan.next; |
| 1982 | try expression(x, want); |
| 1983 | try expect(Scan.sRparen); |
| 1984 | | sTry: |
| 1985 | try tryCall(x); |
| 1986 | if x.mode = Item.mNone then return Scan.markAt(x.pos, "this try has no value"); end; |
| 1987 | if x.typ^.tuple then |
| 1988 | return Scan.markHelp(x.pos, "this try has several values", "they go to variables: a, b := try f(...)"); |
| 1989 | end; |
| 1990 | | sNot: |
| 1991 | Scan.next; |
| 1992 | try factor(x, nil); |
| 1993 | try Item.notOp(x); |
| 1994 | | sTilde: |
| 1995 | Scan.next; |
| 1996 | try factor(x, nil); |
| 1997 | try Item.complement(x); |
| 1998 | | sLbrak: try arrayLiteral(x, want); |
| 1999 | | sLbrace: |
| 2000 | if (want # nil) and (want^.form = Sym.fRecord) then try recordLiteral(x, want); |
| 2001 | else try setLiteral(x, want); |
| 2002 | end; |
| 2003 | | sArrow: |
| 2004 | Scan.next; |
| 2005 | vol := Scan.tok = Scan.sVolatile; |
| 2006 | if vol then Scan.next; end; |
| 2007 | t := try parseType(); |
| 2008 | t := newPtr(t, vol); |
| 2009 | try expect(Scan.sLparen); |
| 2010 | try expression(x, nil); |
| 2011 | try expect(Scan.sRparen); |
| 2012 | try Item.convert(x, t); |
| 2013 | (* a conversion is a factor, not a designator: nothing selects from it *) |
| 2014 | if Scan.tok = Scan.sArrow then |
| 2015 | return Scan.markHelp(Scan.tokPos(), "a conversion can't be dereferenced", |
| 2016 | "convert into a pointer variable, then dereference that"); |
| 2017 | end; |
| 2018 | | else: return expected("an expression"); |
| 2019 | end; |
| 2020 | x.pos := Scan.spanFromAt(start); |
| 2021 | DEC(nest); |
| 2022 | return nil; |
| 2023 | end; |
| 2024 | |
| 2025 | proc isMulOp: BOOL; |
| 2026 | begin |
| 2027 | match Scan.tok of |
| 2028 | | sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr: return true; |
| 2029 | | else: return false; |
| 2030 | end; |
| 2031 | end; |
| 2032 | |
| 2033 | proc isAddOp: BOOL; |
| 2034 | begin |
| 2035 | match Scan.tok of |
| 2036 | | sPlus, sMinus, sBar, sXor: return true; |
| 2037 | | else: return false; |
| 2038 | end; |
| 2039 | end; |
| 2040 | |
| 2041 | proc isRelOp: BOOL; |
| 2042 | begin |
| 2043 | match Scan.tok of |
| 2044 | | sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn: return true; |
| 2045 | | else: return false; |
| 2046 | end; |
| 2047 | end; |
| 2048 | |
| 2049 | proc term(var x: TItem; want: PType): ERROR; |
| 2050 | var op: Scan.Sym; y: TItem; L: INT; start: INT; |
| 2051 | begin |
| 2052 | start := Scan.tokStart(); |
| 2053 | try factor(x, want); |
| 2054 | while isMulOp() do |
| 2055 | op := Scan.tok; |
| 2056 | Scan.next; |
| 2057 | try Item.op1(op, x, L); |
| 2058 | try factor(y, nil); |
| 2059 | try Item.op2(op, x, y, L); |
| 2060 | x.pos := Scan.spanFromAt(start); |
| 2061 | end; |
| 2062 | return nil; |
| 2063 | end; |
| 2064 | |
| 2065 | proc simpleExpr(var x: TItem; want: PType): ERROR; |
| 2066 | var op: Scan.Sym; y: TItem; L: INT; start: INT; |
| 2067 | begin |
| 2068 | start := Scan.tokStart(); |
| 2069 | if Scan.tok = Scan.sMinus then |
| 2070 | Scan.next; |
| 2071 | try term(x, nil); |
| 2072 | x.pos := Scan.spanFromAt(start); |
| 2073 | try Item.neg(x); |
| 2074 | else |
| 2075 | try term(x, want); |
| 2076 | end; |
| 2077 | while isAddOp() do |
| 2078 | op := Scan.tok; |
| 2079 | Scan.next; |
| 2080 | try Item.op1(op, x, L); |
| 2081 | try term(y, nil); |
| 2082 | try Item.op2(op, x, y, L); |
| 2083 | x.pos := Scan.spanFromAt(start); |
| 2084 | end; |
| 2085 | return nil; |
| 2086 | end; |
| 2087 | |
| 2088 | (* A relation. It sets bareBoolRel, for the and or or that may follow: |
| 2089 | a relation binds tighter than and and or, so the # in "a # b and c" |
| 2090 | is read first, as (a # b) and c, which a Pascal reader doesn't expect. *) |
| 2091 | proc relation(var x: TItem; want: PType): ERROR; |
| 2092 | var op: Scan.Sym; y: TItem; L: INT; bools: BOOL; |
| 2093 | begin |
| 2094 | try simpleExpr(x, want); |
| 2095 | bools := false; |
| 2096 | if isRelOp() then |
| 2097 | op := Scan.tok; |
| 2098 | Scan.next; |
| 2099 | try Item.op1(op, x, L); |
| 2100 | if op = Scan.sIn then try simpleExpr(y, nil); else try simpleExpr(y, x.typ); end; |
| 2101 | bools := ((op = Scan.sEql) or (op = Scan.sNeq)) and (x.typ = Sym.tBool) and (y.typ = Sym.tBool); |
| 2102 | try Item.op2(op, x, y, L); |
| 2103 | x.pos := Diag.join(x.pos, y.pos); |
| 2104 | end; |
| 2105 | bareBoolRel := bools; (* a relation in parentheses comes here as a factor, and sets it false *) |
| 2106 | return nil; |
| 2107 | end; |
| 2108 | |
| 2109 | (* Notes x, an operand of the and or or (word) just read, if it is an |
| 2110 | unparenthesised = or # of two BOOLs *) |
| 2111 | proc noteBoolRel(const x: TItem; word: []const U8); |
| 2112 | begin |
| 2113 | if bareBoolRel then |
| 2114 | noteDoubt(x.pos, say2("{} is read first: = and # bind tighter than {}", Diag.source(x.pos), word), |
| 2115 | "put the = or # of two BOOLs in parentheses"); |
| 2116 | end; |
| 2117 | end; |
| 2118 | |
| 2119 | (* and binds tighter than or, and both below the relations *) |
| 2120 | proc conjunct(var x: TItem; want: PType): ERROR; |
| 2121 | var y: TItem; L: INT; start: INT; |
| 2122 | begin |
| 2123 | start := Scan.tokStart(); |
| 2124 | try relation(x, want); |
| 2125 | if Scan.tok = Scan.sAnd then |
| 2126 | noteBoolRel(x, "and"); |
| 2127 | repeat |
| 2128 | Scan.next; |
| 2129 | try Item.op1(Scan.sAnd, x, L); |
| 2130 | try relation(y, nil); |
| 2131 | noteBoolRel(y, "and"); |
| 2132 | try Item.op2(Scan.sAnd, x, y, L); |
| 2133 | x.pos := Scan.spanFromAt(start); |
| 2134 | until Scan.tok # Scan.sAnd; |
| 2135 | bareBoolRel := false; (* x is a conjunction now *) |
| 2136 | end; |
| 2137 | return nil; |
| 2138 | end; |
| 2139 | |
| 2140 | proc expression(var x: TItem; want: PType): ERROR; |
| 2141 | var y: TItem; L: INT; start: INT; |
| 2142 | begin |
| 2143 | start := Scan.tokStart(); |
| 2144 | try conjunct(x, want); |
| 2145 | if Scan.tok = Scan.sOr then |
| 2146 | noteBoolRel(x, "or"); |
| 2147 | repeat |
| 2148 | Scan.next; |
| 2149 | try Item.op1(Scan.sOr, x, L); |
| 2150 | try conjunct(y, nil); |
| 2151 | noteBoolRel(y, "or"); |
| 2152 | try Item.op2(Scan.sOr, x, y, L); |
| 2153 | x.pos := Scan.spanFromAt(start); |
| 2154 | until Scan.tok # Scan.sOr; |
| 2155 | bareBoolRel := false; (* x is a disjunction now *) |
| 2156 | end; |
| 2157 | return nil; |
| 2158 | end; |
| 2159 | |
| 2160 | (* Statements *) |
| 2161 | |
| 2162 | proc enterLoop(var lp: Loop; var old: PLoop); |
| 2163 | begin |
| 2164 | lp.brk := Gen.NoLabel; |
| 2165 | lp.cont := Gen.NoLabel; |
| 2166 | lp.base := numDefers; |
| 2167 | old := curLoop; |
| 2168 | curLoop := SYSTEM.ADR(lp); |
| 2169 | end; |
| 2170 | |
| 2171 | (* Runs the deferred statements in force above base, newest first. *) |
| 2172 | proc runDefers(base: INT); |
| 2173 | var i: INT; |
| 2174 | begin |
| 2175 | for i := numDefers - 1 to base by -1 do Gen.runDefer(defers[i]); end; |
| 2176 | end; |
| 2177 | |
| 2178 | (* Whether what follows "then" is a lone "break;" or "continue;", with |
| 2179 | no deferred statement to run on the way out of the round: it must be |
| 2180 | the branch's last statement, so ";" and then end, elsif or else |
| 2181 | follow. *) |
| 2182 | proc loneJump: BOOL; |
| 2183 | var st: Scan.State; lone: BOOL; |
| 2184 | begin |
| 2185 | if ((Scan.tok # Scan.sBreak) and (Scan.tok # Scan.sContinue)) or (curLoop = nil) |
| 2186 | or (numDefers # curLoop^.base) then |
| 2187 | return false; |
| 2188 | end; |
| 2189 | Scan.saveScan(st); |
| 2190 | lone := false; |
| 2191 | Scan.next; |
| 2192 | if Scan.tok = Scan.sSemicolon then |
| 2193 | Scan.next; |
| 2194 | lone := (Scan.tok = Scan.sEnd) or (Scan.tok = Scan.sElsif) or (Scan.tok = Scan.sElse); |
| 2195 | end; |
| 2196 | Scan.restoreScan(st); |
| 2197 | return lone; |
| 2198 | end; |
| 2199 | |
| 2200 | (* The condition x of if or elsif, and the statements it guards, which |
| 2201 | L skips when it is false. "if c then break; end" is one jump out of |
| 2202 | the loop when c holds, not one past a jump out; "if c then continue; |
| 2203 | end" one jump to the end of the round. *) |
| 2204 | proc thenPart(var x: TItem; var L: INT): ERROR; |
| 2205 | begin |
| 2206 | try expect(Scan.sThen); |
| 2207 | L := Gen.NoLabel; (* stays so with a lone break or continue: there is nothing to skip *) |
| 2208 | if loneJump() then |
| 2209 | Chunk.noteLine(Scan.curLine(), Scan.curCol()); (* the jump gets the break's or continue's line *) |
| 2210 | if Scan.tok = Scan.sBreak then try Item.condJumpTrue(x, curLoop^.brk); |
| 2211 | else try Item.condJumpTrue(x, curLoop^.cont); end; |
| 2212 | Scan.next; Scan.next; (* skip "break" or "continue", and ";" *) |
| 2213 | ends := true; |
| 2214 | else |
| 2215 | try Item.condJump(x, L); |
| 2216 | try statements(); |
| 2217 | end; |
| 2218 | return nil; |
| 2219 | end; |
| 2220 | |
| 2221 | (* if, elsif and else: each condition's jump skips its branch to the |
| 2222 | next; each branch that doesn't end jumps to the end. A branch that |
| 2223 | ends, in return or break, needs no jump past the others, and all of |
| 2224 | them ending is told to the caller in the global ends. *) |
| 2225 | proc ifStatement(start: Diag.Pos; ind: INT): ERROR; |
| 2226 | var x: TItem; L, endL: INT; all: BOOL; |
| 2227 | begin |
| 2228 | Scan.next; |
| 2229 | try expression(x, nil); |
| 2230 | try thenPart(x, L); |
| 2231 | all := ends; |
| 2232 | endL := Gen.NoLabel; |
| 2233 | while Scan.tok = Scan.sElsif do |
| 2234 | if not ends then Gen.jump(endL); end; |
| 2235 | Gen.fix(L); |
| 2236 | Scan.next; |
| 2237 | try expression(x, nil); |
| 2238 | try thenPart(x, L); |
| 2239 | all := all and ends; |
| 2240 | end; |
| 2241 | if Scan.tok = Scan.sElse then |
| 2242 | if not ends then Gen.jump(endL); end; |
| 2243 | Gen.fix(L); |
| 2244 | Scan.next; |
| 2245 | if Scan.tok = Scan.sIf then elseIf := true; end; |
| 2246 | try statements(); |
| 2247 | all := all and ends; |
| 2248 | else |
| 2249 | Gen.fix(L); |
| 2250 | all := false; |
| 2251 | end; |
| 2252 | try closeEnd(start, ind); |
| 2253 | Gen.fix(endL); |
| 2254 | ends := all; |
| 2255 | return nil; |
| 2256 | end; |
| 2257 | |
| 2258 | (* while c do s end: the test comes after the body, and the loop jumps to |
| 2259 | it first, so that a round takes one jump, back to the top if c holds: |
| 2260 | |
| 2261 | jmp test rather than top: c, jump to out if false |
| 2262 | top: s s |
| 2263 | test: c, jump to top if true jmp top |
| 2264 | out: |
| 2265 | |
| 2266 | One pass reads c before s: so c is compiled where it is written, for |
| 2267 | its messages, and its code taken back (rewind); then read again, and |
| 2268 | compiled, after s (saveScan, restoreScan). *) |
| 2269 | proc whileStatement(start: Diag.Pos; ind: INT): ERROR; |
| 2270 | var |
| 2271 | x: TItem; top, L, test: INT; lp: Loop; old: PLoop; cond, after: Scan.State; m: Gen.CodeMark; |
| 2272 | begin |
| 2273 | Scan.next; |
| 2274 | Scan.saveScan(cond); |
| 2275 | Gen.markCode(m); |
| 2276 | try expression(x, nil); |
| 2277 | try Item.discard(x); |
| 2278 | Gen.rewind(m); |
| 2279 | try expect(Scan.sDo); |
| 2280 | test := Gen.NoLabel; |
| 2281 | Gen.jump(test); |
| 2282 | Gen.alignLoop(); |
| 2283 | top := Chunk.pc; |
| 2284 | enterLoop(lp, old); |
| 2285 | try statements(); |
| 2286 | curLoop := old; |
| 2287 | Scan.saveScan(after); |
| 2288 | Scan.restoreScan(cond); |
| 2289 | Gen.fix(test); |
| 2290 | Gen.fix(lp.cont); (* a continue goes to the test *) |
| 2291 | Chunk.noteLine(Scan.curLine(), Scan.curCol()); |
| 2292 | try expression(x, nil); |
| 2293 | ends := (x.mode = Item.mConst) and (x.val # 0) and (lp.brk = Gen.NoLabel); (* while true *) |
| 2294 | if (x.mode = Item.mConst) and (x.typ^.form = Sym.fBool) then |
| 2295 | if x.val # 0 then Gen.jumpBack(top); end; |
| 2296 | else |
| 2297 | L := Gen.NoLabel; |
| 2298 | try Item.condJumpTrue(x, L); |
| 2299 | Gen.fixTo(L, top); |
| 2300 | end; |
| 2301 | Scan.restoreScan(after); |
| 2302 | try closeEnd(start, ind); |
| 2303 | Gen.fix(lp.brk); |
| 2304 | return nil; |
| 2305 | end; |
| 2306 | |
| 2307 | proc repeatStatement: ERROR; |
| 2308 | var x: TItem; top, L: INT; lp: Loop; old: PLoop; |
| 2309 | begin |
| 2310 | Scan.next; |
| 2311 | top := Chunk.pc; |
| 2312 | enterLoop(lp, old); |
| 2313 | try statements(); |
| 2314 | curLoop := old; |
| 2315 | try expect(Scan.sUntil); |
| 2316 | Gen.fix(lp.cont); (* a continue goes to the test *) |
| 2317 | try expression(x, nil); |
| 2318 | ends := (x.mode = Item.mConst) and (x.val = 0) and (lp.brk = Gen.NoLabel); (* until false *) |
| 2319 | L := Gen.NoLabel; |
| 2320 | try Item.condJump(x, L); |
| 2321 | Gen.fixTo(L, top); |
| 2322 | Gen.fix(lp.brk); |
| 2323 | return nil; |
| 2324 | end; |
| 2325 | |
| 2326 | (* for v := a to b by s do ... end, laid out as |
| 2327 | v := a; the limit b, in a slot unless it is a constant |
| 2328 | if v is past b then goto exit |
| 2329 | goto body |
| 2330 | top: v := v + s |
| 2331 | body: the statements |
| 2332 | the end of a round: goto top, or exit (forNext) |
| 2333 | exit: |
| 2334 | so that a round of a loop by 1 takes one compare and one jump. *) |
| 2335 | proc forStatement(start: Diag.Pos; ind: INT): ERROR; |
| 2336 | var |
| 2337 | o, lim: PObj; v, a, b, s: TItem; step: I64; top, body, bodyL, exitL, n: INT; |
| 2338 | lp: Loop; old: PLoop; f: Sym.Form; slot: I64; |
| 2339 | begin |
| 2340 | n := numFors; |
| 2341 | INC(numFors); |
| 2342 | Scan.next; |
| 2343 | if Scan.tok # Scan.sIdent then return expected("a name"); end; |
| 2344 | o := Sym.lookup(Scan.id); |
| 2345 | if o = nil then |
| 2346 | notDeclared(Scan.tokPos(), Scan.id); |
| 2347 | return Scan.Failed; |
| 2348 | end; |
| 2349 | named(o); |
| 2350 | if o^.cls # Sym.oVar then return Scan.mark(say1("{} isn't a variable", nameOf(Scan.id))); end; |
| 2351 | f := o^.typ^.form; |
| 2352 | if (f # Sym.fInt) and (f # Sym.fEnum) then |
| 2353 | return Scan.mark(say1("a for loop needs an integer or enumeration variable, found {}", Sym.typeName(o^.typ))); |
| 2354 | end; |
| 2355 | Scan.next; |
| 2356 | try expect(Scan.sBecomes); |
| 2357 | try Item.makeItem(v, o); |
| 2358 | try expression(a, o^.typ); |
| 2359 | try Item.coerce(a, o^.typ); |
| 2360 | try Item.assign(v, a); |
| 2361 | try expect(Scan.sTo); |
| 2362 | try expression(b, o^.typ); |
| 2363 | try Item.coerce(b, o^.typ); |
| 2364 | (* the limit, evaluated once: a constant as it is; else, in an |
| 2365 | innermost loop, in the register chooseRegs kept for it, as a |
| 2366 | variable no one can name; else in a slot *) |
| 2367 | if (b.mode # Item.mConst) and (limitK >= 0) and (n < MaxFors) and limitIn[n] then |
| 2368 | lim := Sym.newObj(Sym.oVar, o^.name, b.typ); |
| 2369 | lim^.lev := 1; |
| 2370 | lim^.reg := Gen.VarRegs[limitK]; |
| 2371 | try Item.makeItem(v, lim); |
| 2372 | try Item.assign(v, b); |
| 2373 | b := v; |
| 2374 | elsif b.mode # Item.mConst then |
| 2375 | slot := try Item.toSlot(b); |
| 2376 | Item.tempItem(b, b.typ, slot); |
| 2377 | end; |
| 2378 | step := 1; |
| 2379 | if Scan.tok = Scan.sBy then |
| 2380 | Scan.next; |
| 2381 | try expression(s, nil); |
| 2382 | step := try constValue(s); |
| 2383 | if step = 0 then return Scan.markAt(s.pos, "the step can't be zero"); end; |
| 2384 | end; |
| 2385 | try expect(Scan.sDo); |
| 2386 | exitL := Gen.NoLabel; |
| 2387 | if step > 0 then try Item.forCmp(o, b, Scan.sGtr, exitL); else try Item.forCmp(o, b, Scan.sLss, exitL); end; |
| 2388 | bodyL := Gen.NoLabel; |
| 2389 | Gen.jump(bodyL); |
| 2390 | Gen.alignLoop(); |
| 2391 | top := Chunk.pc; |
| 2392 | try Item.forStep(o, step); |
| 2393 | Gen.fix(bodyL); |
| 2394 | body := Chunk.pc; |
| 2395 | enterLoop(lp, old); |
| 2396 | try statements(); |
| 2397 | curLoop := old; |
| 2398 | try closeEnd(start, ind); |
| 2399 | Gen.fix(lp.cont); (* a continue goes to the end of the round *) |
| 2400 | try Item.forNext(o, b, step, exitL, top, body); |
| 2401 | Gen.fix(exitL); |
| 2402 | Gen.fix(lp.brk); |
| 2403 | return nil; |
| 2404 | end; |
| 2405 | |
| 2406 | type |
| 2407 | Labels = record |
| 2408 | lo, hi: [MaxLabels]I64; (* the ranges of the labels so far *) |
| 2409 | at: [MaxLabels]INT; (* where the arm of each starts *) |
| 2410 | n: INT; |
| 2411 | end; |
| 2412 | |
| 2413 | (* a < b, for values of an integer type, unsigned or not *) |
| 2414 | proc below(a, b: I64; unsign: BOOL): BOOL; |
| 2415 | begin |
| 2416 | if unsign then return U64(a) < U64(b); end; |
| 2417 | return a < b; |
| 2418 | end; |
| 2419 | |
| 2420 | (* An arm of a match on an integer of type t: its labels, each a |
| 2421 | constant or a range, none overlapping another (report section 7.4), |
| 2422 | then its statements. No code tests the labels here; dispatch does, |
| 2423 | after the last arm, for which each label notes where its arm starts. *) |
| 2424 | proc intArm(t: PType; var ls: Labels; var endL: INT): ERROR; |
| 2425 | var lo, hi: TItem; first, i: INT; u: BOOL; start: Diag.Pos; |
| 2426 | begin |
| 2427 | u := not t^.signed; |
| 2428 | first := ls.n; |
| 2429 | repeat |
| 2430 | start := Scan.tokPos(); |
| 2431 | try expression(lo, t); |
| 2432 | try Item.coerce(lo, t); |
| 2433 | _ := try constValue(lo); |
| 2434 | hi := lo; |
| 2435 | if Scan.tok = Scan.sUpto then |
| 2436 | Scan.next; |
| 2437 | try expression(hi, t); |
| 2438 | try Item.coerce(hi, t); |
| 2439 | _ := try constValue(hi); |
| 2440 | if below(hi.val, lo.val, u) then return Scan.markAt(Scan.spanFrom(start), "the range is empty"); end; |
| 2441 | end; |
| 2442 | for i := 0 to ls.n - 1 do |
| 2443 | if not below(hi.val, ls.lo[i], u) and not below(ls.hi[i], lo.val, u) then |
| 2444 | if lo.val = hi.val then |
| 2445 | return Scan.markAt(Scan.spanFrom(start), say1("{} is in another label too", Diag.source(Scan.spanFrom(start)))); |
| 2446 | end; |
| 2447 | return Scan.markAt(Scan.spanFrom(start), say1("{} overlaps another label", Diag.source(Scan.spanFrom(start)))); |
| 2448 | end; |
| 2449 | end; |
| 2450 | if ls.n >= MaxLabels then |
| 2451 | return Scan.markAt(Scan.spanFrom(start), tooMany(MaxLabels, "labels in one match")); |
| 2452 | end; |
| 2453 | ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val; |
| 2454 | INC(ls.n); |
| 2455 | if Scan.tok # Scan.sComma then break; end; |
| 2456 | Scan.next; |
| 2457 | until false; |
| 2458 | try expect(Scan.sColon); |
| 2459 | for i := first to ls.n - 1 do ls.at[i] := Chunk.pc; end; |
| 2460 | try statements(); |
| 2461 | Gen.jump(endL); |
| 2462 | return nil; |
| 2463 | end; |
| 2464 | |
| 2465 | (* An arm of a match on a string, whose slice is in slot p: its labels, |
| 2466 | string constants, none equal to another (report section 7.4), each |
| 2467 | compared in turn as its arm is reached, then its statements. ls |
| 2468 | keeps each label's chunk in lo and its length in hi, for the |
| 2469 | comparing of labels. *) |
| 2470 | proc strArm(p: I64; var ls: Labels; var endL: INT): ERROR; |
| 2471 | var x: TItem; i, L, body: INT; last: BOOL; s: []const U8; |
| 2472 | begin |
| 2473 | L := Gen.NoLabel; |
| 2474 | body := Gen.NoLabel; |
| 2475 | repeat |
| 2476 | try expression(x, nil); |
| 2477 | if x.mode # Item.mStr then |
| 2478 | return Scan.markAt(x.pos, say1("a label of a match on a string is a string constant, found {}", Item.what(x))); |
| 2479 | end; |
| 2480 | s := Chunk.rodata[Chunk.chunks[x.chunk].start..Chunk.chunks[x.chunk].start + INT(x.val)]; |
| 2481 | for i := 0 to ls.n - 1 do |
| 2482 | if s = Chunk.rodata[Chunk.chunks[ls.lo[i]].start..Chunk.chunks[ls.lo[i]].start + INT(ls.hi[i])] then |
| 2483 | return Scan.markAt(x.pos, say1("{} is in another label too", Diag.source(x.pos))); |
| 2484 | end; |
| 2485 | end; |
| 2486 | if ls.n >= MaxLabels then return Scan.markAt(x.pos, tooMany(MaxLabels, "labels in one match")); end; |
| 2487 | ls.lo[ls.n] := x.chunk; ls.hi[ls.n] := x.val; |
| 2488 | INC(ls.n); |
| 2489 | last := Scan.tok # Scan.sComma; |
| 2490 | try Item.matchStr(p, x, last, L, body); |
| 2491 | if last then break; end; |
| 2492 | Scan.next; |
| 2493 | until false; |
| 2494 | try expect(Scan.sColon); |
| 2495 | Gen.fix(body); |
| 2496 | try statements(); |
| 2497 | Gen.jump(endL); |
| 2498 | Gen.fix(L); |
| 2499 | return nil; |
| 2500 | end; |
| 2501 | |
| 2502 | const |
| 2503 | MinTable = 4; (* fewer labels are tested one by one *) |
| 2504 | TableDensity = 8; (* a table has at most this many entries to a label *) |
| 2505 | |
| 2506 | (* The code that picks the arm, after the last one, which the match's |
| 2507 | start jumped to: label by label, as a chain of compares each to its |
| 2508 | arm; or, for four or more labels not far apart, a jump table (jumpTable), |
| 2509 | which takes the same few instructions for any of them. It is here and |
| 2510 | not before the arms, since a table can only be made once every arm's |
| 2511 | place is known; an arm is entered by a jump back to it. elseAt is where |
| 2512 | the else arm starts, or NoLabel. *) |
| 2513 | proc dispatch(t: PType; p: I64; var ls: Labels; elseAt: INT; var endL: INT); |
| 2514 | var |
| 2515 | lo, hi: I64; i, start, v, body: INT; u: BOOL; |
| 2516 | entry: [MaxLabels]INT; |
| 2517 | begin |
| 2518 | u := (t^.form = Sym.fInt) and not t^.signed; |
| 2519 | lo := 0; hi := 0; |
| 2520 | if ls.n > 0 then |
| 2521 | lo := ls.lo[0]; hi := ls.hi[0]; |
| 2522 | for i := 1 to ls.n - 1 do |
| 2523 | if below(ls.lo[i], lo, u) then lo := ls.lo[i]; end; |
| 2524 | if below(hi, ls.hi[i], u) then hi := ls.hi[i]; end; |
| 2525 | end; |
| 2526 | end; |
| 2527 | if (ls.n >= MinTable) and (lo >= -2147483648) and (lo <= 2147483647) |
| 2528 | and (U64(hi - lo) < U64(TableDensity * ls.n)) and (hi - lo < MaxLabels) then |
| 2529 | start := Gen.jumpTable(p, lo, INT(hi - lo) + 1, elseAt, endL); |
| 2530 | for v := 0 to INT(hi - lo) do |
| 2531 | if elseAt # Gen.NoLabel then entry[v] := elseAt; else entry[v] := start; end; |
| 2532 | end; |
| 2533 | for i := 0 to ls.n - 1 do |
| 2534 | for v := INT(ls.lo[i] - lo) to INT(ls.hi[i] - lo) do entry[v] := ls.at[i]; end; |
| 2535 | end; |
| 2536 | for v := 0 to INT(hi - lo) do Gen.tableEntry(start, entry[v]); end; |
| 2537 | return; |
| 2538 | end; |
| 2539 | for i := 0 to ls.n - 1 do |
| 2540 | body := Gen.NoLabel; |
| 2541 | Item.matchRange(p, ls.lo[i], ls.hi[i], body); |
| 2542 | Gen.fixTo(body, ls.at[i]); |
| 2543 | end; |
| 2544 | if elseAt # Gen.NoLabel then Gen.jumpBack(elseAt); end; |
| 2545 | end; |
| 2546 | |
| 2547 | (* The case of t, an enumeration or a variant, named n, or nil *) |
| 2548 | proc caseNamed(t: PType; n: INT): PObj; |
| 2549 | var c: PObj; |
| 2550 | begin |
| 2551 | c := t^.fields; |
| 2552 | while (c # nil) and (c^.name # n) do c := c^.next; end; |
| 2553 | return c; |
| 2554 | end; |
| 2555 | |
| 2556 | (* The case of t, an enumeration or a variant, that an arm of a match |
| 2557 | names (report section 7.4). A name alone is looked for among t's own, |
| 2558 | whatever the scope holds. A qualified one, Kind.done, Xml.done or |
| 2559 | Xml.Kind.done, is read by qualIdent, as it is anywhere else, and must |
| 2560 | be one of t's. *) |
| 2561 | proc armCase(t: PType): (PObj, ERROR); |
| 2562 | var st: Scan.State; c: PObj; at: Diag.Pos; qualified: BOOL; msg: []const U8; |
| 2563 | begin |
| 2564 | at := Scan.tokPos(); |
| 2565 | Scan.saveScan(st); |
| 2566 | Scan.next; |
| 2567 | qualified := Scan.tok = Scan.sPeriod; |
| 2568 | Scan.restoreScan(st); |
| 2569 | if not qualified then |
| 2570 | c := caseNamed(t, Scan.id); |
| 2571 | if c = nil then |
| 2572 | return nil, Scan.mark(say2("{} isn't a case of {}", nameOf(Scan.id), Sym.typeName(t))); |
| 2573 | end; |
| 2574 | Scan.next; |
| 2575 | return c, nil; |
| 2576 | end; |
| 2577 | c := try qualIdent(); |
| 2578 | if (c^.cls # Sym.oCase) and not c^.ofEnum then |
| 2579 | return nil, Scan.markAt(Scan.spanFrom(at), say1("expected a case of {}", Sym.typeName(t))); |
| 2580 | end; |
| 2581 | if not Sym.same(c^.typ, t) then |
| 2582 | msg := say2("the match is on {}, not {}", Sym.typeName(t), Sym.typeName(c^.typ)); |
| 2583 | if caseNamed(t, c^.name) = nil then return nil, Scan.markAt(Scan.spanFrom(at), msg); end; |
| 2584 | return nil, Scan.markHelp(Scan.spanFrom(at), msg, |
| 2585 | say2("{} has a {} of its own: write it alone", Sym.typeName(t), nameOf(c^.name))); |
| 2586 | end; |
| 2587 | return c, nil; |
| 2588 | end; |
| 2589 | |
| 2590 | proc matchStatement(start: Diag.Pos; ind: INT): ERROR; |
| 2591 | var |
| 2592 | x: TItem; t: PType; c, f, o: PObj; p: I64; L, endL, n, first, disp, elseAt: INT; |
| 2593 | seen: [256]BOOL; hasElse, all, byValue, isStr, onlyRead: BOOL; endAt, at: Diag.Pos; ls: Labels; |
| 2594 | begin |
| 2595 | Scan.next; |
| 2596 | try expression(x, nil); |
| 2597 | if x.typ^.form = Sym.fConst then try Item.coerce(x, Sym.tI64); end; |
| 2598 | (* a const parameter or a constant: then so are the names its arms give *) |
| 2599 | onlyRead := Item.onlyRead(x) or x.elemRo or ((x.mode = Item.mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst)); |
| 2600 | p := try Item.matchBegin(x); |
| 2601 | t := x.typ; |
| 2602 | isStr := t^.form = Sym.fSlice; (* matchBegin made a string a slice *) |
| 2603 | try expect(Scan.sOf); |
| 2604 | hasElse := false; |
| 2605 | all := true; |
| 2606 | endL := Gen.NoLabel; |
| 2607 | ls.n := 0; |
| 2608 | (* an integer or an enumeration is matched by its value, and the arms |
| 2609 | are picked by dispatch, after them; a variant by its tag, arm by arm *) |
| 2610 | byValue := (t^.form = Sym.fInt) or (t^.form = Sym.fEnum); |
| 2611 | disp := Gen.NoLabel; |
| 2612 | elseAt := Gen.NoLabel; |
| 2613 | if byValue then Gen.jump(disp); end; |
| 2614 | while Scan.tok = Scan.sBar do |
| 2615 | Scan.next; |
| 2616 | if hasElse then return Scan.mark("else must be the last arm"); end; |
| 2617 | if Scan.tok = Scan.sBlank then |
| 2618 | return Scan.markHelp(Scan.tokPos(), "_ matches nothing: it is the blank, which stands only left of :=", |
| 2619 | "the arm for every other case is | else:"); |
| 2620 | end; |
| 2621 | if Scan.tok = Scan.sElse then |
| 2622 | Scan.next; |
| 2623 | try expect(Scan.sColon); |
| 2624 | elseAt := Chunk.pc; |
| 2625 | try statements(); |
| 2626 | if byValue then Gen.jump(endL); end; |
| 2627 | hasElse := true; |
| 2628 | elsif t^.form = Sym.fInt then |
| 2629 | try intArm(t, ls, endL); |
| 2630 | elsif isStr then |
| 2631 | try strArm(p, ls, endL); |
| 2632 | else |
| 2633 | first := ls.n; |
| 2634 | L := Gen.NoLabel; |
| 2635 | repeat |
| 2636 | if Scan.tok # Scan.sIdent then return expected("a case"); end; |
| 2637 | at := Scan.tokPos(); |
| 2638 | c := try armCase(t); |
| 2639 | if (c^.val <= 255) and seen[c^.val] then |
| 2640 | return Scan.markAt(Scan.spanFrom(at), say1("{} has two arms", nameOf(c^.name))); |
| 2641 | end; |
| 2642 | if c^.val <= 255 then seen[c^.val] := true; end; |
| 2643 | if t^.form # Sym.fEnum then |
| 2644 | Item.matchTag(p, c^.val, L); |
| 2645 | break; |
| 2646 | end; |
| 2647 | (* an enumeration's arm may name several, which share its place *) |
| 2648 | ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val; |
| 2649 | INC(ls.n); |
| 2650 | if Scan.tok # Scan.sComma then break; end; |
| 2651 | Scan.next; |
| 2652 | until false; |
| 2653 | try Sym.openScope(Sym.newScope()); |
| 2654 | if Scan.tok = Scan.sLparen then |
| 2655 | Scan.next; |
| 2656 | f := c^.fields; |
| 2657 | n := 0; |
| 2658 | repeat |
| 2659 | if (Scan.tok = Scan.sBlank) and (f # nil) then |
| 2660 | return Scan.markHelp(Scan.tokPos(), "a field is named, not blanked", |
| 2661 | say1("call one the arm doesn't read _{}", nameOf(f^.name))); |
| 2662 | end; |
| 2663 | if Scan.tok # Scan.sIdent then return expected("a name"); end; |
| 2664 | if f = nil then |
| 2665 | return Scan.mark(say1("more names than {} has fields", nameOf(c^.name))); |
| 2666 | end; |
| 2667 | o := Sym.newObj(Sym.oVar, Scan.id, f^.typ); |
| 2668 | o^.lev := 1; o^.ind := true; o^.isVar := true; o^.isConst := onlyRead; |
| 2669 | o^.val := p; o^.off := f^.val; |
| 2670 | try declare(o); |
| 2671 | f := f^.next; |
| 2672 | INC(n); |
| 2673 | Scan.next; |
| 2674 | if Scan.tok # Scan.sComma then break; end; |
| 2675 | Scan.next; |
| 2676 | until false; |
| 2677 | if f # nil then |
| 2678 | return Scan.mark(say1("name all the fields of {}, or none", nameOf(c^.name))); |
| 2679 | end; |
| 2680 | try expect(Scan.sRparen); |
| 2681 | end; |
| 2682 | try expect(Scan.sColon); |
| 2683 | for n := first to ls.n - 1 do ls.at[n] := Chunk.pc; end; |
| 2684 | try statements(); |
| 2685 | Sym.closeScope(); |
| 2686 | Gen.jump(endL); |
| 2687 | if t^.form # Sym.fEnum then Gen.fix(L); end; |
| 2688 | end; |
| 2689 | all := all and ends; |
| 2690 | end; |
| 2691 | endAt := Scan.tokPos(); |
| 2692 | try closeEnd(start, ind); |
| 2693 | ends := all; |
| 2694 | if (t^.form = Sym.fInt) and not hasElse then |
| 2695 | return Scan.markHelp(endAt, "a match on an integer needs an else arm", "it may be empty: | else:"); |
| 2696 | elsif isStr and not hasElse then |
| 2697 | return Scan.markHelp(endAt, "a match on a string needs an else arm", "it may be empty: | else:"); |
| 2698 | end; |
| 2699 | if not hasElse then |
| 2700 | c := t^.fields; |
| 2701 | while c # nil do |
| 2702 | if (c^.val > 255) or not seen[c^.val] then |
| 2703 | return Scan.markAt(endAt, say1("no arm for {}", nameOf(c^.name))); |
| 2704 | end; |
| 2705 | c := c^.next; |
| 2706 | end; |
| 2707 | end; |
| 2708 | if byValue then |
| 2709 | Gen.fix(disp); |
| 2710 | dispatch(t, p, ls, elseAt, endL); |
| 2711 | end; |
| 2712 | Gen.fix(endL); |
| 2713 | return nil; |
| 2714 | end; |
| 2715 | |
| 2716 | (* What a message calls x: its name n when x is just that name, else what |
| 2717 | it is. *) |
| 2718 | proc subject(x: TItem; n: INT): []const U8; |
| 2719 | begin |
| 2720 | if x.pos.b - x.pos.a = LEN(nameOf(n)) then return nameOf(n); end; |
| 2721 | if x.mode = Item.mConst then return "a constant"; end; |
| 2722 | return "a value"; |
| 2723 | end; |
| 2724 | |
| 2725 | (* x, named first n, is a variable the program may assign: not an |
| 2726 | array constant, nor any part of one. *) |
| 2727 | proc assignable(const x: TItem; n: INT): ERROR; |
| 2728 | begin |
| 2729 | if (x.mode = Item.mConst) and (subject(x, n) = nameOf(n)) then |
| 2730 | return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(n))); |
| 2731 | end; |
| 2732 | if (x.mode = Item.mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst) then |
| 2733 | return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(x.obj^.name))); |
| 2734 | end; |
| 2735 | if (x.mode # Item.mVar) or not x.isVar then |
| 2736 | return Scan.markAt(x.pos, say1("can't assign to {}", subject(x, n))); |
| 2737 | end; |
| 2738 | return nil; |
| 2739 | end; |
| 2740 | |
| 2741 | (* The designator a statement starts with. A variable named whole |
| 2742 | before := is assigned, not read: naming it there leaves it as unread |
| 2743 | as it was. *) |
| 2744 | proc leftSide(var x: TItem; var called: BOOL): ERROR; |
| 2745 | var o: PObj; wasRead: BOOL; n: INT; |
| 2746 | begin |
| 2747 | n := Scan.id; |
| 2748 | o := Sym.lookup(n); |
| 2749 | wasRead := (o # nil) and o^.read; |
| 2750 | try designator(x, called); |
| 2751 | if ((Scan.tok = Scan.sBecomes) or (Scan.tok = Scan.sComma)) and (x.pos.b - x.pos.a = LEN(nameOf(n))) then |
| 2752 | o^.read := wasRead; |
| 2753 | end; |
| 2754 | return nil; |
| 2755 | end; |
| 2756 | |
| 2757 | (* a, b := f(x): the variables first, left to right, then the call; |
| 2758 | then each result to its variable, in order. x is the first variable, |
| 2759 | first its name, blank whether it is _. *) |
| 2760 | proc multiAssign(var x: TItem; first: INT; blank: BOOL): ERROR; |
| 2761 | var |
| 2762 | d: [16]TItem; dn: [16]INT; blanks: [16]BOOL; |
| 2763 | y, z: TItem; n, i: INT; called: BOOL; f: PObj; |
| 2764 | begin |
| 2765 | n := 0; |
| 2766 | d[0] := x; |
| 2767 | dn[0] := first; |
| 2768 | blanks[0] := blank; |
| 2769 | repeat |
| 2770 | if not blanks[n] then |
| 2771 | try Item.notReadOnly(d[n]); |
| 2772 | try assignable(d[n], dn[n]); |
| 2773 | try Item.pin(d[n]); (* works out the address now, so that the call can't change it *) |
| 2774 | end; |
| 2775 | INC(n); |
| 2776 | if Scan.tok # Scan.sComma then break; end; |
| 2777 | if n > 15 then return Scan.mark(tooMany(16, "variables in one assignment")); end; |
| 2778 | Scan.next; |
| 2779 | blanks[n] := Scan.tok = Scan.sBlank; |
| 2780 | if blanks[n] then |
| 2781 | Scan.next; |
| 2782 | else |
| 2783 | dn[n] := Scan.id; |
| 2784 | try leftSide(d[n], called); |
| 2785 | end; |
| 2786 | until false; |
| 2787 | try expect(Scan.sBecomes); |
| 2788 | if Scan.tok = Scan.sTry then |
| 2789 | try tryCall(y); |
| 2790 | called := true; |
| 2791 | else |
| 2792 | try designator(y, called); |
| 2793 | end; |
| 2794 | if not called or not y.typ^.tuple or (y.typ^.len # I64(n)) then |
| 2795 | return Scan.markAt(y.pos, Diag.say("expected a call with {} results", [Fmt.int(n)])); |
| 2796 | end; |
| 2797 | (* two results on the stack: the first is brought to the top, and each |
| 2798 | is popped into its variable in turn, as one value; else each is |
| 2799 | read from the temporary they came back in *) |
| 2800 | if y.mode = Item.mWords then Gen.swap(); end; |
| 2801 | f := y.typ^.fields; |
| 2802 | for i := 0 to n - 1 do |
| 2803 | z := y; |
| 2804 | if y.mode = Item.mWords then |
| 2805 | z.mode := Item.mStack; z.typ := f^.typ; |
| 2806 | else |
| 2807 | try Item.field(z, f); |
| 2808 | end; |
| 2809 | if blanks[i] then |
| 2810 | try Item.discard(z); |
| 2811 | else |
| 2812 | (* an INT result widens to an I64 variable; an I64 result |
| 2813 | into an INT is written, but not here, in the call *) |
| 2814 | if Item.widens(d[i].typ, z.typ) then |
| 2815 | return Scan.markAt(y.pos, Diag.say("result {} is {}, which can't go to {}", |
| 2816 | [Fmt.int(i + 1), Fmt.str(Sym.typeName(z.typ)), Fmt.str(Sym.typeName(d[i].typ))])); |
| 2817 | end; |
| 2818 | try Item.coerce(z, d[i].typ); |
| 2819 | try Item.assign(d[i], z); |
| 2820 | end; |
| 2821 | f := f^.next; |
| 2822 | end; |
| 2823 | return nil; |
| 2824 | end; |
| 2825 | |
| 2826 | (* return a, b; or return f(x); with f's several results passed on *) |
| 2827 | proc returnResults: ERROR; |
| 2828 | var f: PObj; x: TItem; |
| 2829 | begin |
| 2830 | f := curResult^.fields; |
| 2831 | passOn := true; |
| 2832 | while f # nil do |
| 2833 | try expression(x, f^.typ); |
| 2834 | if x.typ^.tuple then |
| 2835 | if not Sym.same(x.typ, curResult) and not Item.resultsFit(x.typ, curResult) then |
| 2836 | return Scan.markAt(x.pos, say2("expected the results {}, found {}", Sym.typeName(curResult), Sym.typeName(x.typ))); |
| 2837 | end; |
| 2838 | return Item.returnAll(x); |
| 2839 | end; |
| 2840 | try Item.returnField(f, x); |
| 2841 | f := f^.next; |
| 2842 | if f # nil then try expect(Scan.sComma); end; |
| 2843 | end; |
| 2844 | return nil; |
| 2845 | end; |
| 2846 | |
| 2847 | (* defer s: s is compiled where it stands, as a little subroutine of the |
| 2848 | procedure, jumped over; each way out of the statement list calls it. *) |
| 2849 | proc deferStatement: ERROR; |
| 2850 | var L, pos, saved: INT; oldLoop: PLoop; oldDeferring: BOOL; start: Diag.Pos; |
| 2851 | begin |
| 2852 | start := Scan.tokPos(); |
| 2853 | Scan.next; |
| 2854 | if directDefer then return Scan.markAt(Scan.spanFrom(start), "defer can't be deferred"); end; |
| 2855 | if numDefers >= MaxDefers then |
| 2856 | return Scan.markAt(Scan.spanFrom(start), tooMany(MaxDefers, "deferred statements in one procedure")); |
| 2857 | end; |
| 2858 | L := Gen.NoLabel; |
| 2859 | pos, saved := Gen.deferBegin(L); |
| 2860 | oldLoop := curLoop; oldDeferring := deferring; |
| 2861 | curLoop := nil; |
| 2862 | deferring := true; |
| 2863 | directDefer := true; |
| 2864 | try statement(); |
| 2865 | directDefer := false; |
| 2866 | curLoop := oldLoop; deferring := oldDeferring; |
| 2867 | Gen.deferEnd(L, saved); |
| 2868 | defers[numDefers] := pos; |
| 2869 | INC(numDefers); |
| 2870 | return nil; |
| 2871 | end; |
| 2872 | |
| 2873 | (* Whether the expression of x := ..., which starts at the current |
| 2874 | symbol, is x changed by adding to it, taking from it or its bits: |
| 2875 | x + e, x - e, x | e or x xor e, with x nowhere in e, so that it can be |
| 2876 | worked out in x's own register, if x is in one (Gen's inPlace). *) |
| 2877 | proc changesItself(const x: TItem): BOOL; |
| 2878 | var st: Scan.State; wasSkipping, changes: BOOL; d: INT; |
| 2879 | begin |
| 2880 | if (x.mode # Item.mVar) or (x.base # Gen.bReg) or (x.typ^.form = Sym.fSlice) |
| 2881 | or (Scan.tok # Scan.sIdent) or (Scan.id # x.obj^.name) then |
| 2882 | return false; |
| 2883 | end; |
| 2884 | changes := false; |
| 2885 | Scan.saveScan(st); |
| 2886 | wasSkipping := Scan.skipping; |
| 2887 | Scan.setSkipping(true); (* its slips are told when it is compiled *) |
| 2888 | Scan.next; |
| 2889 | if isAddOp() then |
| 2890 | changes := true; |
| 2891 | d := 0; |
| 2892 | while not ((d = 0) and ((Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEnd))) and (Scan.tok # Scan.sEof) do |
| 2893 | if (Scan.tok = Scan.sIdent) and (Scan.id = x.obj^.name) then changes := false; end; |
| 2894 | match Scan.tok of |
| 2895 | | sLparen, sLbrak, sLbrace: INC(d); |
| 2896 | | sRparen, sRbrak, sRbrace: DEC(d); |
| 2897 | | else: |
| 2898 | end; |
| 2899 | Scan.next; |
| 2900 | end; |
| 2901 | end; |
| 2902 | Scan.restoreScan(st); |
| 2903 | Scan.setSkipping(wasSkipping); |
| 2904 | return changes; |
| 2905 | end; |
| 2906 | |
| 2907 | (* A call standing on its own, which drops the results x holds, if any, |
| 2908 | to be warned of *) |
| 2909 | proc noteDrop(const x: TItem); |
| 2910 | begin |
| 2911 | if (x.mode # Item.mNone) and (numDoubts < MaxDoubts) then |
| 2912 | doubts[numDoubts].at := x.pos; |
| 2913 | doubts[numDoubts].msg := ""; |
| 2914 | if x.typ^.tuple then doubts[numDoubts].n := INT(x.typ^.len); else doubts[numDoubts].n := 1; end; |
| 2915 | INC(numDoubts); |
| 2916 | end; |
| 2917 | end; |
| 2918 | |
| 2919 | proc oneStatement: ERROR; |
| 2920 | var |
| 2921 | x, y: TItem; called: BOOL; m: I64; c: Gen.CallInfo; start: Diag.Pos; first, n, i: INT; k: Gen.Kind; |
| 2922 | begin |
| 2923 | start := Scan.tokPos(); |
| 2924 | first := Scan.id; |
| 2925 | Chunk.noteLine(Scan.curLine(), Scan.curCol()); |
| 2926 | m := Gen.tempMark(); |
| 2927 | ends := false; |
| 2928 | match Scan.tok of |
| 2929 | | sIdent: |
| 2930 | try leftSide(x, called); |
| 2931 | if Scan.tok = Scan.sBecomes then |
| 2932 | try Item.notReadOnly(x); |
| 2933 | try assignable(x, first); |
| 2934 | Scan.next; |
| 2935 | if changesItself(x) then Gen.setInPlace(x.chunk); end; |
| 2936 | try expression(y, x.typ); |
| 2937 | Gen.setInPlace(-1); |
| 2938 | try Item.assign(x, y); |
| 2939 | elsif Scan.tok = Scan.sComma then |
| 2940 | try multiAssign(x, first, false); |
| 2941 | elsif not called then |
| 2942 | if (x.mode = Item.mProc) |
| 2943 | or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc)) then |
| 2944 | try Item.beginCall(c, x); |
| 2945 | try Item.endCall(c, x); |
| 2946 | try Item.discard(x); |
| 2947 | elsif Scan.tok = Scan.sEql then |
| 2948 | return Scan.markHelp(x.pos, say1("{} isn't a statement", subject(x, first)), "assignment is written :="); |
| 2949 | else |
| 2950 | return Scan.markAt(x.pos, say1("{} isn't a statement", subject(x, first))); |
| 2951 | end; |
| 2952 | else |
| 2953 | noteDrop(x); |
| 2954 | try Item.discard(x); |
| 2955 | end; |
| 2956 | | sBlank: |
| 2957 | Scan.next; |
| 2958 | if Scan.tok = Scan.sComma then |
| 2959 | try multiAssign(x, 0, true); |
| 2960 | else |
| 2961 | try expect(Scan.sBecomes); |
| 2962 | try expression(x, nil); |
| 2963 | (* evaluated and dropped: a single value is loaded, so that a |
| 2964 | volatile one is read *) |
| 2965 | if (x.mode = Item.mType) or (x.mode = Item.mBuiltin) or (x.mode = Item.mNone) or (x.mode = Item.mCase) |
| 2966 | or ((x.mode # Item.mStr) and not Sym.isAggregate(x.typ)) then |
| 2967 | try Item.value(x); |
| 2968 | end; |
| 2969 | try Item.discard(x); |
| 2970 | end; |
| 2971 | | sIf: try ifStatement(start, Scan.indent()); |
| 2972 | | sWhile: try whileStatement(start, Scan.indent()); |
| 2973 | | sRepeat: try repeatStatement(); |
| 2974 | | sFor: try forStatement(start, Scan.indent()); |
| 2975 | | sMatch: try matchStatement(start, Scan.indent()); |
| 2976 | | sReturn: |
| 2977 | Scan.next; |
| 2978 | if deferring then return Scan.markAt(Scan.spanFrom(start), "return can't leave a deferred statement"); end; |
| 2979 | if Scan.tok = Scan.sSemicolon then |
| 2980 | runDefers(0); |
| 2981 | try Item.returnNone(); |
| 2982 | else |
| 2983 | if (curResult # nil) and curResult^.tuple then |
| 2984 | try returnResults(); |
| 2985 | else |
| 2986 | Item.literalInResult((Scan.tok = Scan.sLbrace) and (curResult # nil) |
| 2987 | and (curResult^.form = Sym.fRecord) and Sym.behindPointer(curResult)); |
| 2988 | try expression(x, curResult); |
| 2989 | Item.literalInResult(false); |
| 2990 | try Item.returnValue(x); |
| 2991 | end; |
| 2992 | (* the result, one value or two words on top, waits in the frame |
| 2993 | while the deferred statements run *) |
| 2994 | if (numDefers > 0) and (curResult # nil) and not Sym.behindPointer(curResult) then |
| 2995 | n := 1; k := Gen.kindOf(curResult); |
| 2996 | if Sym.inTwoRegs(curResult) then n := 2; k := Gen.kWord; end; |
| 2997 | if deferSlot = 0 then deferSlot := Gen.allocPerm(16, 8); end; |
| 2998 | for i := n - 1 to 0 by -1 do Gen.popVar(Item.frameAdr(deferSlot + I64(8 * i)), 8); end; |
| 2999 | runDefers(0); |
| 3000 | for i := 0 to n - 1 do Gen.pushVar(Item.frameAdr(deferSlot + I64(8 * i)), 8, false, k); end; |
| 3001 | else |
| 3002 | runDefers(0); |
| 3003 | end; |
| 3004 | Gen.returnJump(); |
| 3005 | ends := true; |
| 3006 | if returnEnd < 0 then |
| 3007 | returnEnd := Scan.afterPrev().a; |
| 3008 | if Scan.tok = Scan.sSemicolon then returnEnd := Scan.tokStart() + 1; end; |
| 3009 | end; |
| 3010 | end; |
| 3011 | | sBreak: |
| 3012 | Scan.next; |
| 3013 | if curLoop = nil then return Scan.markAt(Scan.spanFrom(start), "break outside a loop"); end; |
| 3014 | runDefers(curLoop^.base); |
| 3015 | Gen.jump(curLoop^.brk); |
| 3016 | | sContinue: |
| 3017 | Scan.next; |
| 3018 | if curLoop = nil then return Scan.markAt(Scan.spanFrom(start), "continue outside a loop"); end; |
| 3019 | runDefers(curLoop^.base); |
| 3020 | Gen.jump(curLoop^.cont); |
| 3021 | | sDefer: try deferStatement(); |
| 3022 | | sTry: |
| 3023 | try tryCall(x); |
| 3024 | noteDrop(x); |
| 3025 | try Item.discard(x); |
| 3026 | | sArrow: |
| 3027 | return Scan.markHelp(Scan.tokPos(), "a statement starts with a name", |
| 3028 | "convert into a pointer variable, then assign through that"); |
| 3029 | | else: |
| 3030 | if Scan.atLineStart() then |
| 3031 | return endMissing(Scan.missingPos(), say1("expected \"end\", found {}", Scan.found())); |
| 3032 | end; |
| 3033 | return expected("a statement"); |
| 3034 | end; |
| 3035 | Gen.releaseTemps(m); |
| 3036 | return nil; |
| 3037 | end; |
| 3038 | |
| 3039 | proc statement: ERROR; |
| 3040 | var r: Recover; m: I64; err: ERROR; |
| 3041 | begin |
| 3042 | m := Gen.tempMark(); |
| 3043 | guard(r); |
| 3044 | INC(nest); |
| 3045 | if nest > MaxNest then err := tooDeep(); else err := oneStatement(); end; |
| 3046 | if err = nil then |
| 3047 | DEC(nest); |
| 3048 | skipped := false; |
| 3049 | else |
| 3050 | restore(r); |
| 3051 | (* a statement never starts a line: this is the next declaration *) |
| 3052 | if Scan.atLineStart() or not skipConstruct() then return giveUp(r); end; |
| 3053 | Gen.releaseTemps(m); |
| 3054 | skipped := true; |
| 3055 | end; |
| 3056 | unguard(r); |
| 3057 | return nil; |
| 3058 | end; |
| 3059 | |
| 3060 | proc endsStatements: BOOL; |
| 3061 | begin |
| 3062 | match Scan.tok of |
| 3063 | | sEnd, sElse, sElsif, sUntil, sBar, sEof: return true; |
| 3064 | | else: return false; |
| 3065 | end; |
| 3066 | end; |
| 3067 | |
| 3068 | proc statements: ERROR; |
| 3069 | var base: INT; old: BOOL; |
| 3070 | begin |
| 3071 | base := numDefers; |
| 3072 | old := directDefer; |
| 3073 | directDefer := false; |
| 3074 | ends := false; |
| 3075 | while not endsStatements() do |
| 3076 | try statement(); |
| 3077 | if not skipped or (Scan.tok = Scan.sSemicolon) then try expect(Scan.sSemicolon); end; |
| 3078 | end; |
| 3079 | runDefers(base); |
| 3080 | numDefers := base; |
| 3081 | directDefer := old; |
| 3082 | return nil; |
| 3083 | end; |
| 3084 | |
| 3085 | (* Declarations *) |
| 3086 | |
| 3087 | (* In a file read for its interface only: skip a procedure's body, from |
| 3088 | its local declarations to the end that closes it. *) |
| 3089 | proc skipBody: ERROR; |
| 3090 | var d: INT; sawBegin: BOOL; |
| 3091 | begin |
| 3092 | d := 0; |
| 3093 | sawBegin := false; |
| 3094 | repeat |
| 3095 | match Scan.tok of |
| 3096 | | sBegin: |
| 3097 | if d = 0 then sawBegin := true; end; |
| 3098 | INC(d); |
| 3099 | | sIf, sWhile, sFor, sMatch, sRecord, sVariant: INC(d); |
| 3100 | | sEnd: |
| 3101 | DEC(d); |
| 3102 | if (d = 0) and sawBegin then |
| 3103 | Scan.next; |
| 3104 | return nil; |
| 3105 | end; |
| 3106 | | sEof: return expected("\"end\""); |
| 3107 | | else: |
| 3108 | end; |
| 3109 | Scan.next; |
| 3110 | until false; |
| 3111 | return nil; |
| 3112 | end; |
| 3113 | |
| 3114 | proc declarations(top: BOOL); forward; |
| 3115 | |
| 3116 | (* How Rt shows a variable of o's type in the trap report: 1 a signed |
| 3117 | integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus |
| 3118 | its size times 16, and 256 if the frame holds its address, or 512 |
| 3119 | times 1 + i if it is in register ShownRegs[i]; 0 if it isn't shown. *) |
| 3120 | proc varKind(o: PObj): INT; |
| 3121 | var k, i, v: INT; |
| 3122 | begin |
| 3123 | if o^.ind and (o^.reg # 0) then return 0; end; (* the address is in a register, not shown *) |
| 3124 | match o^.typ^.form of |
| 3125 | | fInt: if o^.typ^.signed then k := 1; else k := 2; end; |
| 3126 | | fEnum, fSet: k := 2; |
| 3127 | | fBool: k := 3; |
| 3128 | | fPtr, fProc, fError: k := 4; |
| 3129 | | fReal: k := 5; |
| 3130 | | else: return 0; |
| 3131 | end; |
| 3132 | v := k + INT(o^.typ^.size) * 16; |
| 3133 | if o^.ind then v := v + 256; end; |
| 3134 | for i := 0 to LEN(Gen.ShownRegs) - 1 do |
| 3135 | if o^.reg = Gen.ShownRegs[i] then v := k + INT(o^.typ^.size) * 16 + (i + 1) * 512; end; |
| 3136 | end; |
| 3137 | return v; |
| 3138 | end; |
| 3139 | |
| 3140 | (* Whether variable o could live in registers: a single value, a real |
| 3141 | in an xmm register, or a slice, in two, that isn't C's *) |
| 3142 | proc regFit(o: PObj): BOOL; |
| 3143 | var f: Sym.Form; |
| 3144 | begin |
| 3145 | if (o^.cls # Sym.oVar) or o^.ext then return false; end; |
| 3146 | (* a parameter passed by its address keeps the address in the register *) |
| 3147 | if o^.ind then return o^.param; end; |
| 3148 | f := o^.typ^.form; |
| 3149 | return (f = Sym.fInt) or (f = Sym.fBool) or (f = Sym.fEnum) or (f = Sym.fPtr) or (f = Sym.fProc) |
| 3150 | or (f = Sym.fError) or (f = Sym.fSlice) or (f = Sym.fReal) |
| 3151 | or ((f = Sym.fSet) and (o^.typ^.size <= 8)); |
| 3152 | end; |
| 3153 | |
| 3154 | (* The first local of the procedure being compiled. Locals are chained |
| 3155 | by chain in the order declared, the module's own first; before is the |
| 3156 | last one declared before the procedure's, or nil if there was none. *) |
| 3157 | proc firstLocal(before: PObj): PObj; |
| 3158 | begin |
| 3159 | if before = nil then return Sym.curModule^.locals; end; |
| 3160 | return before^.chain; |
| 3161 | end; |
| 3162 | |
| 3163 | const MaxCand = 64; (* variables of a procedure that may go in registers *) |
| 3164 | |
| 3165 | var |
| 3166 | cand: [MaxCand]PObj; (* chooseRegs's candidates and their weights *) |
| 3167 | weight: [MaxCand]INT; |
| 3168 | numCand: INT; |
| 3169 | |
| 3170 | proc candidate(n: INT): INT; |
| 3171 | var j: INT; |
| 3172 | begin |
| 3173 | for j := 0 to numCand - 1 do |
| 3174 | if cand[j]^.name = n then return j; end; |
| 3175 | end; |
| 3176 | return -1; |
| 3177 | end; |
| 3178 | |
| 3179 | proc addCandidate(o: PObj); |
| 3180 | begin |
| 3181 | if regFit(o) and (numCand < MaxCand) then |
| 3182 | cand[numCand] := o; |
| 3183 | weight[numCand] := 0; |
| 3184 | INC(numCand); |
| 3185 | end; |
| 3186 | end; |
| 3187 | |
| 3188 | (* Whether naming o may make a call: a procedure (not one made in place |
| 3189 | whose expression calls none), a procedure variable, |
| 3190 | or NEW, SYSCALL, COPY or FILL, which use the registers a call would *) |
| 3191 | proc calls(o: PObj): BOOL; |
| 3192 | begin |
| 3193 | if o = nil then return false; end; |
| 3194 | return ((o^.cls = Sym.oProc) and (o^.inl = 0) and ((o^.ret = nil) or o^.ret^.calls)) or ((o^.cls = Sym.oVar) and (o^.typ^.form = Sym.fProc)) |
| 3195 | or ((o^.cls = Sym.oBuiltin) and ((o^.val = Sym.bNew) or (o^.val = Sym.bSyscall) or (o^.val = Sym.bCopy) |
| 3196 | or (o^.val = Sym.bFill))); |
| 3197 | end; |
| 3198 | |
| 3199 | (* Puts the busiest variables of the procedure, whose parameters are |
| 3200 | params and whose locals follow before, in registers: read ahead from |
| 3201 | its "begin" to its end, a use counts 1, in a loop 4, in two 16, in |
| 3202 | three or more 64, and a variable ADR, CAS, XCHG or XADD is given |
| 3203 | can't have one, since they need its address. A register costs a save |
| 3204 | and a restore, so a variable used less than three times keeps its |
| 3205 | place in memory. A slice takes two, its pointer's and its length's; |
| 3206 | a real one of the xmm registers, stored and loaded again around each |
| 3207 | call, as System V keeps none through one. In a procedure that names no procedure, so calls nothing, the |
| 3208 | parameters that arrive in the registers no call needs stay there |
| 3209 | (keepArrived), at no cost. *) |
| 3210 | proc chooseRegs(params, before: PObj); |
| 3211 | var |
| 3212 | isLoop: [256]BOOL; |
| 3213 | forAt: [256]INT; (* the for loop opened at each depth, or -1 *) |
| 3214 | i, k, kx, xmax, d, loops, best, need, nf, inLim: INT; o, q, qual: PObj; st: Scan.State; |
| 3215 | afterDot, wasSkipping, leaf: BOOL; |
| 3216 | begin |
| 3217 | numCand := 0; |
| 3218 | limitK := -1; nf := 0; inLim := -1; |
| 3219 | o := params; |
| 3220 | while o # nil do addCandidate(o); o := o^.next; end; |
| 3221 | o := firstLocal(before); |
| 3222 | while o # nil do addCandidate(o); o := o^.chain; end; |
| 3223 | if numCand = 0 then return; end; |
| 3224 | Scan.saveScan(st); |
| 3225 | wasSkipping := Scan.skipping; |
| 3226 | Scan.setSkipping(true); (* its slips are told when it is compiled *) |
| 3227 | d := 0; loops := 0; afterDot := false; leaf := true; qual := nil; |
| 3228 | repeat |
| 3229 | (* a name, or a module's name and one of its exports, that calls; |
| 3230 | once one has, the rest needn't be looked up *) |
| 3231 | if leaf then |
| 3232 | if (Scan.tok = Scan.sIdent) and not afterDot then |
| 3233 | q := Sym.lookup(Scan.id); |
| 3234 | if calls(q) then leaf := false; end; |
| 3235 | qual := nil; |
| 3236 | if (q # nil) and (q^.cls = Sym.oModule) then qual := q; end; |
| 3237 | elsif (Scan.tok = Scan.sIdent) and (qual # nil) then |
| 3238 | if (qual^.home = nil) or calls(Sym.find(qual^.home^.scope, Scan.id)) then leaf := false; end; |
| 3239 | qual := nil; |
| 3240 | end; |
| 3241 | end; |
| 3242 | match Scan.tok of |
| 3243 | | sBegin, sIf, sMatch, sWhile, sFor, sRepeat: |
| 3244 | if d < 255 then |
| 3245 | INC(d); |
| 3246 | isLoop[d] := (Scan.tok = Scan.sWhile) or (Scan.tok = Scan.sFor) or (Scan.tok = Scan.sRepeat); |
| 3247 | if isLoop[d] then INC(loops); end; |
| 3248 | forAt[d] := -1; |
| 3249 | if (Scan.tok = Scan.sFor) and (nf < MaxFors) then |
| 3250 | (* innermost until a for is found inside it; its |
| 3251 | limit constant until a name in it isn't one *) |
| 3252 | forAt[d] := nf; limitIn[nf] := false; |
| 3253 | i := d - 1; |
| 3254 | while (i > 0) and (forAt[i] < 0) do DEC(i); end; |
| 3255 | if i > 0 then limitIn[forAt[i]] := false; end; |
| 3256 | INC(nf); |
| 3257 | end; |
| 3258 | end; |
| 3259 | | sTo: if (d > 0) and (forAt[d] >= 0) then inLim := forAt[d]; end; |
| 3260 | | sDo, sBy: inLim := -1; |
| 3261 | | sEnd, sUntil: |
| 3262 | (* an end with no begin before it, in a body the parser will |
| 3263 | report, leaves d at 0 *) |
| 3264 | if d > 0 then |
| 3265 | if isLoop[d] then DEC(loops); end; |
| 3266 | DEC(d); |
| 3267 | end; |
| 3268 | | sIdent: |
| 3269 | if (Scan.id = nameAdr) or (Scan.id = nameCas) or (Scan.id = nameXchg) or (Scan.id = nameXadd) then |
| 3270 | Scan.next; |
| 3271 | if Scan.tok = Scan.sLparen then Scan.next; end; |
| 3272 | (* a hugely negative weight bars it from a register, whatever |
| 3273 | its uses add *) |
| 3274 | if (Scan.tok = Scan.sIdent) and (candidate(Scan.id) >= 0) then weight[candidate(Scan.id)] := -1073741824; end; |
| 3275 | elsif not afterDot and (candidate(Scan.id) >= 0) then |
| 3276 | k := candidate(Scan.id); |
| 3277 | if loops > 2 then INC(weight[k], 64); else INC(weight[k], 1 shl (2 * loops)); end; |
| 3278 | end; |
| 3279 | if (inLim >= 0) and not afterDot then |
| 3280 | q := Sym.lookup(Scan.id); |
| 3281 | if (q = nil) or (q^.cls # Sym.oConst) then limitIn[inLim] := true; end; |
| 3282 | end; |
| 3283 | | else: |
| 3284 | end; |
| 3285 | afterDot := Scan.tok = Scan.sPeriod; (* a name after a dot is a field, not a variable *) |
| 3286 | if (d > 0) and (Scan.tok # Scan.sEof) then Scan.next; end; |
| 3287 | until (d = 0) or (Scan.tok = Scan.sEof); |
| 3288 | Scan.restoreScan(st); |
| 3289 | Scan.setSkipping(wasSkipping); |
| 3290 | if leaf then |
| 3291 | o := params; |
| 3292 | while o # nil do |
| 3293 | k := candidate(o^.name); |
| 3294 | if (k >= 0) and (weight[k] >= 0) then Gen.keepArrived(o); end; (* a candidate whose ADR isn't taken *) |
| 3295 | o := o^.next; |
| 3296 | end; |
| 3297 | end; |
| 3298 | (* xmm4 to xmm7 too, where no call or real parameter needs them *) |
| 3299 | xmax := 4; |
| 3300 | if leaf then |
| 3301 | xmax := 8; |
| 3302 | o := params; i := 0; |
| 3303 | while o # nil do |
| 3304 | if (o^.typ^.form = Sym.fReal) and not o^.isVar then INC(i); end; |
| 3305 | o := o^.next; |
| 3306 | end; |
| 3307 | if i > 4 then xmax := 4; end; |
| 3308 | end; |
| 3309 | (* a slice's weight is shared by its two registers; one passed by |
| 3310 | its address has one *) |
| 3311 | for i := 0 to numCand - 1 do |
| 3312 | if (cand[i]^.typ^.form = Sym.fSlice) and not cand[i]^.ind then weight[i] := weight[i] div 2; end; |
| 3313 | end; |
| 3314 | (* the heaviest, each used at least three times a register, take the |
| 3315 | five registers in turn, while there are enough for each, and the |
| 3316 | reals xmax of the xmm registers of XVarRegs *) |
| 3317 | k := 0; kx := 0; |
| 3318 | repeat |
| 3319 | best := -1; |
| 3320 | for i := 0 to numCand - 1 do |
| 3321 | if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i; end; |
| 3322 | end; |
| 3323 | if best < 0 then break; end; |
| 3324 | (* a parameter passed by its address (ind) holds the address, one |
| 3325 | integer register whatever its type: a var real's address in |
| 3326 | an xmm register would be moved, by the prologue, into the |
| 3327 | integer register of the same number, another variable's *) |
| 3328 | need := 1; |
| 3329 | if (cand[best]^.typ^.form = Sym.fSlice) and not cand[best]^.ind then need := 2; end; |
| 3330 | if (cand[best]^.typ^.form = Sym.fReal) and not cand[best]^.ind then |
| 3331 | if kx < xmax then |
| 3332 | cand[best]^.reg := Gen.XVarRegs[kx]; |
| 3333 | INC(kx); |
| 3334 | else |
| 3335 | weight[best] := 0; |
| 3336 | end; |
| 3337 | elsif k + need <= 5 then |
| 3338 | cand[best]^.reg := Gen.VarRegs[k]; |
| 3339 | if need = 2 then cand[best]^.reg2 := Gen.VarRegs[k + 1]; end; |
| 3340 | INC(k, need); |
| 3341 | else |
| 3342 | weight[best] := 0; (* too big for what is left *) |
| 3343 | end; |
| 3344 | until false; |
| 3345 | for i := 0 to nf - 1 do |
| 3346 | if limitIn[i] and (k < 5) then limitK := k; end; |
| 3347 | end; |
| 3348 | end; |
| 3349 | |
| 3350 | (* The registers the variables of the procedure are in, as bits: bit i |
| 3351 | is VarRegs[i], bit XBit + i XVarRegs[i] *) |
| 3352 | proc regBits(o: PObj): INT; |
| 3353 | var m, k: INT; |
| 3354 | begin |
| 3355 | m := 0; |
| 3356 | for k := 0 to 4 do |
| 3357 | if (o^.reg = Gen.VarRegs[k]) or (o^.reg2 = Gen.VarRegs[k]) then m := m | (1 shl k); end; |
| 3358 | end; |
| 3359 | for k := 0 to LEN(Gen.XVarRegs) - 1 do |
| 3360 | if o^.reg = Gen.XVarRegs[k] then m := m | (1 shl (Gen.XBit + k)); end; |
| 3361 | end; |
| 3362 | return m; |
| 3363 | end; |
| 3364 | |
| 3365 | proc regsOf(params, before: PObj): INT; |
| 3366 | var o: PObj; m: INT; |
| 3367 | begin |
| 3368 | m := 0; |
| 3369 | o := params; |
| 3370 | while o # nil do |
| 3371 | m := m | regBits(o); |
| 3372 | o := o^.next; |
| 3373 | end; |
| 3374 | o := firstLocal(before); |
| 3375 | while o # nil do |
| 3376 | if o^.cls = Sym.oVar then m := m | regBits(o); end; |
| 3377 | o := o^.chain; |
| 3378 | end; |
| 3379 | if limitK >= 0 then m := m | (1 shl limitK); end; |
| 3380 | return m; |
| 3381 | end; |
| 3382 | |
| 3383 | (* Parameter o, kept where it arrived until a call or a copy wanted rdi |
| 3384 | or rsi, takes the registers of VarRegs that m, the taken ones, leaves, |
| 3385 | if it is used enough for them (chooseRegs's weight of 3) and there |
| 3386 | are enough; else it goes to memory. *) |
| 3387 | proc unkeep(o: PObj; m: INT); |
| 3388 | var k: INT; two: BOOL; |
| 3389 | begin |
| 3390 | two := o^.reg2 # 0; |
| 3391 | o^.reg := 0; o^.reg2 := 0; |
| 3392 | if weight[candidate(o^.name)] < 3 then return; end; |
| 3393 | for k := 0 to 4 do |
| 3394 | if (m & (1 shl k)) = 0 then |
| 3395 | if o^.reg = 0 then o^.reg := Gen.VarRegs[k]; |
| 3396 | elsif two and (o^.reg2 = 0) then o^.reg2 := Gen.VarRegs[k]; end; |
| 3397 | end; |
| 3398 | end; |
| 3399 | if two and (o^.reg2 = 0) then o^.reg := 0; end; |
| 3400 | end; |
| 3401 | |
| 3402 | (* Gives each local not in a register its slot in the frame, the slots |
| 3403 | the prologue zeroes, and then tells Gen which registers the |
| 3404 | variables are in. A variable in a register has no slot: it starts at |
| 3405 | zero in its register, and the trap report finds it there. *) |
| 3406 | proc placeLocals(params, before: PObj); |
| 3407 | var o: PObj; |
| 3408 | begin |
| 3409 | Gen.resetLocals(); |
| 3410 | o := firstLocal(before); |
| 3411 | while o # nil do |
| 3412 | if (o^.cls = Sym.oVar) and (o^.reg = 0) then |
| 3413 | o^.val := Gen.allocPerm(o^.typ^.size, o^.typ^.align); |
| 3414 | elsif (o^.cls = Sym.oVar) and (o^.reg >= Gen.XmmVar) then |
| 3415 | o^.val := Gen.allocPerm(8, 8); |
| 3416 | Gen.xHome(o^.reg, o^.val); |
| 3417 | end; |
| 3418 | o := o^.chain; |
| 3419 | end; |
| 3420 | o := params; |
| 3421 | while o # nil do |
| 3422 | if o^.reg >= Gen.XmmVar then Gen.xHome(o^.reg, o^.val); end; |
| 3423 | o := o^.next; |
| 3424 | end; |
| 3425 | Gen.useRegs(regsOf(params, before)); |
| 3426 | end; |
| 3427 | |
| 3428 | (* p, whose body is only return e, e read from at, is made in place of |
| 3429 | a call (inlined) if it returns a single value. *) |
| 3430 | proc onlyReturns(p: PObj; sig: PType; const at: Scan.State; calls: BOOL); |
| 3431 | begin |
| 3432 | if (sig^.base = nil) or not Sym.isScalar(sig^.base) then return; end; |
| 3433 | NEW(p^.ret, Heap.heap); |
| 3434 | if p^.ret = nil then Diag.fatal("out of memory"); end; |
| 3435 | p^.ret^.at := at; |
| 3436 | p^.ret^.path := Chunk.curFilePath(); |
| 3437 | p^.ret^.checks := Item.checks; |
| 3438 | p^.ret^.calls := calls; |
| 3439 | end; |
| 3440 | |
| 3441 | proc body(p: PObj; sig: PType; line: INT): ERROR; |
| 3442 | var |
| 3443 | q, params, last, o, before: PObj; old: PType; st, at: Scan.State; |
| 3444 | mark: Gen.CodeMark; doubts0, errs, calls0: INT; first, only: BOOL; |
| 3445 | begin |
| 3446 | try Sym.openScope(Sym.newScope()); |
| 3447 | params := nil; last := nil; |
| 3448 | q := sig^.fields; |
| 3449 | while q # nil do |
| 3450 | o := Sym.newObj(Sym.oVar, q^.name, q^.typ); |
| 3451 | o^.pos := q^.pos; |
| 3452 | o^.lev := 1; |
| 3453 | o^.isVar := q^.isVar; |
| 3454 | o^.isConst := q^.isConst; |
| 3455 | o^.param := true; |
| 3456 | if last = nil then params := o; else last^.next := o; end; |
| 3457 | last := o; |
| 3458 | q := q^.next; |
| 3459 | end; |
| 3460 | Item.beginProc(sig, params); |
| 3461 | deferSlot := 0; |
| 3462 | o := params; |
| 3463 | while o # nil do |
| 3464 | q := o^.next; |
| 3465 | try declare(o); |
| 3466 | o := q; |
| 3467 | end; |
| 3468 | curProc := p; |
| 3469 | before := Sym.curModule^.lastLocal; |
| 3470 | declarations(false); |
| 3471 | chooseRegs(params, before); |
| 3472 | placeLocals(params, before); |
| 3473 | (* the body, made again if a variable in a register must be in memory *) |
| 3474 | Scan.saveScan(st); |
| 3475 | Gen.markCode(mark); doubts0 := numDoubts; errs := Diag.errors; |
| 3476 | old := curResult; |
| 3477 | repeat |
| 3478 | Item.setDemoted(false); |
| 3479 | try expect(Scan.sBegin); |
| 3480 | curResult := sig^.base; |
| 3481 | Gen.enterBody(p^.chunk, line); |
| 3482 | stray := false; elseIf := false; deferSlot := 0; numFors := 0; |
| 3483 | first := Scan.tok = Scan.sReturn; |
| 3484 | Scan.saveScan(at); returnEnd := -1; sawTry := false; calls0 := numCalls; |
| 3485 | try statements(); |
| 3486 | only := first and (Scan.tok = Scan.sEnd) and (Scan.afterPrev().a = returnEnd) and not sawTry; |
| 3487 | p^.openEnd := (curResult # nil) and not ends; |
| 3488 | Chunk.noteLine(Scan.curLine(), Scan.curCol()); |
| 3489 | try expect(Scan.sEnd); |
| 3490 | if not (Item.demoted or Gen.lost) or (Diag.errors # errs) then break; end; |
| 3491 | (* a parameter kept where it arrived goes to a free register of |
| 3492 | VarRegs, or to memory: a call or a copy wanted its register *) |
| 3493 | if Gen.lost then |
| 3494 | o := params; |
| 3495 | while o # nil do |
| 3496 | if Gen.keptIn(o) then unkeep(o, regsOf(params, before)); end; |
| 3497 | o := o^.next; |
| 3498 | end; |
| 3499 | end; |
| 3500 | numDoubts := doubts0; |
| 3501 | Gen.redo(mark); |
| 3502 | placeLocals(params, before); |
| 3503 | Scan.restoreScan(st); |
| 3504 | until false; |
| 3505 | try Gen.endProc(p^.chunk, p^.openEnd); |
| 3506 | if only and (Sym.curModule^.lastLocal = before) and (Diag.errors = errs) then |
| 3507 | onlyReturns(p, sig, at, numCalls # calls0); |
| 3508 | end; |
| 3509 | (* its parameters and variables, for the trap report *) |
| 3510 | o := firstLocal(before); |
| 3511 | q := params; |
| 3512 | while q # nil do |
| 3513 | if varKind(q) # 0 then Chunk.noteVar(p^.chunk, q^.name, INT(q^.val), varKind(q)); end; |
| 3514 | q := q^.next; |
| 3515 | end; |
| 3516 | while o # nil do |
| 3517 | if (o^.cls = Sym.oVar) and (varKind(o) # 0) then Chunk.noteVar(p^.chunk, o^.name, INT(o^.val), varKind(o)); end; |
| 3518 | o := o^.chain; |
| 3519 | end; |
| 3520 | curResult := old; |
| 3521 | curProc := nil; |
| 3522 | limitK := -1; |
| 3523 | Sym.closeScope(); |
| 3524 | return nil; |
| 3525 | end; |
| 3526 | |
| 3527 | (* An integer constant in a code procedure, for the assembler: a whole |
| 3528 | expression, or a single factor where an expression would read on |
| 3529 | too far *) |
| 3530 | proc asmConst(whole: BOOL): (I64, ERROR); |
| 3531 | var x: TItem; |
| 3532 | begin |
| 3533 | if whole then return constExpr(); end; |
| 3534 | try factor(x, nil); |
| 3535 | if not Sym.isInt(x.typ) then |
| 3536 | return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x))); |
| 3537 | end; |
| 3538 | return constValue(x); |
| 3539 | end; |
| 3540 | |
| 3541 | (* A procedure or a module variable named in a code procedure, for the |
| 3542 | assembler: it stands for its address (report section 8). Its chunk, |
| 3543 | the name read, bare or qualified as any other; -1, with nothing read, |
| 3544 | if the name at the scan is anything else, for the assembler to read as |
| 3545 | a constant. Being named, it is used, and the linker keeps it, as it |
| 3546 | keeps what a call reaches: by the fixup to its chunk. *) |
| 3547 | proc asmName: (INT, ERROR); |
| 3548 | var o: PObj; st: Scan.State; at: Diag.Pos; |
| 3549 | begin |
| 3550 | o := Sym.lookup(Scan.id); |
| 3551 | if (o = nil) or ((o^.cls # Sym.oModule) and (o^.cls # Sym.oProc) and (o^.cls # Sym.oVar)) then |
| 3552 | return -1, nil; |
| 3553 | end; |
| 3554 | Scan.saveScan(st); |
| 3555 | at := Scan.tokPos(); |
| 3556 | o := try qualIdent(); |
| 3557 | if (o^.cls = Sym.oProc) or ((o^.cls = Sym.oVar) and (o^.lev = 0)) then |
| 3558 | if o^.ext then |
| 3559 | return -1, Scan.markAt(Scan.spanFrom(at), say1("{} is C's: a code procedure names only raz's procedures and variables", nameOf(o^.name))); |
| 3560 | end; |
| 3561 | return o^.chunk, nil; |
| 3562 | end; |
| 3563 | Scan.restoreScan(st); |
| 3564 | return -1, nil; |
| 3565 | end; |
| 3566 | |
| 3567 | proc codeBody(p: PObj; sig: PType; at: Diag.Pos): ERROR; |
| 3568 | var q: PObj; ni, nf: INT; err: ERROR; |
| 3569 | begin |
| 3570 | ni := 0; nf := 0; |
| 3571 | q := sig^.fields; |
| 3572 | while q # nil do |
| 3573 | if not q^.isVar and (q^.typ^.form = Sym.fSlice) then |
| 3574 | INC(ni, 2); (* address, then length *) |
| 3575 | else |
| 3576 | if not q^.isVar and not Sym.isScalar(q^.typ) then |
| 3577 | return Scan.markAt(at, "a code procedure takes integers, BOOL, reals, pointers, procedures and slices"); |
| 3578 | end; |
| 3579 | if (q^.typ^.form = Sym.fReal) and not q^.isVar then INC(nf); else INC(ni); end; |
| 3580 | end; |
| 3581 | q := q^.next; |
| 3582 | end; |
| 3583 | if (ni > 6) or (nf > 8) or sig^.variadic then |
| 3584 | return Scan.markAt(at, "too many parameters for a code procedure"); |
| 3585 | end; |
| 3586 | if sig^.base # nil then |
| 3587 | if sig^.base^.tuple then |
| 3588 | q := sig^.base^.fields; |
| 3589 | if (sig^.base^.len # 2) or (q^.typ^.size # 8) or (q^.next^.typ^.size # 8) |
| 3590 | or not Sym.isScalar(q^.typ) or not Sym.isScalar(q^.next^.typ) |
| 3591 | or (q^.typ^.form = Sym.fReal) or (q^.next^.typ^.form = Sym.fReal) then |
| 3592 | return Scan.markAt(at, "a code procedure returns two results only in rax and rdx"); |
| 3593 | end; |
| 3594 | elsif not Sym.isScalar(sig^.base) and (sig^.base^.form # Sym.fSlice) then |
| 3595 | return Scan.markAt(at, "a code procedure returns a single value"); |
| 3596 | end; |
| 3597 | end; |
| 3598 | (* in a scope of its own, so that a name it uses and isn't declared, |
| 3599 | declared then as poison, is gone at its end, as a procedure's |
| 3600 | locals are, and doesn't clash with a declaration after it *) |
| 3601 | try Sym.openScope(Sym.newScope()); |
| 3602 | err := Gen.codeProc(p^.chunk, asmConst, asmName); |
| 3603 | Sym.closeScope; |
| 3604 | if err # nil then return err; end; |
| 3605 | (* a square root of one real, of its own kind, is made in place *) |
| 3606 | q := sig^.fields; |
| 3607 | if (q # nil) and (q^.next = nil) and not q^.isVar and (q^.typ^.form = Sym.fReal) |
| 3608 | and (sig^.base # nil) and Sym.same(sig^.base, q^.typ) then |
| 3609 | p^.inl := Gen.oneRealOp(p^.chunk, q^.typ^.size = 4); |
| 3610 | end; |
| 3611 | return expect(Scan.sEnd); |
| 3612 | end; |
| 3613 | |
| 3614 | proc procDecl: ERROR; |
| 3615 | var n, line: INT; exp: BOOL; sig: PType; p: PObj; at: Diag.Pos; |
| 3616 | begin |
| 3617 | try instancesFor(false); |
| 3618 | line := Scan.curLine(); |
| 3619 | Scan.next; |
| 3620 | try identDef(n, exp, at); |
| 3621 | sig := try signature(); |
| 3622 | try expect(Scan.sSemicolon); |
| 3623 | p := Sym.find(Sym.topScope(), n); |
| 3624 | if (p # nil) and (p^.cls = Sym.oProc) and p^.fwd then |
| 3625 | if not Sym.same(p^.typ, sig) then |
| 3626 | Diag.error(at, say1("{} doesn't have the signature it was declared forward with", nameOf(n))); |
| 3627 | Diag.note(p^.pos, "the signature is here"); |
| 3628 | return Scan.Failed; |
| 3629 | end; |
| 3630 | if Scan.tok = Scan.sForward then return Scan.mark(say1("{} is declared forward twice", nameOf(n))); end; |
| 3631 | p^.exported := p^.exported or exp; |
| 3632 | else |
| 3633 | p := Sym.newObj(Sym.oProc, n, sig); |
| 3634 | p^.pos := at; |
| 3635 | p^.exported := exp; |
| 3636 | if (Sym.curModule^.name = nameRt) and not checkMode and (n = nameFail) then |
| 3637 | p^.chunk := Gen.rtFail; |
| 3638 | else |
| 3639 | p^.chunk := Chunk.newChunk(Chunk.secText, Sym.curModule^.sname, n); |
| 3640 | end; |
| 3641 | try declare(p); |
| 3642 | end; |
| 3643 | if Scan.tok = Scan.sForward then |
| 3644 | Scan.next; |
| 3645 | p^.fwd := true; |
| 3646 | return nil; |
| 3647 | end; |
| 3648 | p^.fwd := false; |
| 3649 | if Scan.tok = Scan.sCode then |
| 3650 | _ := Item.needSystem(Scan.tokPos(), "a code procedure"); (* said, and the declaration read on *) |
| 3651 | Scan.next; |
| 3652 | p^.isCode := true; |
| 3653 | if checkMode then |
| 3654 | (* a file of another target's, read for its interface: its code |
| 3655 | is in that machine's assembly, which this one's can't read; |
| 3656 | ! is a symbol there, as A64's assembler has it *) |
| 3657 | Scan.setBang(true); |
| 3658 | while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do Scan.next; end; |
| 3659 | Scan.setBang(false); |
| 3660 | try expect(Scan.sEnd); |
| 3661 | else |
| 3662 | try codeBody(p, sig, at); |
| 3663 | end; |
| 3664 | elsif checkMode then |
| 3665 | try skipBody(); |
| 3666 | else |
| 3667 | try body(p, sig, line); |
| 3668 | end; |
| 3669 | if Scan.tok = Scan.sIdent then |
| 3670 | if Scan.id = Sym.curModule^.name then |
| 3671 | return endMissing(Scan.tokPos(), say1("{} has no \"end\": this one closes the module", nameOf(n))); |
| 3672 | elsif Scan.id # n then |
| 3673 | return endMissing(Scan.tokPos(), say2("expected {}, found {}", nameOf(n), nameOf(Scan.id))); |
| 3674 | end; |
| 3675 | Scan.next; |
| 3676 | end; |
| 3677 | return nil; |
| 3678 | end; |
| 3679 | |
| 3680 | (* An extern procedure or variable: C's, reached through the quadword |
| 3681 | that holds its address. *) |
| 3682 | proc externDecl: ERROR; |
| 3683 | var n: INT; exp: BOOL; o, q: PObj; t: PType; at: Diag.Pos; |
| 3684 | begin |
| 3685 | _ := Item.needSystem(Scan.tokPos(), "extern"); (* said, and the declaration read on *) |
| 3686 | Scan.next; |
| 3687 | Sym.curModule^.usesC := true; |
| 3688 | if Scan.tok = Scan.sProc then |
| 3689 | Scan.next; |
| 3690 | try identDef(n, exp, at); |
| 3691 | willDeclare(n); |
| 3692 | inExtern := true; |
| 3693 | t := try signature(); |
| 3694 | inExtern := false; |
| 3695 | q := t^.fields; |
| 3696 | while q # nil do |
| 3697 | if q^.isVar or not Sym.isScalar(q^.typ) then |
| 3698 | return Scan.markAt(at, "C takes integers, BOOL, reals, pointers and procedures"); |
| 3699 | end; |
| 3700 | q := q^.next; |
| 3701 | end; |
| 3702 | if (t^.base # nil) and not Sym.isScalar(t^.base) then |
| 3703 | return Scan.markAt(at, "C returns a single value"); |
| 3704 | end; |
| 3705 | o := Sym.newObj(Sym.oProc, n, t); |
| 3706 | else |
| 3707 | if Scan.tok # Scan.sVar then return expected("\"proc\" or \"var\""); end; |
| 3708 | Scan.next; |
| 3709 | try identDef(n, exp, at); |
| 3710 | willDeclare(n); |
| 3711 | try expect(Scan.sColon); |
| 3712 | declExported := exp; |
| 3713 | t := try parseType(); |
| 3714 | declExported := false; |
| 3715 | o := Sym.newObj(Sym.oVar, n, t); |
| 3716 | end; |
| 3717 | o^.pos := at; |
| 3718 | o^.exported := exp; |
| 3719 | o^.ext := true; |
| 3720 | o^.chunk := Chunk.externChunk(n); |
| 3721 | return declare(o); |
| 3722 | end; |
| 3723 | |
| 3724 | (* An array or record constant: a literal of constants, which become |
| 3725 | the bytes of a read-only chunk, as a string constant's do (report |
| 3726 | section 4). An address in it, of a string, an array constant, a |
| 3727 | procedure or an ERROR, waits in fixes until the chunk is made, then |
| 3728 | is a fixup the linker patches. The bytes are the compiler's own |
| 3729 | machine's, little-endian, as the target's are. *) |
| 3730 | var |
| 3731 | constBytes: ^U8; |
| 3732 | fixes: [MaxFixes]record off, chunk: INT; end; |
| 3733 | numFixes: INT; |
| 3734 | |
| 3735 | proc constFix(off, chunk: INT): ERROR; |
| 3736 | begin |
| 3737 | if numFixes >= MaxFixes then |
| 3738 | return Scan.mark(tooMany(MaxFixes, "addresses in one constant")); |
| 3739 | end; |
| 3740 | fixes[numFixes].off := off; |
| 3741 | fixes[numFixes].chunk := chunk; |
| 3742 | INC(numFixes); |
| 3743 | return nil; |
| 3744 | end; |
| 3745 | |
| 3746 | (* The n bytes of v, at off in the constant: little-endian, as the machine is *) |
| 3747 | proc putBytes(off, n: INT; v: I64); |
| 3748 | var src: ^U8; |
| 3749 | begin |
| 3750 | src := ^U8(SYSTEM.ADR(v)); |
| 3751 | COPY(constBytes[off..off + n], src[0..n]); |
| 3752 | end; |
| 3753 | |
| 3754 | (* The number of elements of the array literal at the scanner, at its |
| 3755 | "[": read ahead, counting the commas outside any inner brackets, |
| 3756 | then read again from the "[" (saveScan, restoreScan). Its slips are |
| 3757 | told when it is read again. *) |
| 3758 | proc literalLength: INT; |
| 3759 | var st: Scan.State; depth, n: INT; wasSkipping: BOOL; |
| 3760 | begin |
| 3761 | Scan.saveScan(st); |
| 3762 | wasSkipping := Scan.skipping; |
| 3763 | Scan.setSkipping(true); |
| 3764 | Scan.next; |
| 3765 | n := 0; |
| 3766 | if Scan.tok # Scan.sRbrak then n := 1; end; |
| 3767 | depth := 0; |
| 3768 | while (Scan.tok # Scan.sEof) and ((depth > 0) or (Scan.tok # Scan.sRbrak)) do |
| 3769 | match Scan.tok of |
| 3770 | | sLparen, sLbrak, sLbrace: INC(depth); |
| 3771 | | sRparen, sRbrak, sRbrace: DEC(depth); |
| 3772 | | sComma: if depth = 0 then INC(n); end; |
| 3773 | | else: |
| 3774 | end; |
| 3775 | Scan.next; |
| 3776 | end; |
| 3777 | Scan.setSkipping(wasSkipping); |
| 3778 | Scan.restoreScan(st); |
| 3779 | return n; |
| 3780 | end; |
| 3781 | |
| 3782 | (* A constant typed []T, or an array literal for a slice part of one, |
| 3783 | is an array constant whose length is its literal's (report, 4): t, |
| 3784 | the slice type, becomes [n]T, as if n had been written, with n |
| 3785 | counted ahead (literalLength). With no element, [], it stays []T: |
| 3786 | the empty slice, kept as 16 zero bytes. *) |
| 3787 | proc literalArray(t: PType): (PType, ERROR); |
| 3788 | var a: PType; n: INT; |
| 3789 | begin |
| 3790 | if Scan.tok # Scan.sLbrak then |
| 3791 | return nil, Scan.markAt(Scan.tokPos(), say1("expected a literal of {}", Sym.typeName(t))); |
| 3792 | end; |
| 3793 | n := literalLength(); |
| 3794 | if n = 0 then return t, nil; end; |
| 3795 | a := Sym.newType(Sym.fArray, I64(n) * t^.base^.size, t^.base^.align); |
| 3796 | a^.len := I64(n); |
| 3797 | a^.base := t^.base; |
| 3798 | return a, nil; |
| 3799 | end; |
| 3800 | |
| 3801 | proc constPart(t: PType; off: INT): ERROR; forward; |
| 3802 | proc constChunk(t: PType; n: INT): (INT, ERROR); forward; |
| 3803 | |
| 3804 | (* A variant's case built from constants, at offset off of the constant |
| 3805 | (report section 4): its number, then each field where the case lays |
| 3806 | it out, as constructCase builds one in a program; the rest stays |
| 3807 | zero. The case is read here, by its name, since expression would |
| 3808 | make the code that builds one. *) |
| 3809 | proc constCase(t: PType; off: INT): ERROR; |
| 3810 | var c, f: PObj; at: Diag.Pos; |
| 3811 | begin |
| 3812 | at := Scan.tokPos(); |
| 3813 | c := try qualIdent(); |
| 3814 | if (c^.cls # Sym.oCase) or (c^.typ # t) then |
| 3815 | return Scan.markAt(Scan.spanFrom(at), say1("expected a case of {}", Sym.typeName(t))); |
| 3816 | end; |
| 3817 | putBytes(off, 8, c^.val); |
| 3818 | f := c^.fields; |
| 3819 | if Scan.tok = Scan.sLparen then |
| 3820 | Scan.next; |
| 3821 | while f # nil do |
| 3822 | try constPart(f^.typ, off + INT(f^.val)); |
| 3823 | f := f^.next; |
| 3824 | if f # nil then try expect(Scan.sComma); end; |
| 3825 | end; |
| 3826 | return expect(Scan.sRparen); |
| 3827 | elsif f # nil then |
| 3828 | return Scan.markAt(Scan.spanFrom(at), say1("{} needs its fields", nameOf(c^.name))); |
| 3829 | end; |
| 3830 | return nil; |
| 3831 | end; |
| 3832 | |
| 3833 | (* The part of type t at offset off of the constant *) |
| 3834 | proc constPart(t: PType; off: INT): ERROR; |
| 3835 | var e: TItem; f: PObj; k, c: INT; r: F32; start: Diag.Pos; src: ^U8; st, fx: INT; a: PType; |
| 3836 | begin |
| 3837 | start := Scan.tokPos(); |
| 3838 | if (t^.form = Sym.fSlice) and (Scan.tok = Scan.sLbrak) then |
| 3839 | a := try literalArray(t); |
| 3840 | if a = t then |
| 3841 | (* [], the empty slice (report, 4): its bytes stay zero, ptr nil and len 0 *) |
| 3842 | Scan.next; |
| 3843 | return expect(Scan.sRbrak); |
| 3844 | end; |
| 3845 | (* an array literal (report, 4) is an array constant of its own, |
| 3846 | in a chunk of its own, made before this one is; the slice |
| 3847 | points at it, as it would at a named one: |
| 3848 | const Rows: [][]INT = [[1, 2], [3]]; |
| 3849 | is laid out as |
| 3850 | const R0: [2]INT = [1, 2]; R1: [1]INT = [3]; |
| 3851 | const Rows: [][]INT = [R0, R1]; *) |
| 3852 | c := try constChunk(a, -1); |
| 3853 | try constFix(off, c); |
| 3854 | putBytes(off + 8, 8, a^.len); |
| 3855 | return nil; |
| 3856 | end; |
| 3857 | if (t^.form = Sym.fArray) and (Scan.tok = Scan.sLbrak) then |
| 3858 | Scan.next; |
| 3859 | k := 0; |
| 3860 | if Scan.tok # Scan.sRbrak then |
| 3861 | repeat |
| 3862 | if I64(k) < t^.len then |
| 3863 | try constPart(t^.base, off + k * INT(t^.base^.size)); |
| 3864 | else |
| 3865 | try constPart(t^.base, off); |
| 3866 | end; |
| 3867 | INC(k); |
| 3868 | if Scan.tok # Scan.sComma then break; end; |
| 3869 | Scan.next; |
| 3870 | until false; |
| 3871 | end; |
| 3872 | try expect(Scan.sRbrak); |
| 3873 | if I64(k) # t^.len then |
| 3874 | return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(t^.len), Fmt.int(k)])); |
| 3875 | end; |
| 3876 | return nil; |
| 3877 | end; |
| 3878 | if (t^.form = Sym.fRecord) and not t^.tuple and (Scan.tok = Scan.sLbrace) then |
| 3879 | Scan.next; |
| 3880 | if Scan.tok # Scan.sRbrace then |
| 3881 | repeat |
| 3882 | if Scan.tok # Scan.sIdent then return expected("a field"); end; |
| 3883 | f := try fieldOf(t); |
| 3884 | Scan.next; |
| 3885 | try expect(Scan.sColon); |
| 3886 | try constPart(f^.typ, off + INT(f^.val)); |
| 3887 | if Scan.tok # Scan.sComma then break; end; |
| 3888 | Scan.next; |
| 3889 | until false; |
| 3890 | end; |
| 3891 | return expect(Scan.sRbrace); |
| 3892 | end; |
| 3893 | if (t^.form = Sym.fVariant) and (Scan.tok = Scan.sIdent) then return constCase(t, off); end; |
| 3894 | if Scan.tok = Scan.sLbrak then (* an array literal where neither an array nor a slice is *) |
| 3895 | return Scan.mark(say1("expected {}, found an array literal", Sym.typeName(t))); |
| 3896 | end; |
| 3897 | try expression(e, t); |
| 3898 | if (t^.form = Sym.fSlice) and not t^.rdonly then |
| 3899 | return Scan.markHelp(e.pos, say1("a constant's slice is a []const, not {}", Sym.typeName(t)), |
| 3900 | "a constant can't be changed: declare the slice []const"); |
| 3901 | end; |
| 3902 | if (e.mode = Item.mStr) and ((t^.form = Sym.fSlice) or (t^.form = Sym.fArray)) and (t^.base = Sym.tU8) then |
| 3903 | if t^.form = Sym.fSlice then |
| 3904 | try constFix(off, e.chunk); |
| 3905 | putBytes(off + 8, 8, e.val); |
| 3906 | elsif e.val > t^.len then |
| 3907 | return Scan.markAt(e.pos, say1("the string is longer than {}", Sym.typeName(t))); |
| 3908 | else |
| 3909 | st := Chunk.chunks[e.chunk].start; |
| 3910 | COPY(constBytes[off..off + INT(e.val)], Chunk.rodata[st..st + INT(e.val)]); |
| 3911 | end; |
| 3912 | elsif t^.form = Sym.fSlice then |
| 3913 | (* the whole constant, here or another module's, not a part of |
| 3914 | it, which has a type of its own: the element's, or a slice's *) |
| 3915 | if (e.mode # Item.mVar) or (e.obj = nil) or (e.obj^.cls # Sym.oConst) or (e.typ # e.obj^.typ) |
| 3916 | or not (e.typ^.form in {Sym.fArray, Sym.fSlice}) or not Sym.same(e.typ^.base, t^.base) then |
| 3917 | return Scan.markAt(e.pos, say1("a constant slice is a string, an array constant or literal of its elements, or [], found {}", Item.what(e))); |
| 3918 | end; |
| 3919 | if e.typ^.form = Sym.fArray then (* else an empty slice constant, whose bytes stay zero *) |
| 3920 | try constFix(off, e.chunk); |
| 3921 | putBytes(off + 8, 8, e.typ^.len); |
| 3922 | end; |
| 3923 | elsif t^.form = Sym.fVariant then |
| 3924 | return Scan.markAt(e.pos, say1("expected a case of {}", Sym.typeName(t))); |
| 3925 | elsif (t^.form = Sym.fArray) or (t^.form = Sym.fRecord) then |
| 3926 | (* a literal, or the whole of a constant of the type: its bytes and addresses are copied *) |
| 3927 | if (e.mode # Item.mVar) or (e.obj = nil) or (e.obj^.cls # Sym.oConst) or (e.typ # e.obj^.typ) |
| 3928 | or not Sym.same(e.typ, t) then |
| 3929 | return Scan.markAt(e.pos, say1("expected a literal of {}", Sym.typeName(t))); |
| 3930 | end; |
| 3931 | st := Chunk.chunks[e.chunk].start; |
| 3932 | COPY(constBytes[off..off + INT(t^.size)], Chunk.rodata[st..st + INT(t^.size)]); |
| 3933 | fx := Chunk.chunks[e.chunk].firstFix; |
| 3934 | for k := fx to fx + Chunk.chunks[e.chunk].numFix - 1 do |
| 3935 | try constFix(off + Chunk.dataFixups[k].at, Chunk.dataFixups[k].chunk); |
| 3936 | end; |
| 3937 | else |
| 3938 | try Item.coerce(e, t); |
| 3939 | if (e.mode = Item.mProc) and not e.obj^.ext then |
| 3940 | try constFix(off, e.obj^.chunk); |
| 3941 | elsif e.mode # Item.mConst then |
| 3942 | return Scan.markAt(e.pos, say1("expected a constant, found {}", Item.what(e))); |
| 3943 | elsif (t^.form = Sym.fError) and (e.val > 0) then |
| 3944 | try constFix(off, INT(e.val) - 1); |
| 3945 | elsif (t^.form = Sym.fPtr) and (e.val # 0) then |
| 3946 | return Scan.markAt(e.pos, "a constant pointer is nil"); |
| 3947 | elsif (t^.form = Sym.fReal) and (t^.size = 4) then |
| 3948 | r := F32(Item.realOf(e)); |
| 3949 | src := ^U8(SYSTEM.ADR(r)); |
| 3950 | COPY(constBytes[off..off + 4], src[0..4]); |
| 3951 | else |
| 3952 | putBytes(off, INT(t^.size), e.val); |
| 3953 | end; |
| 3954 | end; |
| 3955 | return nil; |
| 3956 | end; |
| 3957 | |
| 3958 | (* The chunk of n, a constant of type t whose literal is next, or of |
| 3959 | an array literal in a constant's slice part, with n -1. That one is |
| 3960 | made while the constant around it is still being read: its bytes are |
| 3961 | its own, and the constant's are put back after; its addresses go on |
| 3962 | in fixes after the constant's, from base, and are taken off again. *) |
| 3963 | proc constChunk(t: PType; n: INT): (INT, ERROR); |
| 3964 | var c, i, size, base: INT; outer: ^U8; |
| 3965 | begin |
| 3966 | outer := constBytes; |
| 3967 | base := numFixes; |
| 3968 | size := INT(t^.size); |
| 3969 | constBytes := Scan.grab(size + 8); |
| 3970 | for i := 0 to size + 7 do constBytes[i] := 0; end; |
| 3971 | try constPart(t, 0); |
| 3972 | if n < 0 then |
| 3973 | c := Chunk.newChunk(Chunk.secRodata, -1, -1); |
| 3974 | else |
| 3975 | c := Chunk.newChunk(Chunk.secRodata, Sym.curModule^.sname, n); |
| 3976 | end; |
| 3977 | Chunk.setData(c, constBytes, size, INT(t^.align)); |
| 3978 | for i := base to numFixes - 1 do Chunk.addDataFixup(c, fixes[i].off, fixes[i].chunk, 0); end; |
| 3979 | numFixes := base; |
| 3980 | constBytes := outer; |
| 3981 | return c, nil; |
| 3982 | end; |
| 3983 | |
| 3984 | (* The chunk of n, a constant of type t whose literal is next *) |
| 3985 | proc aggregateConst(t: PType; n: INT): (INT, ERROR); |
| 3986 | begin |
| 3987 | numFixes := 0; (* none left over from a constant an error broke off *) |
| 3988 | return constChunk(t, n); |
| 3989 | end; |
| 3990 | |
| 3991 | proc constDecl(top: BOOL): ERROR; |
| 3992 | var n, c: INT; exp: BOOL; x: TItem; o: PObj; t: PType; start, at: Diag.Pos; |
| 3993 | begin |
| 3994 | try identDef(n, exp, at); |
| 3995 | willDeclare(n); |
| 3996 | t := nil; |
| 3997 | if Scan.tok = Scan.sColon then |
| 3998 | Scan.next; |
| 3999 | start := Scan.tokPos(); |
| 4000 | t := try parseType(); |
| 4001 | if (t # Sym.tError) and not ((t^.form = Sym.fArray) or (t^.form = Sym.fSlice) |
| 4002 | or ((t^.form = Sym.fRecord) and not t^.tuple) or (t^.form = Sym.fVariant)) then |
| 4003 | if t^.form = Sym.fSet then |
| 4004 | return Scan.markAt(Scan.spanFrom(start), "a set constant takes its type from its names: write it without one"); |
| 4005 | end; |
| 4006 | return Scan.markAt(Scan.spanFrom(start), "only an ERROR, an array, a record or a variant constant has a type"); |
| 4007 | end; |
| 4008 | end; |
| 4009 | try expect(Scan.sEql); |
| 4010 | if (t # nil) and (t^.form = Sym.fSlice) then t := try literalArray(t); end; |
| 4011 | if (t # nil) and (t^.form in {Sym.fArray, Sym.fRecord, Sym.fSlice, Sym.fVariant}) then |
| 4012 | o := Sym.newObj(Sym.oConst, n, t); |
| 4013 | o^.chunk := try aggregateConst(t, n); |
| 4014 | o^.pos := at; |
| 4015 | o^.exported := exp and top; |
| 4016 | try declare(o); |
| 4017 | return expect(Scan.sSemicolon); |
| 4018 | end; |
| 4019 | try expression(x, nil); |
| 4020 | if x.typ^.form = Sym.fVariant then |
| 4021 | return Scan.markHelp(x.pos, "a variant constant needs its type", |
| 4022 | say2("write const {}: {} = ...", nameOf(n), Sym.typeName(x.typ))); |
| 4023 | end; |
| 4024 | o := Sym.newObj(Sym.oConst, n, x.typ); |
| 4025 | o^.pos := at; |
| 4026 | o^.exported := exp and top; |
| 4027 | if (t = Sym.tError) and (x.mode = Item.mConst) and (x.typ = Sym.tError) and (x.val > 0) then |
| 4028 | (* another ERROR constant (report, 5.8): that same error, its |
| 4029 | chunk, so that the two compare equal; only a string makes one *) |
| 4030 | o^.typ := Sym.tError; |
| 4031 | o^.val := x.val; |
| 4032 | elsif t = Sym.tError then |
| 4033 | o^.typ := Sym.tError; |
| 4034 | c := try Item.errorChunk(x, Sym.curModule^.sname, n); |
| 4035 | o^.val := c + 1; |
| 4036 | elsif x.mode = Item.mStr then |
| 4037 | o^.val := x.val; |
| 4038 | o^.chunk := x.chunk; |
| 4039 | else |
| 4040 | o^.val := try constValue(x); |
| 4041 | end; |
| 4042 | try declare(o); |
| 4043 | return expect(Scan.sSemicolon); |
| 4044 | end; |
| 4045 | |
| 4046 | proc typeDecl(top: BOOL): ERROR; |
| 4047 | var n: INT; exp: BOOL; o: PObj; t: PType; at: Diag.Pos; |
| 4048 | begin |
| 4049 | try identDef(n, exp, at); |
| 4050 | willDeclare(n); |
| 4051 | try expect(Scan.sEql); |
| 4052 | declExported := exp and top; |
| 4053 | inTypes := true; |
| 4054 | t := try parseType(); |
| 4055 | o := Sym.newObj(Sym.oType, n, t); |
| 4056 | o^.pos := at; |
| 4057 | o^.exported := exp and top; |
| 4058 | if t^.obj = nil then t^.obj := o; end; |
| 4059 | try declare(o); |
| 4060 | return expect(Scan.sSemicolon); |
| 4061 | end; |
| 4062 | |
| 4063 | proc varDecl(top: BOOL): ERROR; |
| 4064 | var |
| 4065 | i, k: INT; o: PObj; t: PType; |
| 4066 | names: [MaxNames]INT; exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos; |
| 4067 | begin |
| 4068 | k := 0; |
| 4069 | repeat |
| 4070 | if k >= MaxNames then return Scan.mark(tooMany(MaxNames, "names in one declaration")); end; |
| 4071 | try identDef(names[k], exps[k], poss[k]); |
| 4072 | willDeclare(names[k]); |
| 4073 | INC(k); |
| 4074 | if Scan.tok # Scan.sComma then break; end; |
| 4075 | Scan.next; |
| 4076 | until false; |
| 4077 | try expect(Scan.sColon); |
| 4078 | declExported := top and exps[0]; |
| 4079 | t := try parseType(); |
| 4080 | declExported := false; |
| 4081 | for i := 0 to k - 1 do |
| 4082 | o := Sym.newObj(Sym.oVar, names[i], t); |
| 4083 | o^.pos := poss[i]; |
| 4084 | o^.exported := exps[i] and top; |
| 4085 | o^.isVar := false; |
| 4086 | if top then |
| 4087 | o^.lev := 0; |
| 4088 | o^.chunk := Chunk.newChunk(Chunk.secBss, Sym.curModule^.sname, names[i]); |
| 4089 | Chunk.setBss(o^.chunk, INT(t^.size), INT(t^.align)); |
| 4090 | else |
| 4091 | o^.lev := 1; (* its slot comes from placeLocals, if it needs one *) |
| 4092 | end; |
| 4093 | try declare(o); |
| 4094 | end; |
| 4095 | return expect(Scan.sSemicolon); |
| 4096 | end; |
| 4097 | |
| 4098 | (* After a procedure had an error: its name is poison if it wasn't |
| 4099 | declared, and reading goes on after the "end Name;" that closes it, |
| 4100 | or at the next procedure if that is missing *) |
| 4101 | proc skipProc; |
| 4102 | var st: Scan.State; |
| 4103 | begin |
| 4104 | Scan.next; |
| 4105 | if (Scan.tok = Scan.sIdent) and (Sym.find(Sym.topScope(), Scan.id) = nil) then poison(Scan.id); end; |
| 4106 | repeat |
| 4107 | repeat Scan.next; until Scan.atLineStart() or (Scan.tok = Scan.sEof); |
| 4108 | match Scan.tok of |
| 4109 | | sProc, sExtern, sEof: return; |
| 4110 | | sEnd: |
| 4111 | Scan.saveScan(st); |
| 4112 | Scan.next; |
| 4113 | if Scan.tok = Scan.sIdent then Scan.next; end; |
| 4114 | if Scan.tok = Scan.sSemicolon then |
| 4115 | Scan.next; |
| 4116 | return; |
| 4117 | end; |
| 4118 | Scan.restoreScan(st); |
| 4119 | return; |
| 4120 | | else: |
| 4121 | end; |
| 4122 | until false; |
| 4123 | end; |
| 4124 | |
| 4125 | (* What one declaration, of the kind k, reads *) |
| 4126 | proc declarationOf(k: Scan.Sym; top: BOOL): ERROR; |
| 4127 | begin |
| 4128 | match k of |
| 4129 | | sConst: return constDecl(top); |
| 4130 | | sType: return typeDecl(top); |
| 4131 | | sVar: return varDecl(top); |
| 4132 | | sProc: |
| 4133 | if not top then return Scan.mark("procedures don't nest"); end; |
| 4134 | try procDecl(); |
| 4135 | return expect(Scan.sSemicolon); |
| 4136 | | sExtern: |
| 4137 | if not top then return Scan.mark("extern is only for the top of a module"); end; |
| 4138 | try externDecl(); |
| 4139 | return expect(Scan.sSemicolon); |
| 4140 | | else: return nil; |
| 4141 | end; |
| 4142 | end; |
| 4143 | |
| 4144 | (* One declaration, as a recovery point: an error is reported, the |
| 4145 | declaration skipped, and reading goes on after it *) |
| 4146 | proc declaration(k: Scan.Sym; top: BOOL); |
| 4147 | var r: Recover; |
| 4148 | begin |
| 4149 | guard(r); |
| 4150 | numDeclaring := 0; |
| 4151 | if declarationOf(k, top) # nil then |
| 4152 | restore(r); |
| 4153 | if k = Scan.sProc then skipProc(); else skipDeclaration(); end; |
| 4154 | end; |
| 4155 | unguard(r); |
| 4156 | end; |
| 4157 | |
| 4158 | proc declarations(top: BOOL); |
| 4159 | var k: Scan.Sym; |
| 4160 | begin |
| 4161 | repeat |
| 4162 | k := Scan.tok; |
| 4163 | match k of |
| 4164 | | sConst, sVar: |
| 4165 | Scan.next; |
| 4166 | while Scan.tok = Scan.sIdent do declaration(k, top); end; |
| 4167 | | sType: |
| 4168 | Scan.next; |
| 4169 | numLater := 0; |
| 4170 | while Scan.tok = Scan.sIdent do declaration(Scan.sType, top); end; |
| 4171 | inTypes := false; |
| 4172 | resolveLaters(); |
| 4173 | | sProc, sExtern: declaration(k, top); |
| 4174 | | else: return; |
| 4175 | end; |
| 4176 | until false; |
| 4177 | end; |
| 4178 | |
| 4179 | (* Modules *) |
| 4180 | |
| 4181 | (* Whether m is module n with these arguments. *) |
| 4182 | proc isModule(m: PModule; n: INT; args: Sym.Args): BOOL; |
| 4183 | var i: INT; |
| 4184 | begin |
| 4185 | if (m^.name # n) or (m^.args.n # args.n) then return false; end; |
| 4186 | for i := 0 to args.n - 1 do |
| 4187 | if (m^.args.o[i] # args.o[i]) or not Sym.same(m^.args.t[i], args.t[i]) then return false; end; |
| 4188 | end; |
| 4189 | return true; |
| 4190 | end; |
| 4191 | |
| 4192 | proc findModule(n: INT; args: Sym.Args): PModule; |
| 4193 | var m: PModule; |
| 4194 | begin |
| 4195 | m := firstModule; |
| 4196 | while (m # nil) and not isModule(m, n, args) do m := m^.next; end; |
| 4197 | return m; |
| 4198 | end; |
| 4199 | |
| 4200 | (* The arguments of an instance: types, or procedures named. *) |
| 4201 | proc parseArgs(var args: Sym.Args; mname: []const U8): ERROR; |
| 4202 | var o: PObj; start: Diag.Pos; |
| 4203 | begin |
| 4204 | Scan.next; |
| 4205 | repeat |
| 4206 | if args.n >= LEN(args.o) then |
| 4207 | return Scan.mark(tooMany(LEN(args.o), say1("type arguments to {}", mname))); |
| 4208 | end; |
| 4209 | args.o[args.n] := nil; |
| 4210 | start := Scan.tokPos(); |
| 4211 | if Scan.tok = Scan.sIdent then |
| 4212 | o := try qualIdent(); |
| 4213 | if o^.cls = Sym.oProc then |
| 4214 | args.o[args.n] := o; |
| 4215 | elsif o^.cls # Sym.oType then |
| 4216 | return Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type or a procedure", nameOf(o^.name))); |
| 4217 | end; |
| 4218 | args.t[args.n] := o^.typ; |
| 4219 | else |
| 4220 | args.t[args.n] := try parseType(); |
| 4221 | end; |
| 4222 | args.pos[args.n] := Scan.spanFrom(start); |
| 4223 | INC(args.n); |
| 4224 | if Scan.tok # Scan.sComma then break; end; |
| 4225 | Scan.next; |
| 4226 | until false; |
| 4227 | return expect(Scan.sRparen); |
| 4228 | end; |
| 4229 | |
| 4230 | (* Past an instance's arguments, to be read when it is made *) |
| 4231 | proc skipArgs: ERROR; |
| 4232 | var p: INT; |
| 4233 | begin |
| 4234 | p := 0; |
| 4235 | repeat |
| 4236 | if Scan.tok = Scan.sLparen then |
| 4237 | INC(p); |
| 4238 | elsif Scan.tok = Scan.sRparen then |
| 4239 | DEC(p); |
| 4240 | elsif (Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEof) then |
| 4241 | return expected("\")\""); |
| 4242 | end; |
| 4243 | Scan.next; |
| 4244 | until p = 0; |
| 4245 | return nil; |
| 4246 | end; |
| 4247 | |
| 4248 | (* A generic module's parameters, bound to the instance's arguments: a |
| 4249 | type parameter names its type, a procedure parameter its procedure. |
| 4250 | The instance's name is the module's with its arguments, List(I64). *) |
| 4251 | proc moduleParams(m: PModule): ERROR; |
| 4252 | var i: INT; o, a: PObj; sig: PType; s: Buf.Buf; at: Diag.Pos; text: []U8; |
| 4253 | begin |
| 4254 | Buf.init(s, Heap.heap); |
| 4255 | i := 0; |
| 4256 | Buf.str(s, nameOf(m^.name)); |
| 4257 | Buf.add(s, '('); |
| 4258 | Scan.next; |
| 4259 | repeat |
| 4260 | if Scan.tok # Scan.sIdent then return expected("a name"); end; |
| 4261 | if i >= m^.args.n then |
| 4262 | return Scan.markAt(m^.args.at, say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id))); |
| 4263 | end; |
| 4264 | if m^.args.o[i] # nil then |
| 4265 | return Scan.markAt(m^.args.pos[i], say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id))); |
| 4266 | end; |
| 4267 | o := Sym.newObj(Sym.oType, Scan.id, m^.args.t[i]); |
| 4268 | o^.used := true; (* a parameter of the module, not a declaration *) |
| 4269 | try declare(o); |
| 4270 | Buf.str(s, Sym.typeName(m^.args.t[i])); |
| 4271 | Buf.add(s, ','); |
| 4272 | INC(i); |
| 4273 | Scan.next; |
| 4274 | if Scan.tok # Scan.sComma then break; end; |
| 4275 | Scan.next; |
| 4276 | until false; |
| 4277 | while Scan.tok = Scan.sSemicolon do |
| 4278 | Scan.next; |
| 4279 | if Scan.tok # Scan.sIdent then return expected("a name"); end; |
| 4280 | at := Scan.tokPos(); |
| 4281 | o := Sym.newObj(Sym.oProc, Scan.id, nil); |
| 4282 | Scan.next; |
| 4283 | try expect(Scan.sColon); |
| 4284 | try expect(Scan.sProc); |
| 4285 | sig := try signature(); |
| 4286 | if i >= m^.args.n then |
| 4287 | return Scan.markAt(m^.args.at, say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name))); |
| 4288 | end; |
| 4289 | a := m^.args.o[i]; |
| 4290 | if a = nil then |
| 4291 | return Scan.markAt(m^.args.pos[i], say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name))); |
| 4292 | end; |
| 4293 | if not Sym.same(a^.typ, sig) then |
| 4294 | Diag.error(m^.args.pos[i], say2("{} doesn't have the signature of {}", nameOf(a^.name), nameOf(o^.name))); |
| 4295 | Diag.note(at, "the signature is here"); |
| 4296 | Diag.finish(); |
| 4297 | end; |
| 4298 | o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext; |
| 4299 | o^.used := true; |
| 4300 | try declare(o); |
| 4301 | Buf.str(s, nameOf(a^.home^.name)); |
| 4302 | Buf.add(s, '.'); |
| 4303 | Buf.str(s, nameOf(a^.name)); |
| 4304 | Buf.add(s, ','); |
| 4305 | INC(i); |
| 4306 | end; |
| 4307 | try expect(Scan.sRparen); |
| 4308 | if i # m^.args.n then |
| 4309 | return Scan.markAt(m^.args.at, say1("too many type arguments for {}", nameOf(m^.name))); |
| 4310 | end; |
| 4311 | text := Buf.bytes(s); |
| 4312 | text[LEN(text) - 1] := ')'; |
| 4313 | m^.sname := internName(text); |
| 4314 | Buf.done(s); |
| 4315 | return nil; |
| 4316 | end; |
| 4317 | |
| 4318 | (* Warns of o if it is never used, or a variable only assigned. What |
| 4319 | is exported may be used elsewhere, and a name that starts with _ says |
| 4320 | it is meant to go unused. Writing a var parameter, a match's name for |
| 4321 | a field or C's variable is what it is for. *) |
| 4322 | proc warn(o: PObj); |
| 4323 | var s, t: []const U8; |
| 4324 | begin |
| 4325 | s := nameOf(o^.name); |
| 4326 | if (o^.cls = Sym.oProc) and o^.openEnd then |
| 4327 | Diag.warning(o^.pos, say1("{} may reach its end without return, and then returns zero", s)); |
| 4328 | end; |
| 4329 | if o^.exported or (s[0] = '_') then return; end; |
| 4330 | if o^.used and (o^.read or (o^.cls # Sym.oVar) or (o^.isVar and not o^.isConst) or o^.ext) then return; end; |
| 4331 | match o^.cls of |
| 4332 | | oConst: t := say1("constant {}", s); |
| 4333 | | oType: t := say1("type {}", s); |
| 4334 | | oVar: |
| 4335 | if o^.param then t := say1("parameter {}", s); else t := say1("variable {}", s); end; |
| 4336 | | oProc: t := say1("procedure {}", s); |
| 4337 | | oModule: t := say1("module {}", s); |
| 4338 | | else: return; |
| 4339 | end; |
| 4340 | if o^.used then |
| 4341 | Diag.warning(o^.pos, say1("{} is assigned but never read", t)); |
| 4342 | elsif o^.cls = Sym.oModule then |
| 4343 | Diag.warning(o^.pos, say1("{} is imported but never used", t)); |
| 4344 | else |
| 4345 | Diag.warning(o^.pos, say1("{} is never used", t)); |
| 4346 | end; |
| 4347 | if not o^.used and o^.param then |
| 4348 | Diag.help(say1("if it must be there, call it _{}", s)); |
| 4349 | elsif not o^.used and o^.ind then (* not a parameter, so a name a match arm gives *) |
| 4350 | Diag.help(say1("an arm names all the fields of a case or none: call one it doesn't read _{}", s)); |
| 4351 | end; |
| 4352 | end; |
| 4353 | |
| 4354 | (* Warns of the call at p, which drops its n results *) |
| 4355 | proc dropped(p: Diag.Pos; n: INT); |
| 4356 | var s, blanks: []const U8; i: INT; |
| 4357 | begin |
| 4358 | s := Diag.source(p); |
| 4359 | i := 0; |
| 4360 | while (i < LEN(s)) and (s[i] # '(') do INC(i); end; |
| 4361 | if i < LEN(s) then s := s[0..i]; end; |
| 4362 | blanks := "_"; |
| 4363 | for i := 2 to n do blanks := say1("{}, _", blanks); end; |
| 4364 | if n = 1 then |
| 4365 | Diag.warning(p, say1("the result of {} is dropped", s)); |
| 4366 | else |
| 4367 | Diag.warning(p, say1("the results of {} are dropped", s)); |
| 4368 | end; |
| 4369 | Diag.help(say2("if that is meant, write {} := {}(...)", blanks, s)); |
| 4370 | end; |
| 4371 | |
| 4372 | (* The warnings of module m, by where each declaration is: its own |
| 4373 | declarations and its procedures' are two lists, each in order, and |
| 4374 | firstDoubt on are the calls that drop results and the other doubts. The |
| 4375 | instances of a generic module share its text, and so its warnings: |
| 4376 | only the first is warned of. *) |
| 4377 | proc warnings(m: PModule; firstDoubt: INT); |
| 4378 | var a, b: PObj; n: PModule; i: INT; |
| 4379 | begin |
| 4380 | n := firstModule; |
| 4381 | while (n # nil) and (n^.name # m^.name) do n := n^.next; end; |
| 4382 | if n # nil then return; end; |
| 4383 | a := m^.first; b := m^.locals; |
| 4384 | i := firstDoubt; |
| 4385 | while (a # nil) or (b # nil) or (i < numDoubts) do |
| 4386 | if (i < numDoubts) and ((a = nil) or (doubts[i].at.a < a^.pos.a)) and ((b = nil) or (doubts[i].at.a < b^.pos.a)) then |
| 4387 | if LEN(doubts[i].msg) = 0 then |
| 4388 | dropped(doubts[i].at, doubts[i].n); |
| 4389 | else |
| 4390 | Diag.warning(doubts[i].at, doubts[i].msg); |
| 4391 | Diag.help(doubts[i].hint); |
| 4392 | end; |
| 4393 | INC(i); |
| 4394 | elsif (b = nil) or ((a # nil) and (a^.pos.a < b^.pos.a)) then |
| 4395 | warn(a); |
| 4396 | a := a^.chain; |
| 4397 | else |
| 4398 | warn(b); |
| 4399 | b := b^.chain; |
| 4400 | end; |
| 4401 | end; |
| 4402 | end; |
| 4403 | |
| 4404 | (* Modules being compiled, not yet finished: for finding a cycle. *) |
| 4405 | var |
| 4406 | pending: [MaxPending]PModule; |
| 4407 | numPending: INT; |
| 4408 | |
| 4409 | proc exists(path: []const U8): BOOL; |
| 4410 | var info: Sys.Info; err: INT; |
| 4411 | begin |
| 4412 | info, err := Sys.info(path); |
| 4413 | return (err = 0) and info.file; |
| 4414 | end; |
| 4415 | |
| 4416 | (* Which file path is, as its device and inode: two names of one file |
| 4417 | have the same. Zero for a file that can't be asked about. *) |
| 4418 | proc identity(path: []const U8): (INT, INT); |
| 4419 | var i: Sys.Info; err: INT; (* Sys.info follows a symbolic link, and is the same on every target *) |
| 4420 | begin |
| 4421 | i, err := Sys.info(path); |
| 4422 | if err # 0 then return 0, 0; end; |
| 4423 | return INT(i.dev), INT(i.ino); |
| 4424 | end; |
| 4425 | |
| 4426 | (* s, in memory that is never freed, for what must outlast the buffer it is in *) |
| 4427 | proc keep(s: []const U8): []const U8; |
| 4428 | var p: ^U8; |
| 4429 | begin |
| 4430 | if LEN(s) = 0 then return ""; end; |
| 4431 | p := Scan.grab(LEN(s)); |
| 4432 | COPY(p[0..LEN(s)], s); |
| 4433 | return p[0..LEN(s)]; |
| 4434 | end; |
| 4435 | |
| 4436 | proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); forward; |
| 4437 | |
| 4438 | (* Compiles module n from path, an instance if args are given, or only |
| 4439 | reads its interface if checkOnly; returns it. An import calls this in |
| 4440 | the middle of reading another file, so it is re-entrant: it saves the |
| 4441 | scanner's state, the open scopes, the current module and file and |
| 4442 | whether checks are on, and puts them back at the end. *) |
| 4443 | proc compileFile(path: []const U8; n: INT; args: Sym.Args; checkOnly: BOOL): (PModule, ERROR); |
| 4444 | var |
| 4445 | st: Scan.State; saved: [Sym.MaxDepth]INT; d: INT; |
| 4446 | oldMod: PModule; oldCheck, oldChecks: BOOL; m: PModule; |
| 4447 | lib: ^Sym.Lib; start: Diag.Pos; alias, mname, line, oldPath: INT; o: PObj; bodyChunk: INT; iargs: Sym.Args; |
| 4448 | generic, atName: BOOL; argsAt: Scan.State; why: []const U8; firstDoubt: INT; |
| 4449 | begin |
| 4450 | firstDoubt := numDoubts; |
| 4451 | Scan.saveScan(st); |
| 4452 | d := Sym.saveScopes(saved[0..Sym.MaxDepth]); |
| 4453 | oldMod := Sym.curModule; oldCheck := checkMode; oldPath := Chunk.curFilePath(); oldChecks := Item.checks; |
| 4454 | Item.setChecks(true); |
| 4455 | Chunk.setCurFile(internName(path)); |
| 4456 | why := Scan.open(path); |
| 4457 | if LEN(why) # 0 then Diag.fatal(say2("can't read {}: {}", path, why)); end; |
| 4458 | Diag.setOrigin(Scan.tokPos().f, originNote); |
| 4459 | originNote := ""; |
| 4460 | NEW(m, Heap.heap); |
| 4461 | m^.name := n; |
| 4462 | m^.sname := n; |
| 4463 | m^.args := args; |
| 4464 | m^.scope := Sym.newScope(); |
| 4465 | m^.path := path; |
| 4466 | m^.body := -1; |
| 4467 | m^.checkOnly := checkOnly; |
| 4468 | Sym.setCurModule(m); |
| 4469 | checkMode := checkOnly; |
| 4470 | if not checkOnly then |
| 4471 | if numPending >= MaxPending then |
| 4472 | return nil, Scan.mark(tooMany(MaxPending, "imports nested deep")); |
| 4473 | end; |
| 4474 | pending[numPending] := m; |
| 4475 | INC(numPending); |
| 4476 | end; |
| 4477 | try Sym.openScope(m^.scope); |
| 4478 | Scan.next; |
| 4479 | try expect(Scan.sModule); |
| 4480 | if (Scan.tok # Scan.sIdent) or (Scan.id # n) then |
| 4481 | return nil, Scan.mark(say2("expected module {}, found {}", nameOf(n), Scan.found())); |
| 4482 | end; |
| 4483 | m^.at := Scan.tokPos(); |
| 4484 | Scan.next; |
| 4485 | (* the module first pending is the one named on the command line, |
| 4486 | which nothing imports, so no arguments come with it *) |
| 4487 | if (Scan.tok = Scan.sLparen) and not checkOnly and (numPending = 1) then |
| 4488 | return nil, Scan.mark(say1("{} is generic: it is compiled where a module imports it", nameOf(n))); |
| 4489 | elsif Scan.tok = Scan.sLparen then |
| 4490 | try moduleParams(m); |
| 4491 | elsif args.n > 0 then |
| 4492 | return nil, Scan.markAt(args.at, say1("{} isn't generic", nameOf(n))); |
| 4493 | end; |
| 4494 | try expect(Scan.sSemicolon); |
| 4495 | while Scan.tok = Scan.sImport do |
| 4496 | Scan.next; |
| 4497 | repeat |
| 4498 | if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end; |
| 4499 | start := Scan.tokPos(); |
| 4500 | alias := Scan.id; |
| 4501 | atName := define and (alias = Scan.atCursor); (* raz -q def on a module's name here *) |
| 4502 | if atName then alias := internName(Scan.word); end; |
| 4503 | mname := alias; |
| 4504 | iargs.n := 0; |
| 4505 | generic := false; |
| 4506 | Scan.next; |
| 4507 | if Scan.tok = Scan.sBecomes then |
| 4508 | Scan.next; |
| 4509 | if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end; |
| 4510 | mname := Scan.id; |
| 4511 | Scan.next; |
| 4512 | if Scan.tok = Scan.sLparen then |
| 4513 | generic := true; |
| 4514 | Scan.saveScan(argsAt); |
| 4515 | try skipArgs(); |
| 4516 | end; |
| 4517 | end; |
| 4518 | iargs.at := Scan.spanFrom(start); |
| 4519 | o := Sym.newObj(Sym.oModule, alias, nil); |
| 4520 | o^.pos := start; |
| 4521 | try declare(o); |
| 4522 | if mname = Sym.system^.name then |
| 4523 | (* no file: the language's own, which a grep must find *) |
| 4524 | if (alias # mname) or generic then |
| 4525 | return nil, Scan.markHelp(iargs.at, "SYSTEM is imported only as itself", |
| 4526 | "every module that reaches memory through SYSTEM says so by that name: write import SYSTEM"); |
| 4527 | end; |
| 4528 | o^.home := Sym.system; |
| 4529 | m^.system := true; |
| 4530 | named(o); (* not warned of when only its features are used *) |
| 4531 | elsif not generic then |
| 4532 | o^.home := try importModule(mname, iargs); |
| 4533 | addImport(m, o^.home); |
| 4534 | if atName then answer(m^.scope); end; |
| 4535 | else |
| 4536 | o^.home := nil; (* until the instance is made, at its first use *) |
| 4537 | if numDeferred >= MaxDeferred then |
| 4538 | return nil, Scan.mark(tooMany(MaxDeferred, "generic imports")); |
| 4539 | end; |
| 4540 | deferred[numDeferred].o := o; |
| 4541 | deferred[numDeferred].home := m; |
| 4542 | deferred[numDeferred].mname := mname; |
| 4543 | deferred[numDeferred].args := argsAt; |
| 4544 | deferred[numDeferred].at := iargs.at; |
| 4545 | INC(numDeferred); |
| 4546 | end; |
| 4547 | if Scan.tok # Scan.sComma then break; end; |
| 4548 | Scan.next; |
| 4549 | until false; |
| 4550 | try expect(Scan.sSemicolon); |
| 4551 | end; |
| 4552 | while Scan.tok = Scan.sLink do |
| 4553 | Scan.next; |
| 4554 | if (Scan.tok = Scan.sIdent) and (Scan.id = nameStatic) then |
| 4555 | m^.linkStatic := true; |
| 4556 | elsif Scan.tok = Scan.sString then |
| 4557 | _ := Item.needSystem(Scan.tokPos(), "a link of a library"); (* said, and the declaration read on *) |
| 4558 | NEW(lib, Heap.heap); |
| 4559 | lib^.name := internName(Scan.strBytes()); |
| 4560 | lib^.next := m^.libs; |
| 4561 | m^.libs := lib; |
| 4562 | m^.usesC := true; |
| 4563 | else |
| 4564 | return nil, expected("a library or \"static\""); |
| 4565 | end; |
| 4566 | Scan.next; |
| 4567 | try expect(Scan.sSemicolon); |
| 4568 | end; |
| 4569 | (* check off;: the module's index and slice checks left out; neither |
| 4570 | word is reserved *) |
| 4571 | if (Scan.tok = Scan.sIdent) and (Scan.id = nameCheck) then |
| 4572 | _ := Item.needSystem(Scan.tokPos(), "check off"); (* said, and the declaration read on *) |
| 4573 | Scan.next; |
| 4574 | if (Scan.tok # Scan.sIdent) or (Scan.id # nameOff) then return nil, expected("\"off\""); end; |
| 4575 | Scan.next; |
| 4576 | try expect(Scan.sSemicolon); |
| 4577 | Item.setChecks(false); |
| 4578 | end; |
| 4579 | declarations(true); |
| 4580 | if Scan.tok = Scan.sBegin then |
| 4581 | if checkMode then |
| 4582 | try skipBody(); |
| 4583 | else |
| 4584 | try instancesFor(true); |
| 4585 | line := Scan.curLine(); |
| 4586 | Scan.next; |
| 4587 | bodyChunk := Chunk.newChunk(Chunk.secText, m^.sname, nameBody); |
| 4588 | m^.body := bodyChunk; |
| 4589 | Item.beginProc(tBodySig, nil); |
| 4590 | deferSlot := 0; |
| 4591 | curResult := nil; |
| 4592 | Gen.enterBody(bodyChunk, line); |
| 4593 | stray := false; elseIf := false; |
| 4594 | try statements(); |
| 4595 | Chunk.noteLine(Scan.curLine(), Scan.curCol()); |
| 4596 | try expect(Scan.sEnd); |
| 4597 | try Gen.endProc(bodyChunk, false); |
| 4598 | end; |
| 4599 | else |
| 4600 | try expect(Scan.sEnd); |
| 4601 | end; |
| 4602 | if (Scan.tok # Scan.sIdent) or (Scan.id # n) then |
| 4603 | return nil, endMissing(Scan.missingPos(), say2("expected {}, found {}", nameOf(n), Scan.found())); |
| 4604 | end; |
| 4605 | Scan.next; |
| 4606 | if Scan.tok # Scan.sPeriod then return nil, expected("\".\""); end; |
| 4607 | o := m^.first; |
| 4608 | while o # nil do |
| 4609 | if (o^.cls = Sym.oProc) and o^.fwd then |
| 4610 | Diag.error(Scan.tokPos(), say1("{} is declared forward but never defined", nameOf(o^.name))); |
| 4611 | end; |
| 4612 | o := o^.chain; |
| 4613 | end; |
| 4614 | if (Diag.errors = 0) and not checkOnly then warnings(m, firstDoubt); end; |
| 4615 | numDoubts := firstDoubt; |
| 4616 | if Diag.errors > 0 then Diag.finish(); end; (* a module with errors stops the compiler after it *) |
| 4617 | Sym.closeScope(); |
| 4618 | m^.done := true; |
| 4619 | if not checkOnly then |
| 4620 | DEC(numPending); |
| 4621 | if lastModule = nil then firstModule := m; else lastModule^.next := m; end; |
| 4622 | lastModule := m; |
| 4623 | end; |
| 4624 | Sym.setCurModule(oldMod); checkMode := oldCheck; Chunk.setCurFile(oldPath); Item.setChecks(oldChecks); |
| 4625 | Sym.restoreScopes(d, saved[0..Sym.MaxDepth]); |
| 4626 | Scan.restoreScan(st); |
| 4627 | return m, nil; |
| 4628 | end; |
| 4629 | |
| 4630 | (* The interface check: b must export just what a does. *) |
| 4631 | proc compareIface(a, b: PModule); |
| 4632 | var o, q: PObj; |
| 4633 | begin |
| 4634 | (* an enumeration's names are its type's, which the type's |
| 4635 | fingerprint has, and the name alone may be another's *) |
| 4636 | o := a^.first; |
| 4637 | while o # nil do |
| 4638 | if o^.exported and not o^.ofEnum then |
| 4639 | q := Sym.find(b^.scope, o^.name); |
| 4640 | if (q = nil) or not q^.exported or (Sym.fingerprint(o) # Sym.fingerprint(q)) then |
| 4641 | Diag.fatal(Diag.say("{}: {} isn't exported as in {}", [Fmt.str(b^.path), Fmt.str(nameOf(o^.name)), Fmt.str(a^.path)])); |
| 4642 | end; |
| 4643 | end; |
| 4644 | o := o^.chain; |
| 4645 | end; |
| 4646 | q := b^.first; |
| 4647 | while q # nil do |
| 4648 | o := Sym.find(a^.scope, q^.name); |
| 4649 | if q^.exported and not q^.ofEnum and ((o = nil) or not o^.exported) then |
| 4650 | Diag.fatal(Diag.say("{}: {} isn't exported by {}", [Fmt.str(b^.path), Fmt.str(nameOf(q^.name)), Fmt.str(a^.path)])); |
| 4651 | end; |
| 4652 | q := q^.chain; |
| 4653 | end; |
| 4654 | end; |
| 4655 | |
| 4656 | (* A directory and a module name, keeping the root's slash and not |
| 4657 | adding another when the directory already ends in one: "lib/" gives |
| 4658 | "lib/Sys.raz", not "lib//Sys.raz", and "/" gives "/Sys.raz". *) |
| 4659 | proc modulePath(dir, file: []const U8): []const U8; |
| 4660 | begin |
| 4661 | if (LEN(dir) > 0) and (dir[LEN(dir) - 1] = '/') then return say2("{}{}", dir, file); end; |
| 4662 | return say2("{}/{}", dir, file); |
| 4663 | end; |
| 4664 | |
| 4665 | (* Reads every other file of module n in dir, and checks its interface |
| 4666 | against m, compiled from the file named chosen. *) |
| 4667 | proc checkSiblings(dir, chosen: []const U8; n: INT; m: PModule; args: Sym.Args): ERROR; |
| 4668 | var |
| 4669 | dp: Sys.Dir; e, prefix: []const U8; i, numOthers: INT; more: BOOL; sib: PModule; |
| 4670 | others: [32][]const U8; |
| 4671 | begin |
| 4672 | prefix := say1("{}.", nameOf(n)); |
| 4673 | numOthers := 0; |
| 4674 | if Sys.openDir(dp, dir) # 0 then return nil; end; |
| 4675 | repeat |
| 4676 | e, more := Sys.nextEntry(dp); |
| 4677 | if not more then break; end; |
| 4678 | if (LEN(e) > 4) and Str.hasPrefix(e, prefix) and (e[LEN(e) - 4..LEN(e)] = ".raz") |
| 4679 | and (e # chosen) and (numOthers < 32) then |
| 4680 | others[numOthers] := keep(e); |
| 4681 | INC(numOthers); |
| 4682 | end; |
| 4683 | until false; |
| 4684 | Sys.closeDir(dp); |
| 4685 | for i := 0 to numOthers - 1 do |
| 4686 | sib := try compileFile(modulePath(dir, others[i]), n, args, true); |
| 4687 | compareIface(m, sib); |
| 4688 | end; |
| 4689 | return nil; |
| 4690 | end; |
| 4691 | |
| 4692 | (* The compiler's version as a library's RAZ-VERSION would say it: |
| 4693 | "0.21" for "0.21.0-5-g38d29a8"; a name with fewer dots stays whole *) |
| 4694 | proc majorMinor(v: []const U8): []const U8; |
| 4695 | var i, dots: INT; |
| 4696 | begin |
| 4697 | dots := 0; |
| 4698 | for i := 0 to LEN(v) - 1 do |
| 4699 | if v[i] = '.' then |
| 4700 | INC(dots); |
| 4701 | if dots = 2 then return v[0..i]; end; |
| 4702 | end; |
| 4703 | end; |
| 4704 | return v; |
| 4705 | end; |
| 4706 | |
| 4707 | (* The line told with the first error in a module found in dir, an -I or |
| 4708 | RAZ_PATH directory: if dir holds a file RAZ-VERSION, the raz its |
| 4709 | library was written for. The file is only read; a library with none, |
| 4710 | or a module of the program's own directory or of lib, has no line. *) |
| 4711 | proc libraryNote(dir: []const U8): []const U8; |
| 4712 | var fd, n, i: INT; b: [32]U8; |
| 4713 | begin |
| 4714 | if (dir = mainDir) or (dir = libDir) then return ""; end; |
| 4715 | fd := Sys.openRead(say1("{}/RAZ-VERSION", dir)); |
| 4716 | if fd < 0 then return ""; end; |
| 4717 | n := Sys.read(fd, b[0..32]); |
| 4718 | Sys.close(fd); |
| 4719 | i := 0; |
| 4720 | while (i < n) and (b[i] # 10) and (b[i] # 32) do INC(i); end; |
| 4721 | if i = 0 then return ""; end; |
| 4722 | return say2("a library written for raz {}; this is raz {}", b[0..i], majorMinor(thisVersion)); |
| 4723 | end; |
| 4724 | |
| 4725 | (* The directories searched for modules: main, -I, user libraries, lib *) |
| 4726 | proc searchDir(i: INT): []const U8; |
| 4727 | begin |
| 4728 | if i = -1 then return mainDir; end; |
| 4729 | if i < numInc then return incDirs[i]; end; |
| 4730 | i := i - numInc; |
| 4731 | if i < LEN(userDirs) then return userDirs[i]; end; |
| 4732 | return libDir; |
| 4733 | end; |
| 4734 | |
| 4735 | (* The file of module n in dir that suffix j says: Name.OS-ARCH.raz for |
| 4736 | a file of this target alone (Name.linux-x86_64.raz, say), then |
| 4737 | Name.OS.raz, Name.ARCH.raz, and Name.raz *) |
| 4738 | proc fileName(n, j: INT): []const U8; |
| 4739 | begin |
| 4740 | if j = 0 then |
| 4741 | return Diag.say("{}.{}-{}.raz", [Fmt.str(nameOf(n)), Fmt.str(targetOs), Fmt.str(targetArch)]); |
| 4742 | elsif j = 1 then |
| 4743 | return Diag.say("{}.{}.raz", [Fmt.str(nameOf(n)), Fmt.str(targetOs)]); |
| 4744 | elsif j = 2 then |
| 4745 | return Diag.say("{}.{}.raz", [Fmt.str(nameOf(n)), Fmt.str(targetArch)]); |
| 4746 | end; |
| 4747 | return Diag.say("{}.raz", [Fmt.str(nameOf(n))]); |
| 4748 | end; |
| 4749 | |
| 4750 | proc moduleFile(n: INT): ([]const U8, []const U8, BOOL); |
| 4751 | var i, j: INT; dir, f: []const U8; |
| 4752 | begin |
| 4753 | for i := -1 to numInc + LEN(userDirs) do |
| 4754 | dir := searchDir(i); |
| 4755 | for j := 0 to 3 do |
| 4756 | f := fileName(n, j); |
| 4757 | if exists(modulePath(dir, f)) then return dir, f, true; end; |
| 4758 | end; |
| 4759 | end; |
| 4760 | return "", "", false; |
| 4761 | end; |
| 4762 | |
| 4763 | (* A program has one module of each name: module n, found as dir/f, |
| 4764 | must have no files in a later directory, unless dir/f is a link to |
| 4765 | one of them, which chooses it (report, section 3) *) |
| 4766 | proc checkOneModule(n: INT; dir, f: []const U8; at: Diag.Pos): ERROR; |
| 4767 | var |
| 4768 | i, j, dev, ino, mineDev, mineIno: INT; past, chosen: BOOL; g, files, others: []const U8; |
| 4769 | begin |
| 4770 | mineDev, mineIno := identity(modulePath(dir, f)); |
| 4771 | others := ""; |
| 4772 | past := false; |
| 4773 | for i := -1 to numInc + LEN(userDirs) do |
| 4774 | if past then |
| 4775 | files := ""; |
| 4776 | chosen := false; |
| 4777 | for j := 0 to 3 do |
| 4778 | g := modulePath(searchDir(i), fileName(n, j)); |
| 4779 | if exists(g) then |
| 4780 | files := say2("{} and {}", files, Diag.shownPath(g)); |
| 4781 | dev, ino := identity(g); |
| 4782 | chosen := chosen or ((dev = mineDev) and (ino = mineIno)); |
| 4783 | end; |
| 4784 | end; |
| 4785 | if not chosen then others := say2("{}{}", others, files); end; |
| 4786 | end; |
| 4787 | past := past or (searchDir(i) = dir); |
| 4788 | end; |
| 4789 | if LEN(others) = 0 then return nil; end; |
| 4790 | Diag.error(at, say3("module {} is in {}{}", nameOf(n), Diag.shownPath(modulePath(dir, f)), others)); |
| 4791 | Diag.help("a program has one module of each name; a symbolic link to one of these files chooses it"); |
| 4792 | return Scan.Failed; |
| 4793 | end; |
| 4794 | |
| 4795 | proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); |
| 4796 | var m: PModule; i: INT; dir, f, where: []const U8; found: BOOL; |
| 4797 | begin |
| 4798 | m := findModule(name, args); |
| 4799 | if m # nil then return m, nil; end; |
| 4800 | for i := 0 to numPending - 1 do |
| 4801 | if isModule(pending[i], name, args) then |
| 4802 | return nil, Scan.markAt(args.at, say1("{} imports itself", nameOf(name))); |
| 4803 | end; |
| 4804 | end; |
| 4805 | dir, f, found := moduleFile(name); |
| 4806 | if not found then |
| 4807 | Diag.error(args.at, say1("can't find module {}", nameOf(name))); |
| 4808 | where := Diag.shownPath(searchDir(-1)); |
| 4809 | for i := 0 to numInc + LEN(userDirs) do where := say2("{}, {}", where, Diag.shownPath(searchDir(i))); end; |
| 4810 | Diag.help(say2("looked for {}.raz in {}", nameOf(name), where)); |
| 4811 | return nil, Scan.Failed; |
| 4812 | end; |
| 4813 | try checkOneModule(name, dir, f, args.at); |
| 4814 | originNote := libraryNote(dir); |
| 4815 | m := try compileFile(modulePath(dir, f), name, args, false); |
| 4816 | try checkSiblings(dir, f, name, m, args); |
| 4817 | return m, nil; |
| 4818 | end; |
| 4819 | |
| 4820 | proc addImport(m, im: PModule); |
| 4821 | var imp: ^Sym.Import; |
| 4822 | begin |
| 4823 | NEW(imp, Heap.heap); |
| 4824 | imp^.home := im; |
| 4825 | imp^.next := m^.imports; |
| 4826 | m^.imports := imp; |
| 4827 | end; |
| 4828 | |
| 4829 | (* Makes the instance that deferred[i] imports: its arguments are read |
| 4830 | where the import wrote them, and must be declared by now. Compiling |
| 4831 | the instance comes in the middle of a declaration, so what that |
| 4832 | declaration has under way is kept aside meanwhile. *) |
| 4833 | proc makeInstance(i: INT; at: Diag.Pos): ERROR; |
| 4834 | var |
| 4835 | d: Deferred; st: Scan.State; args: Sym.Args; types, exported, ext, wasQuiet: BOOL; nf, nd: INT; |
| 4836 | lt: [MaxLater]Later; decl: [MaxNames]INT; |
| 4837 | begin |
| 4838 | d := deferred[i]; |
| 4839 | DEC(numDeferred); |
| 4840 | deferred[i] := deferred[numDeferred]; |
| 4841 | Scan.saveScan(st); |
| 4842 | Scan.restoreScan(d.args); |
| 4843 | args.n := 0; |
| 4844 | making := true; useAt := at; |
| 4845 | try parseArgs(args, nameOf(d.mname)); |
| 4846 | making := false; |
| 4847 | Scan.restoreScan(st); |
| 4848 | args.at := d.at; |
| 4849 | types := inTypes; exported := declExported; ext := inExtern; wasQuiet := Diag.quiet; |
| 4850 | nf := numLater; lt := laters; nd := numDeclaring; decl := declaring; |
| 4851 | d.o^.home := try importModule(d.mname, args); |
| 4852 | inTypes := types; declExported := exported; inExtern := ext; Diag.setQuiet(wasQuiet); |
| 4853 | numLater := nf; laters := lt; numDeclaring := nd; declaring := decl; |
| 4854 | addImport(Sym.curModule, d.o^.home); |
| 4855 | return nil; |
| 4856 | end; |
| 4857 | |
| 4858 | proc firstUse(o: PObj; at: Diag.Pos): ERROR; |
| 4859 | var i: INT; |
| 4860 | begin |
| 4861 | for i := 0 to numDeferred - 1 do |
| 4862 | if deferred[i].o = o then return makeInstance(i, at); end; |
| 4863 | end; |
| 4864 | return Scan.Failed; (* its arguments had an error, already reported *) |
| 4865 | end; |
| 4866 | |
| 4867 | (* An instance can't be compiled in the middle of another procedure's |
| 4868 | code, so before a procedure's code begins, from its "proc" on, or |
| 4869 | the module body's, from its "begin" to the end of the file, this |
| 4870 | reads ahead for the names of imports not yet made, and makes those. *) |
| 4871 | proc instancesFor(wholeRest: BOOL): ERROR; |
| 4872 | var st: Scan.State; d, i: INT; begun: BOOL; |
| 4873 | begin |
| 4874 | if checkMode then return nil; end; |
| 4875 | i := numDeferred - 1; |
| 4876 | while (i >= 0) and (deferred[i].home # Sym.curModule) do DEC(i); end; |
| 4877 | if i < 0 then return nil; end; |
| 4878 | (* The procedure ends at the "end" that closes its first "begin": d |
| 4879 | counts the words still open that "end" or "until" closes, and begun |
| 4880 | says that begin was met, so that a record's end in its declarations |
| 4881 | doesn't stop it. A forward or code procedure has no raz body to |
| 4882 | read, so it stops at that word. The body reads to the end of the |
| 4883 | file, as wholeRest says. *) |
| 4884 | Scan.saveScan(st); |
| 4885 | d := 0; begun := false; |
| 4886 | repeat |
| 4887 | match Scan.tok of |
| 4888 | | sIdent: |
| 4889 | for i := numDeferred - 1 to 0 by -1 do |
| 4890 | if (deferred[i].home = Sym.curModule) and (deferred[i].o^.name = Scan.id) then |
| 4891 | try makeInstance(i, Scan.tokPos()); |
| 4892 | end; |
| 4893 | end; |
| 4894 | | sBegin: |
| 4895 | begun := begun or (d = 0); |
| 4896 | INC(d); |
| 4897 | | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d); |
| 4898 | | sEnd, sUntil: DEC(d); |
| 4899 | | else: |
| 4900 | end; |
| 4901 | if not wholeRest and (d = 0) and (begun or (Scan.tok = Scan.sForward) or (Scan.tok = Scan.sCode)) then break; end; |
| 4902 | Scan.next; |
| 4903 | until Scan.tok = Scan.sEof; |
| 4904 | Scan.restoreScan(st); |
| 4905 | return nil; |
| 4906 | end; |
| 4907 | |
| 4908 | (* The main module, from the file at path, and Rt, which every program |
| 4909 | needs, first *) |
| 4910 | proc compileMain*(path: []const U8): (PModule, ERROR); |
| 4911 | var base: []const U8; i, n: INT; none: Sym.Args; m: PModule; |
| 4912 | begin |
| 4913 | none.n := 0; |
| 4914 | i := LEN(path); |
| 4915 | while (i > 0) and (path[i - 1] # '/') do DEC(i); end; |
| 4916 | (* the directory is the path less its last "/"; for "/Main.raz" that would be "", so keep the root *) |
| 4917 | if i = 0 then mainDir := "."; |
| 4918 | elsif i = 1 then mainDir := "/"; |
| 4919 | else mainDir := path[0..i - 1]; end; |
| 4920 | base := path[i..LEN(path)]; |
| 4921 | i := 0; |
| 4922 | while (i < LEN(base)) and (base[i] # '.') do INC(i); end; |
| 4923 | base := base[0..i]; |
| 4924 | if LEN(base) = 0 then Diag.fatal(say1("no module in {}", path)); end; |
| 4925 | n := internName(base); |
| 4926 | none.at := Scan.tokPos(); |
| 4927 | if n # nameRt then _ := try importModule(nameRt, none); end; |
| 4928 | m := findModule(n, none); |
| 4929 | if m # nil then return m, nil; end; |
| 4930 | return compileFile(path, n, none, false); |
| 4931 | end; |
| 4932 | |
| 4933 | begin |
| 4934 | limitK := -1; |
| 4935 | nameRt := internName("Rt"); |
| 4936 | nameFail := internName("fail"); |
| 4937 | nameAdr := internName("ADR"); |
| 4938 | nameCas := internName("CAS"); |
| 4939 | nameXchg := internName("XCHG"); |
| 4940 | nameXadd := internName("XADD"); |
| 4941 | nameBody := internName("body"); |
| 4942 | nameStatic := internName("static"); |
| 4943 | nameCheck := internName("check"); |
| 4944 | nameOff := internName("off"); |
| 4945 | tArgv := newPtr(newPtr(Sym.tU8, false), false); |
| 4946 | tBodySig := Sym.newType(Sym.fProc, 8, 8); |
| 4947 | end Parse. |