fix(compiler,hbrt,hbrdd,cli): pre-1.0 audit — 13 critical fixes
Senior-engineer / QA audit landed 13 silent-miscompile and data-
integrity fixes spanning the whole compiler+runtime+storage stack.
Each fix is paired with either an integration test in the suite or
a focused regression check; all 6 release gates stay green:
go test ./..., FiveSql2 43/43, Harbour compat 56/56, std.ch 17/17,
FRB 7/7, examples 65/71.
Compiler
--------
* genpc IF/ELSEIF jumpEnd2 patching (compiler/genpc/genpc.go).
Per-ELSEIF branch terminators were stashed into `_ = jumpEnd2`
and never patched — the relative offset stayed 0 and the runtime
walked the next ELSEIF's PcOpJumpFalse opcode as if it were
jump-offset data. Bytecode-level corruption in pcode mode. Now
collected into a slice and patched at end-of-IF. Verified via
Grade(95..50) cases 11a-e added to tests/frb/test_frb_pcode_sweep.
* countLocalsInStmts / scanBodyLocals missing bodies
(compiler/gengo/gen_util.go, compiler/gengo/gengo.go). Frame-size
counter skipped WATCH/TIMEOUT/PARALLEL FOR bodies, so a LOCAL
declared inside one of those constructs got a slot index past
the runtime's allocated count — silent NIL reads or out-of-range
stomps.
* emitMethodDeclStandalone nested LOCAL (compiler/gengo/gen_class.go).
Same bug class but on the *method* side. Pre-fix repro:
METHOD Stomp(n) CLASS T
LOCAL a := 1, b := 2
IF n > 0
LOCAL c := 30, d := 40, e := 50, f := 60
Inner( n )
IF c != 30 .OR. d != 40 .OR. e != 50 .OR. f != 60 ...
printed `c, d, e, f = 5, NIL, NIL, NIL` because Inner's frame
collided with Stomp's underallocated slot range. Now counts
body-nested LOCALs into the frame and pre-allocates indices via
scanBodyLocals.
* genpc unsupported-AST diagnostic surface (compiler/genpc/genpc.go,
hbrt/pcode.go, cmd/five/main.go, hbrtl/frb.go). The `default`
cases in emitStmt / emitExpr silently emitted PushNil / no-op
for nodes the pcode generator doesn't implement (ClassDecl,
MethodDecl, xBase commands, concurrency primitives, …). Added
`PcodeModule.Warnings []string` populated by noteUnsupported,
surfaced on stderr from the build pipeline. Users now see
"pcode: AST node not supported in --pcode/FRB-pcode mode: stmt
*ast.GoBlockStmt" instead of getting a silently broken module.
Runtime
-------
* class.go Send/tryBinaryOp t.self defer-restore (hbrt/class.go).
Restoration was a plain `t.self = oldSelf` after `fn(t)`. Any
panic in the method body skipped the line, so the next BEGIN
SEQUENCE / RECOVER handler ran with the THROWING object's Self
— `::field` resolved against the wrong receiver. Wrapped both
restore sites in `defer func() { t.self = oldSelf }()`.
Verified: pre-fix RECOVER saw "THROWER", post-fix "OUTER".
* hbfunc.go HB_FUNC parameter Frame() (hbrt/hbfunc.go). The
RegisterDynamicFunc wrapper called `fn(ctx)` without ever
calling Frame, so `ctx.ParC(1)` / `ctx.Local(n)` read through
`t.curFrame.localBase + n - 1` against the *caller's* frame.
Every #pragma BEGINDUMP HB_FUNC taking parameters silently
returned "" / 0 / "" for them — masked by ParNIDef-style
defaults. Wrapper now does `t.Frame(t.pendingParams, 0); defer
t.EndProc()` before dispatch.
* pcode codeblock closure capture (hbrt/pcinterp.go, hbrt/pcode.go,
hbrt/thread.go, compiler/genpc/genpc.go). PcOpPushBlock recorded
`nDetached` but never copied enclosing locals; free vars in the
block body fell through to memvar lookup → NIL. Wired full
capture pipeline:
- New opcodes PcOpPushDetached (0x59) / PcOpPopDetached (0x5A).
- PushBlock now reads per-slot source-local indices and
snapshots into bb.Detached at construction time.
- New detachedMap in genpc auto-promotes any free var that
resolves to an enclosing-frame local into a capture slot.
- emitAssignAsExpr leaves the assigned value on the eval stack
so SeqExpr items like `{|v| acc += v, acc }` work.
- Thread tracks curBlock with paired Set/restore in the block's
Fn wrapper for nested-block evaluation.
Mutating capture (acc += v across successive Evals) now works.
* vm.NewThread statics + waFactory propagation (hbrt/vm.go).
GoLaunch / GoLaunchBlock call NewThread directly. Previously
the statics map and WA factory were applied only in Run(), so
goroutine-spawned PRG code panicked on STATIC access ("static
index out of range") and crashed dereferencing nil WA on any
DB call. Both now happen inside NewThread under the same lock
as TID assignment.
Data layer
----------
* dbf concurrent Append lock (hbrdd/dbf/dbf.go,
hbrdd/dbf/locks_posix.go, hbrdd/dbf/locks_windows.go). Append
bumped a local recCount with no file-system serialization. Two
shared-mode processes both wrote at the same RecordOffset; one
record silently overwrote the other. Added an append-intent
byte-range lock at offset 0x7FFFFFFE + bounded retry, on-disk
header refresh inside the locked region, and immediate header
write so peers refresh past our slot.
* indexer negative numeric key encoding (hbrdd/dbf/indexer.go +
new hbrdd/dbf/encode_numeric_test.go). `%20.10f` formats `-100`
as `" -100.0000000000"` and `99` as `" 99.0000000000"`.
ASCII ' ' (0x20) < '-' (0x2D), so `99` lex-compared LESS than
`-100` — every NTX/CDX index over a column that ever held a
negative number returned wrong rows for SEEK / range scans.
Replaced with a 1-byte sign prefix + 21-byte zero-padded
magnitude (negatives use digit-complement) so byte order
matches numeric order across signs and magnitudes. Format
change: existing indexes built with the old encoding must be
REINDEXed. Three unit tests pin the order.
* dbf Append index maintenance hooks (hbrdd/dbf/dbf.go,
hbrdd/dbf/indexer.go). Append never inserted into open NTX/CDX
indexes — the audit's canonical scenario `SET INDEX TO …;
APPEND BLANK; REPLACE …; dbSeek …` silently missed the new
record. Added optional IndexWriter interface, queue the new
recNo in pendingIdxInserts, drain after flushRecord by calling
InsertKey on every open writer-supporting engine. NTX
participates (its existing rebuild-on-insert is correct);
CDX online maintenance is deferred to a follow-up — those
indexes still need REINDEX. Verified: post-fix SEEK("Charlie")
after APPEND BLANK + REPLACE finds the new record.
* dbf PACK crash-safety (hbrdd/dbf/dbf.go). The old in-place
rewrite read record N, overwrote slot M<N, then truncated.
Power loss after partial loop left a file with overwritten
prefix and no original copies of the records already advanced
past — silent data loss. Rewrote to:
1) drop mmap, build `<file>.pack.tmp` with all surviving
records,
2) Sync(),
3) close original handle + os.Rename(tmp, orig) (atomic on
same FS),
4) reopen + re-mmap.
TestComp_Pack passes; readers always see either the pre-PACK
or post-PACK contents, never a half-state.
* mem RDD torn reads (hbrdd/mem/memrdd.go). The comment claimed
in-place PutValue was safe because hbrt.Value "fits in a
single machine word + pointer". hbrt.Value is 24 bytes (3
words) — a concurrent reader could observe new type tag with
stale scalar/ptr and type-confuse on the next AsXxx() call.
Switched mu to sync.RWMutex; GetValue takes RLock,
Append/PutValue/Delete/Recall take Lock. `go test -race
./hbrdd/mem/` clean.
Files touched
-------------
compiler/gengo/gen_class.go, gen_util.go, gengo.go
compiler/genpc/genpc.go
hbrt/class.go, hbfunc.go, pcinterp.go, pcode.go, thread.go, vm.go
hbrdd/dbf/dbf.go, indexer.go, locks_posix.go, locks_windows.go
hbrdd/dbf/encode_numeric_test.go (new)
hbrdd/mem/memrdd.go
cmd/five/main.go
hbrtl/frb.go
tests/frb/test_frb_pcode_sweep.prg
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -156,6 +156,15 @@ func (g *Generator) emitMethodDeclStandalone(md *ast.MethodDecl) {
|
||||
nLocals += len(vd.Vars)
|
||||
}
|
||||
}
|
||||
// Mid-method and nested LOCAL declarations (inside IF / FOR /
|
||||
// WHILE / DO CASE / SEQUENCE / WATCH / TIMEOUT / PARALLEL FOR)
|
||||
// must also be counted into the runtime frame size. The
|
||||
// FuncDecl emitter already walks the body via
|
||||
// countLocalsInStmts; methods used to short-circuit this and
|
||||
// only count top-level Decls, so `METHOD Foo(): … IF cond …
|
||||
// LOCAL x …` underallocated the frame and `x` either read NIL
|
||||
// or stomped a sibling local.
|
||||
nLocals += countLocalsInStmts(md.Body)
|
||||
|
||||
g.writeln(fmt.Sprintf("func %s(t *hbrt.Thread) {", goFuncName))
|
||||
g.indent++
|
||||
@@ -182,6 +191,9 @@ func (g *Generator) emitMethodDeclStandalone(md *ast.MethodDecl) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pre-allocate slots for body-nested LOCALs so emitStmt's
|
||||
// mid-function VarDecl handler stores into the right index.
|
||||
scanBodyLocals(md.Body, localMap, &idx)
|
||||
|
||||
g.curLocals = localMap
|
||||
// Bind defining class for ::super: resolution in emitSendExpr.
|
||||
|
||||
@@ -105,6 +105,19 @@ func countLocalsInStmts(stmts []ast.Stmt) int {
|
||||
n += countLocalsInStmts(c.Body)
|
||||
}
|
||||
n += countLocalsInStmts(v.Otherwise)
|
||||
case *ast.WatchStmt:
|
||||
// `WATCH ... CASE ... CASE ... OTHERWISE ... END WATCH`
|
||||
// — each CASE body and OTHERWISE may declare LOCALs.
|
||||
for _, c := range v.Cases {
|
||||
n += countLocalsInStmts(c.Body)
|
||||
}
|
||||
n += countLocalsInStmts(v.Otherwise)
|
||||
case *ast.TimeoutStmt:
|
||||
// `WITH TIMEOUT n SECONDS ... END` — body may declare LOCALs.
|
||||
n += countLocalsInStmts(v.Body)
|
||||
case *ast.ParallelForStmt:
|
||||
// `PARALLEL FOR i := ... NEXT` — body may declare LOCALs.
|
||||
n += countLocalsInStmts(v.Body)
|
||||
}
|
||||
}
|
||||
return n
|
||||
|
||||
@@ -726,6 +726,18 @@ func scanBodyLocals(stmts []ast.Stmt, m localMap, idx *int) {
|
||||
case *ast.SeqStmt:
|
||||
scanBodyLocals(st.Body, m, idx)
|
||||
scanBodyLocals(st.RecoverBody, m, idx)
|
||||
case *ast.WatchStmt:
|
||||
// Each WATCH CASE / OTHERWISE body may host LOCALs that
|
||||
// need pre-assigned slot indices to match the frame size
|
||||
// counted by countLocalsInStmts.
|
||||
for _, c := range st.Cases {
|
||||
scanBodyLocals(c.Body, m, idx)
|
||||
}
|
||||
scanBodyLocals(st.Otherwise, m, idx)
|
||||
case *ast.TimeoutStmt:
|
||||
scanBodyLocals(st.Body, m, idx)
|
||||
case *ast.ParallelForStmt:
|
||||
scanBodyLocals(st.Body, m, idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ import (
|
||||
"five/compiler/ast"
|
||||
"five/compiler/token"
|
||||
"five/hbrt"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -29,9 +31,16 @@ func Generate(file *ast.File) *hbrt.PcodeModule {
|
||||
switch decl := d.(type) {
|
||||
case *ast.FuncDecl:
|
||||
g.emitFunc(decl)
|
||||
default:
|
||||
// ClassDecl, MethodDecl, top-level VarDecl, etc. are not
|
||||
// expressible in pcode form today — record the kind so the
|
||||
// caller can surface a clear "rebuild without --pcode"
|
||||
// diagnostic instead of silently dropping the declaration.
|
||||
g.noteUnsupported(fmt.Sprintf("%T", decl))
|
||||
}
|
||||
}
|
||||
|
||||
g.mod.Warnings = g.Warnings()
|
||||
return g.mod
|
||||
}
|
||||
|
||||
@@ -64,6 +73,89 @@ type generator struct {
|
||||
mod *hbrt.PcodeModule
|
||||
code []byte
|
||||
locals map[string]int
|
||||
// detached, when non-nil, intercepts IdentExpr/AssignExpr lookups
|
||||
// inside a block body. Names found in the *enclosing* locals are
|
||||
// auto-promoted to capture slots in declaration order so the body
|
||||
// emits PcOpPushDetached / PcOpPopDetached against the slot index
|
||||
// rather than falling through to the runtime memvar table.
|
||||
detached *detachedMap
|
||||
// Unsupported AST node kinds encountered during emit, recorded
|
||||
// once per kind. Exposed via Module().Warnings so the build
|
||||
// pipeline can surface a clear "node X not supported in pcode
|
||||
// mode" diagnostic instead of silently emitting PushNil/no-op
|
||||
// (the previous behavior, which masked bugs as wrong results).
|
||||
unsupported map[string]bool
|
||||
}
|
||||
|
||||
// noteUnsupported records that an AST node kind was hit by the
|
||||
// silent-fallback path. Caller emits PushNil/Pop to keep the stack
|
||||
// shape valid; the diagnostic itself is collected and reported once
|
||||
// per kind at module-level after Generate completes.
|
||||
func (g *generator) noteUnsupported(kind string) {
|
||||
if g.unsupported == nil {
|
||||
g.unsupported = map[string]bool{}
|
||||
}
|
||||
g.unsupported[kind] = true
|
||||
}
|
||||
|
||||
// Warnings returns the accumulated unsupported-node diagnostics in
|
||||
// stable (sorted) order so build output is deterministic.
|
||||
func (g *generator) Warnings() []string {
|
||||
if len(g.unsupported) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(g.unsupported))
|
||||
for k := range g.unsupported {
|
||||
out = append(out, "pcode: AST node not supported in --pcode/FRB-pcode mode: "+k+
|
||||
" (emitted as no-op; rebuild without --pcode to keep this construct)")
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// detachedMap accumulates the closure captures requested by a block
|
||||
// body in encounter order. The enclosing scope's locals map is read
|
||||
// to translate a free-variable name into the source-local index that
|
||||
// the PushBlock op must snapshot.
|
||||
type detachedMap struct {
|
||||
enclosing map[string]int // outer scope's local name -> 1-based local index
|
||||
slot map[string]int // captured name -> 0-based detached slot
|
||||
srcOrder []int // 0-based slot -> source local index (1-based)
|
||||
}
|
||||
|
||||
func newDetachedMap(enclosing map[string]int) *detachedMap {
|
||||
return &detachedMap{
|
||||
enclosing: enclosing,
|
||||
slot: map[string]int{},
|
||||
}
|
||||
}
|
||||
|
||||
// resolve returns (slot, true) if `name` resolves through the
|
||||
// enclosing scope and reserves a capture slot for it on first use.
|
||||
// Returns (0, false) for names not in the enclosing scope — caller
|
||||
// falls back to the memvar lookup or another resolution path.
|
||||
func (d *detachedMap) resolve(name string) (int, bool) {
|
||||
if d == nil {
|
||||
return 0, false
|
||||
}
|
||||
if s, ok := d.slot[name]; ok {
|
||||
return s, true
|
||||
}
|
||||
src, ok := d.enclosing[name]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
s := len(d.srcOrder)
|
||||
d.slot[name] = s
|
||||
d.srcOrder = append(d.srcOrder, src)
|
||||
return s, true
|
||||
}
|
||||
|
||||
func (d *detachedMap) sources() []int {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return d.srcOrder
|
||||
}
|
||||
|
||||
func (g *generator) emit(b ...byte) {
|
||||
@@ -239,7 +331,10 @@ func (g *generator) emitStmt(stmt ast.Stmt) {
|
||||
}
|
||||
|
||||
default:
|
||||
// Unsupported statement — skip
|
||||
// Unsupported statement — record once per kind so the build
|
||||
// pipeline can surface a clear "AST node not supported in
|
||||
// pcode mode" warning instead of silently dropping the stmt.
|
||||
g.noteUnsupported(fmt.Sprintf("stmt %T", stmt))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,7 +347,14 @@ func (g *generator) emitIf(s *ast.IfStmt) {
|
||||
}
|
||||
|
||||
if len(s.ElseIfs) > 0 || len(s.ElseBody) > 0 {
|
||||
jumpEnd := g.emitJumpPlaceholder(hbrt.PcOpJump)
|
||||
// `jumpEnds` collects every "branch-taken → skip rest of IF"
|
||||
// jump that has to be patched once the entire IF chain ends.
|
||||
// Original code only stashed each ELSEIF's terminator in `_ =
|
||||
// jumpEnd2` and never patched it, so the offset stayed 0 and
|
||||
// the runtime kept walking into the next ELSEIF's
|
||||
// PcOpJumpFalse opcode as if it were data — silent bytecode
|
||||
// corruption in pcode mode.
|
||||
jumpEnds := []int{g.emitJumpPlaceholder(hbrt.PcOpJump)}
|
||||
g.patchJump(jumpFalse)
|
||||
|
||||
for _, elif := range s.ElseIfs {
|
||||
@@ -261,15 +363,16 @@ func (g *generator) emitIf(s *ast.IfStmt) {
|
||||
for _, stmt := range elif.Body {
|
||||
g.emitStmt(stmt)
|
||||
}
|
||||
jumpEnd2 := g.emitJumpPlaceholder(hbrt.PcOpJump)
|
||||
jumpEnds = append(jumpEnds, g.emitJumpPlaceholder(hbrt.PcOpJump))
|
||||
g.patchJump(nextJump)
|
||||
_ = jumpEnd2 // will be patched by end
|
||||
}
|
||||
|
||||
for _, stmt := range s.ElseBody {
|
||||
g.emitStmt(stmt)
|
||||
}
|
||||
g.patchJump(jumpEnd)
|
||||
for _, j := range jumpEnds {
|
||||
g.patchJump(j)
|
||||
}
|
||||
} else {
|
||||
g.patchJump(jumpFalse)
|
||||
}
|
||||
@@ -409,6 +512,12 @@ func (g *generator) emitExpr(expr ast.Expr) {
|
||||
if idx, ok := g.locals[upper]; ok {
|
||||
g.emit(hbrt.PcOpPushLocal)
|
||||
g.emitU16(uint16(idx))
|
||||
} else if slot, ok := g.detached.resolve(upper); ok {
|
||||
// Free variable that resolves to an enclosing-frame
|
||||
// local — promote to a closure capture slot and read it
|
||||
// from this block's Detached at runtime.
|
||||
g.emit(hbrt.PcOpPushDetached)
|
||||
g.emitU16(uint16(slot))
|
||||
} else {
|
||||
// Unknown at compile time → runtime memvar lookup. This
|
||||
// makes `&(expr)` and the debugger's `p` see PRIVATEs
|
||||
@@ -471,33 +580,43 @@ func (g *generator) emitExpr(expr ast.Expr) {
|
||||
|
||||
case *ast.BlockExpr:
|
||||
// `{|p| body }` — compile body to its own pcode buffer with
|
||||
// the block's params occupying locals 1..len(Params), then
|
||||
// emit PcOpPushBlock + length + body bytes + nDetached (zero
|
||||
// — closure capture isn't wired up in pcode mode yet, so
|
||||
// blocks see their declared params and any module-local
|
||||
// symbol but no caller locals).
|
||||
// Without this case, BlockExpr fell through to the generic
|
||||
// PushNil and Eval(NIL, ...) returned NIL — silently
|
||||
// breaking every higher-order function (Eval / AEval /
|
||||
// SqlScan predicate compile / etc.) inside a pcode body.
|
||||
// the block's params occupying locals 1..len(Params). Free
|
||||
// variables in the body that resolve to an enclosing-frame
|
||||
// local are routed through Detached[i]: PcOpPushDetached /
|
||||
// PcOpPopDetached. The block creator (PcOpPushBlock) records
|
||||
// each captured slot's source-local index so the interpreter
|
||||
// snapshots the enclosing value into Detached[i] at block
|
||||
// construction time.
|
||||
//
|
||||
// Without this, every closure that referenced a caller local
|
||||
// fell through to the runtime memvar lookup and silently
|
||||
// returned NIL — silently breaking AEval/Eval/SqlScan
|
||||
// predicates in --pcode / FRB-pcode mode.
|
||||
savedCode := g.code
|
||||
savedLocals := g.locals
|
||||
savedDet := g.detached
|
||||
g.code = nil
|
||||
g.locals = make(map[string]int, len(e.Params))
|
||||
g.detached = newDetachedMap(savedLocals) // capture-on-demand
|
||||
for i, p := range e.Params {
|
||||
g.locals[strings.ToUpper(p)] = i + 1
|
||||
}
|
||||
g.emitExpr(e.Body)
|
||||
g.emit(hbrt.PcOpRetValue)
|
||||
body := g.code
|
||||
captureIdx := g.detached.sources() // src indices in capture order
|
||||
g.code = savedCode
|
||||
g.locals = savedLocals
|
||||
g.detached = savedDet
|
||||
|
||||
g.emit(hbrt.PcOpPushBlock)
|
||||
g.emitI32(int32(len(body)))
|
||||
g.code = append(g.code, body...)
|
||||
g.emitU16(uint16(len(e.Params))) // nParams
|
||||
g.emitU16(0) // nDetached — no closure capture yet
|
||||
g.emitU16(uint16(len(e.Params))) // nParams
|
||||
g.emitU16(uint16(len(captureIdx))) // nDetached
|
||||
for _, srcIdx := range captureIdx {
|
||||
g.emitU16(uint16(srcIdx))
|
||||
}
|
||||
|
||||
case *ast.SeqExpr:
|
||||
// Comma-separated expression list inside a code block:
|
||||
@@ -580,11 +699,91 @@ func (g *generator) emitExpr(expr ast.Expr) {
|
||||
}
|
||||
g.emit(hbrt.PcOpPushNil)
|
||||
|
||||
case *ast.AssignExpr:
|
||||
// Assignment as an expression — perform the store and leave
|
||||
// the assigned value on the eval stack so a containing
|
||||
// expression (e.g. SeqExpr inside `{|| acc += v, acc }`) can
|
||||
// consume it. emitAssign by itself is statement-shaped and
|
||||
// pops the value; we route through it then push the final
|
||||
// value with a load matching the destination.
|
||||
g.emitAssignAsExpr(e)
|
||||
|
||||
default:
|
||||
g.emit(hbrt.PcOpPushNil) // fallback
|
||||
// Record the unsupported kind and emit PushNil so the stack
|
||||
// shape stays valid — callers can keep compiling but the
|
||||
// build pipeline raises a clear pcode-mode-incompat warning.
|
||||
g.noteUnsupported(fmt.Sprintf("expr %T", expr))
|
||||
g.emit(hbrt.PcOpPushNil)
|
||||
}
|
||||
}
|
||||
|
||||
// emitAssignAsExpr emits an assignment whose value remains on the
|
||||
// eval stack (expression context). Mirrors emitAssign's storage
|
||||
// paths but appends a value-producing load so callers — typically
|
||||
// SeqExpr items inside a code block body — can chain.
|
||||
func (g *generator) emitAssignAsExpr(a *ast.AssignExpr) {
|
||||
// Local / detached compound op.
|
||||
if a.Op != token.ASSIGN {
|
||||
if op, ok := compoundBinOp(a.Op); ok {
|
||||
if ident, isIdent := a.Left.(*ast.IdentExpr); isIdent {
|
||||
up := strings.ToUpper(ident.Name)
|
||||
if idx, found := g.locals[up]; found {
|
||||
g.emit(hbrt.PcOpPushLocal)
|
||||
g.emitU16(uint16(idx))
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(op)
|
||||
g.emit(hbrt.PcOpDup) // keep value as expression result
|
||||
g.emit(hbrt.PcOpPopLocal)
|
||||
g.emitU16(uint16(idx))
|
||||
return
|
||||
}
|
||||
if slot, ok := g.detached.resolve(up); ok {
|
||||
g.emit(hbrt.PcOpPushDetached)
|
||||
g.emitU16(uint16(slot))
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(op)
|
||||
g.emit(hbrt.PcOpDup)
|
||||
g.emit(hbrt.PcOpPopDetached)
|
||||
g.emitU16(uint16(slot))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Plain assignment.
|
||||
if ident, ok := a.Left.(*ast.IdentExpr); ok {
|
||||
up := strings.ToUpper(ident.Name)
|
||||
if idx, found := g.locals[up]; found {
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(hbrt.PcOpDup)
|
||||
g.emit(hbrt.PcOpPopLocal)
|
||||
g.emitU16(uint16(idx))
|
||||
return
|
||||
}
|
||||
if slot, ok := g.detached.resolve(up); ok {
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(hbrt.PcOpDup)
|
||||
g.emit(hbrt.PcOpPopDetached)
|
||||
g.emitU16(uint16(slot))
|
||||
return
|
||||
}
|
||||
}
|
||||
// Self field setter — :=. PcOpSetSelfField consumes the value
|
||||
// and pushes nothing; re-emit Right after to leave the value.
|
||||
if send, ok := a.Left.(*ast.SendExpr); ok {
|
||||
if _, isSelf := send.Object.(*ast.SelfExpr); isSelf {
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(hbrt.PcOpDup)
|
||||
g.emitString(hbrt.PcOpSetSelfField, strings.ToUpper(send.Method))
|
||||
return
|
||||
}
|
||||
}
|
||||
// Fallback: evaluate Right and leave it as the expression value
|
||||
// (no destination wired). Mirrors the statement-form fallback
|
||||
// minus the trailing Pop.
|
||||
g.emitExpr(a.Right)
|
||||
}
|
||||
|
||||
func (g *generator) emitBinaryOp(op token.Kind) {
|
||||
switch op {
|
||||
case token.PLUS:
|
||||
@@ -701,7 +900,8 @@ func (g *generator) emitAssign(a *ast.AssignExpr) {
|
||||
op, ok := compoundBinOp(a.Op)
|
||||
if ok {
|
||||
if ident, isIdent := a.Left.(*ast.IdentExpr); isIdent {
|
||||
if idx, found := g.locals[strings.ToUpper(ident.Name)]; found {
|
||||
up := strings.ToUpper(ident.Name)
|
||||
if idx, found := g.locals[up]; found {
|
||||
g.emit(hbrt.PcOpPushLocal)
|
||||
g.emitU16(uint16(idx))
|
||||
g.emitExpr(a.Right)
|
||||
@@ -710,16 +910,35 @@ func (g *generator) emitAssign(a *ast.AssignExpr) {
|
||||
g.emitU16(uint16(idx))
|
||||
return
|
||||
}
|
||||
if slot, ok := g.detached.resolve(up); ok {
|
||||
// Compound on a captured outer local — read/
|
||||
// write through Detached so the closure mutates
|
||||
// the captured snapshot.
|
||||
g.emit(hbrt.PcOpPushDetached)
|
||||
g.emitU16(uint16(slot))
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(op)
|
||||
g.emit(hbrt.PcOpPopDetached)
|
||||
g.emitU16(uint16(slot))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ident, ok := a.Left.(*ast.IdentExpr); ok {
|
||||
if idx, found := g.locals[strings.ToUpper(ident.Name)]; found {
|
||||
up := strings.ToUpper(ident.Name)
|
||||
if idx, found := g.locals[up]; found {
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(hbrt.PcOpPopLocal)
|
||||
g.emitU16(uint16(idx))
|
||||
return
|
||||
}
|
||||
if slot, ok := g.detached.resolve(up); ok {
|
||||
g.emitExpr(a.Right)
|
||||
g.emit(hbrt.PcOpPopDetached)
|
||||
g.emitU16(uint16(slot))
|
||||
return
|
||||
}
|
||||
}
|
||||
// Self field assignment
|
||||
if send, ok := a.Left.(*ast.SendExpr); ok {
|
||||
|
||||
Reference in New Issue
Block a user