From fd47c730868003ff094aa48a112403ee3d91a80d Mon Sep 17 00:00:00 2001 From: xushiwei Date: Wed, 14 Feb 2024 15:21:07 +0800 Subject: [PATCH] gmxMainFunc: force line of main code = (last comment line + 1) --- cl/classfile.go | 5 +++++ cl/compile.go | 9 ++++++--- cl/stmt.go | 32 ++++++++++++++++++++++---------- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/cl/classfile.go b/cl/classfile.go index 725811e09..50f062d43 100644 --- a/cl/classfile.go +++ b/cl/classfile.go @@ -267,6 +267,11 @@ func gmxMainFunc(pkg *gox.Package, ctx *pkgCtx, noAutoGenMain bool) func() { new := pkg.Builtin().Ref("new") cb := fn.BodyStart(pkg).Val(new).Val(o).Call(1).MemberVal("Main") + // force line of main code = (last comment line + 1) + if ctx.lastStmt != nil { + commentStmtEx(cb, ctx, ctx.lastStmt, true) + } + sig := cb.Get(-1).Type.(*types.Signature) narg := gmxMainNarg(sig) if narg > 0 { diff --git a/cl/compile.go b/cl/compile.go index d3b2336f9..f07ee2773 100644 --- a/cl/compile.go +++ b/cl/compile.go @@ -346,6 +346,8 @@ type pkgCtx struct { generics map[string]bool // generic type record idents []*ast.Ident // toType ident recored inInst int // toType in generic instance + + lastStmt ast.Stmt // set by commentStmt for line:xxx } type pkgImp struct { @@ -368,9 +370,10 @@ type blockCtx struct { classRecv *ast.FieldList // available when gmxSettings != nil fileScope *types.Scope // only valid when isGopFile rec *typesRecorder - fileLine bool - isClass bool - isGopFile bool // is Go+ file or not + + fileLine bool + isClass bool + isGopFile bool // is Go+ file or not } func (bc *blockCtx) recorder() *typesRecorder { diff --git a/cl/stmt.go b/cl/stmt.go index 8c76e460e..ca4ac27c2 100644 --- a/cl/stmt.go +++ b/cl/stmt.go @@ -47,17 +47,29 @@ func relFile(dir string, absFile string) string { func commentStmt(ctx *blockCtx, stmt ast.Stmt) { if ctx.fileLine { - start := stmt.Pos() - pos := ctx.fset.Position(start) - if ctx.relBaseDir != "" { - pos.Filename = fileLineFile(ctx.relBaseDir, pos.Filename) - } - line := fmt.Sprintf("\n//line %s:%d:1", pos.Filename, pos.Line) - comments := &goast.CommentGroup{ - List: []*goast.Comment{{Text: line}}, - } - ctx.cb.SetComments(comments, false) + ctx.lastStmt = stmt // for gmxMainFunc + commentStmtEx(ctx.cb, ctx.pkgCtx, stmt, false) + } +} + +func commentStmtEx(cb *gox.CodeBuilder, ctx *pkgCtx, stmt ast.Stmt, next bool) { + var start token.Pos + var delta int + if next { + start = stmt.End() - 1 + delta = 1 + } else { + start = stmt.Pos() + } + pos := ctx.fset.Position(start) + if ctx.relBaseDir != "" { + pos.Filename = fileLineFile(ctx.relBaseDir, pos.Filename) + } + line := fmt.Sprintf("\n//line %s:%d:1", pos.Filename, pos.Line+delta) + comments := &goast.CommentGroup{ + List: []*goast.Comment{{Text: line}}, } + cb.SetComments(comments, false) } func commentFunc(ctx *blockCtx, fn *gox.Func, decl *ast.FuncDecl) {