@@ -15,6 +15,7 @@ import (
15
15
"os"
16
16
"os/exec"
17
17
"path/filepath"
18
+ "slices"
18
19
"strings"
19
20
"unicode"
20
21
@@ -255,7 +256,12 @@ func (s *Session) evalStmt(in string) error {
255
256
case * ast.DeclStmt :
256
257
if decl , ok := stmt .Decl .(* ast.GenDecl ); ok {
257
258
if decl .Tok == token .TYPE {
258
- s .file .Decls = append (s .file .Decls , decl )
259
+ for i , d := range s .file .Decls {
260
+ if d , ok := d .(* ast.FuncDecl ); ok && d .Name .String () == "main" {
261
+ s .file .Decls = slices .Insert (s .file .Decls , i , stmt .Decl )
262
+ break
263
+ }
264
+ }
259
265
continue
260
266
} else if stmt := buildPrintStmtOfDecl (decl ); stmt != nil {
261
267
stmts = append (stmts , stmt )
@@ -317,17 +323,23 @@ func (s *Session) evalFunc(in string) error {
317
323
if len (f .Decls ) != 1 {
318
324
return errors .New ("eval func error" )
319
325
}
320
- newDecl , ok := f .Decls [0 ].( * ast. FuncDecl )
321
- if ! ok {
326
+ decl , name := f .Decls [0 ], ""
327
+ if d , ok := decl .( * ast. FuncDecl ); ! ok {
322
328
return errors .New ("eval func error" )
329
+ } else {
330
+ name = d .Name .String ()
323
331
}
324
332
for i , d := range s .file .Decls {
325
- if d , ok := d .(* ast.FuncDecl ); ok && d .Name .String () == newDecl .Name .String () {
326
- s .file .Decls = append (s .file .Decls [:i ], s .file .Decls [i + 1 :]... )
327
- break
333
+ if d , ok := d .(* ast.FuncDecl ); ok {
334
+ if d .Name .String () == name {
335
+ s .file .Decls [i ] = decl
336
+ break
337
+ } else if d .Name .String () == "main" {
338
+ s .file .Decls = slices .Insert (s .file .Decls , i , decl )
339
+ break
340
+ }
328
341
}
329
342
}
330
- s .file .Decls = append (s .file .Decls , newDecl )
331
343
return nil
332
344
}
333
345
@@ -502,10 +514,7 @@ func (s *Session) invokeCommand(in string) (err error) {
502
514
// storeCode stores current state of code so that it can be restored
503
515
func (s * Session ) storeCode () {
504
516
s .lastStmts = s .mainBody .List
505
- if len (s .lastDecls ) != len (s .file .Decls ) {
506
- s .lastDecls = make ([]ast.Decl , len (s .file .Decls ))
507
- }
508
- copy (s .lastDecls , s .file .Decls )
517
+ s .lastDecls = slices .Clone (s .file .Decls )
509
518
}
510
519
511
520
// restoreCode restores the previous code
0 commit comments