github.com/Konstantin8105/c4go@v0.0.0-20240505174241-768bb1c65a51/transpiler/util.go (about) 1 // This file contains utility and helper methods for the transpiler. 2 3 package transpiler 4 5 import ( 6 goast "go/ast" 7 "reflect" 8 ) 9 10 func isNil(stmt goast.Node) bool { 11 if stmt == nil { 12 return true 13 } 14 return reflect.ValueOf(stmt).IsNil() 15 } 16 17 func convertDeclToStmt(decls []goast.Decl) (stmts []goast.Stmt) { 18 for i := range decls { 19 if decls[i] != nil { 20 stmts = append(stmts, &goast.DeclStmt{Decl: decls[i]}) 21 } 22 } 23 return 24 } 25 26 func combinePreAndPostStmts( 27 pre []goast.Stmt, 28 post []goast.Stmt, 29 newPre []goast.Stmt, 30 newPost []goast.Stmt) ([]goast.Stmt, []goast.Stmt) { 31 pre = append(pre, nilFilterStmts(newPre)...) 32 post = append(post, nilFilterStmts(newPost)...) 33 34 return pre, post 35 } 36 37 // nilFilterDecl - remove nil decls from slice 38 func nilFilterDecl(decls []goast.Decl) (out []goast.Decl) { 39 for _, decl := range decls { 40 if isNil(decl) { 41 panic("Found nil decl") 42 } 43 } 44 return decls 45 } 46 47 // nilFilterStmts - remove nil stmt from slice 48 func nilFilterStmts(stmts []goast.Stmt) (out []goast.Stmt) { 49 for _, stmt := range stmts { 50 if isNil(stmt) { 51 panic("Found nil stmt") 52 } 53 } 54 return stmts 55 } 56 57 // combineStmts - combine elements to slice 58 func combineStmts(preStmts []goast.Stmt, stmt goast.Stmt, postStmts []goast.Stmt) (stmts []goast.Stmt) { 59 stmts = make([]goast.Stmt, 0, 1+len(preStmts)+len(postStmts)) 60 61 preStmts = nilFilterStmts(preStmts) 62 if preStmts != nil { 63 stmts = append(stmts, preStmts...) 64 } 65 if !isNil(stmt) { 66 stmts = append(stmts, stmt) 67 } 68 postStmts = nilFilterStmts(postStmts) 69 if postStmts != nil { 70 stmts = append(stmts, postStmts...) 71 } 72 return 73 }