本文整理汇总了Golang中go/ast.BlockStmt类的典型用法代码示例。如果您正苦于以下问题:Golang BlockStmt类的具体用法?Golang BlockStmt怎么用?Golang BlockStmt使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BlockStmt类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: funcBody
// Sets multiLine to true if the function body spans multiple lines.
func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLine *bool) {
if b == nil {
return
}
p.nesting++
defer func() {
p.nesting--
}()
if p.isOneLineFunc(b, headerSize) {
sep := vtab
if isLit {
sep = blank
}
p.print(sep, b.Pos(), token.LBRACE)
if len(b.List) > 0 {
p.print(blank)
for i, s := range b.List {
if i > 0 {
p.print(token.SEMICOLON, blank)
}
p.stmt(s, i == len(b.List)-1, ignoreMultiLine)
}
p.print(blank)
}
p.print(b.Rbrace, token.RBRACE)
return
}
p.print(blank)
p.block(b, 1)
*multiLine = true
}
示例2: rewriteFnWithRecovers
func rewriteFnWithRecovers(body *ast.BlockStmt, fnType *ast.FuncType) (wrapped *ast.FuncLit) {
// The formatting of the channel declaration is ugly, but it's presented this way here to show how it will look in the actual output.
// As far as I know, I would need to set the token.Pos values for the left and right braces of the struct and interface type literals
// in order to get them on one line, but I don't think I can do that without computing all of the other token.Pos values for everything
// else I generate.
// TODO: These identifiers will probably conflict if there is a nested function that also has unnamed outputs. Should probably make a better gensym.
outputDecls, outputs := inputsOrOutputs(fnType.Results, idents.result)
if len(outputs) > 0 {
body.List = astPrintf(`%s = func() (%s) {%s}()`, outputs, fnType.Results, body.List)
}
body.List = astPrintf(`
{{%s}}
_r := make(chan chan interface {
})
recovers, panicChan := godebug.EnterFuncWithRecovers(_r, func(ctx *godebug.Context) {
%s
})
for recoverChan := range recovers {
recoverChan <- recover()
}
if panicVal, ok := <-panicChan; ok {
panic(panicVal)
}
{{return %s}}`, outputDecls, body.List, outputs)
body.Rbrace = token.NoPos // without this I was getting extra whitespace at the end of the function
return wrapped
}
示例3: labels
// labels checks correct label use in body.
func (check *Checker) labels(body *ast.BlockStmt) {
// set of all labels in this body
all := NewScope(nil, body.Pos(), body.End(), "label")
fwdJumps := check.blockBranches(all, nil, nil, body.List)
// If there are any forward jumps left, no label was found for
// the corresponding goto statements. Either those labels were
// never defined, or they are inside blocks and not reachable
// for the respective gotos.
for _, jmp := range fwdJumps {
var msg string
name := jmp.Label.Name
if alt := all.Lookup(name); alt != nil {
msg = "goto %s jumps into block"
alt.(*Label).used = true // avoid another error
} else {
msg = "label %s not declared"
}
check.errorf(jmp.Label.Pos(), msg, name)
}
// spec: "It is illegal to define a label that is never used."
for _, obj := range all.elems {
if lbl := obj.(*Label); !lbl.used {
check.softErrorf(lbl.pos, "label %s declared but not used", lbl.name)
}
}
}
示例4: parseBlock
func (p *parser) parseBlock(n *parse.Node, scope *ast.Scope) *ast.BlockStmt {
block := ast.BlockStmt{
Lbrace: token.Pos(n.Child(0).Pos()),
Rbrace: token.Pos(n.LastChild().Pos()),
}
eachListItem(stmt, n.Child(1), func(item *parse.Node) {
block.List = append(block.List, p.parseStmt(item))
})
return &block
}
示例5: createBlockMetadata
func (c *compiler) createBlockMetadata(stmt *ast.BlockStmt) llvm.DebugDescriptor {
uniqueId++
file := c.fileset.File(stmt.Pos())
fd := llvm.FileDescriptor(file.Name())
return &llvm.BlockDescriptor{
File: &fd,
Line: uint32(file.Line(stmt.Pos())),
Context: c.currentDebugContext(),
Id: uniqueId,
}
}
示例6: block
// block prints an *ast.BlockStmt; it always spans at least two lines.
func (p *printer) block(s *ast.BlockStmt, indent int, moveComments bool) {
if moveComments {
p.print(p.beforeComment(s.Pos()))
} else {
p.print(s.Pos())
}
p.print(token.LBRACE)
p.stmtList(s.List, indent)
p.linebreak(s.Rbrace.Line, 1, maxStmtNewlines, ignore, true)
p.print(s.Rbrace, token.RBRACE)
}
示例7: lastComment
// lastComment returns the last comment inside the provided block.
func lastComment(b *ast.BlockStmt, c []*ast.CommentGroup) (i int, last *ast.CommentGroup) {
pos, end := b.Pos(), b.End()
for j, cg := range c {
if cg.Pos() < pos {
continue
}
if cg.End() > end {
break
}
i, last = j, cg
}
return
}
示例8: finalizeLoop
func (v *visitor) finalizeLoop(pos token.Pos, body *ast.BlockStmt) {
if body == nil {
return
}
line := pos2line(pos)
if len(v.newIdents) == 0 {
call := newCall(idents.godebug, "Line", ast.NewIdent(idents.ctx), ast.NewIdent(v.scopeVar), newInt(line))
body.List = append(body.List, &ast.ExprStmt{X: call})
} else {
body.List = append([]ast.Stmt{
astPrintf(`godebug.Line(ctx, scope, %s)`, strconv.Itoa(line))[0],
newDeclareCall(idents.scope, v.newIdents),
}, body.List...)
}
}
示例9: trimBlock
func (lp *linePrinter) trimBlock(stmt *ast.BlockStmt) *ast.BlockStmt {
if !lp.trim(stmt) {
return lp.emptyBlock(stmt)
}
stmt.Rbrace = stmt.Lbrace
return stmt
}
示例10: New
// New returns a new control-flow graph for the specified function body,
// which must be non-nil.
//
// The CFG builder calls mayReturn to determine whether a given function
// call may return. For example, calls to panic, os.Exit, and log.Fatal
// do not return, so the builder can remove infeasible graph edges
// following such calls. The builder calls mayReturn only for a
// CallExpr beneath an ExprStmt.
func New(body *ast.BlockStmt, mayReturn func(*ast.CallExpr) bool) *CFG {
b := builder{
mayReturn: mayReturn,
cfg: new(CFG),
}
b.current = b.newBlock("entry")
b.stmt(body)
// Does control fall off the end of the function's body?
// Make implicit return explicit.
if b.current != nil && !b.current.unreachable {
b.add(&ast.ReturnStmt{
Return: body.End() - 1,
})
}
return b.cfg
}
示例11: funcBody
func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body *ast.BlockStmt) {
if trace {
if name == "" {
name = "<function literal>"
}
fmt.Printf("--- %s: %s {\n", name, sig)
defer fmt.Println("--- <end>")
}
// set function scope extent
sig.scope.pos = body.Pos()
sig.scope.end = body.End()
// save/restore current context and setup function context
// (and use 0 indentation at function start)
defer func(ctxt context, indent int) {
check.context = ctxt
check.indent = indent
}(check.context, check.indent)
check.context = context{
decl: decl,
scope: sig.scope,
sig: sig,
}
check.indent = 0
check.stmtList(0, body.List)
if check.hasLabel {
check.labels(body)
}
if sig.results.Len() > 0 && !check.isTerminating(body, "") {
check.error(body.Rbrace, "missing return")
}
// spec: "Implementation restriction: A compiler may make it illegal to
// declare a variable inside a function body if the variable is never used."
// (One could check each scope after use, but that distributes this check
// over several places because CloseScope is not always called explicitly.)
check.usage(sig.scope)
}
示例12: filterBlock
// filterBlocks keeps the statements that are need to calculate MappedCells.
func filterBlock(blk *ast.BlockStmt, filterIDs map[string]bool,
imports map[string]string) (*ast.BlockStmt, []dictKey) {
dicts := dictionaries(blk, imports)
usedDks := make(map[dictKey]bool)
filtered := make([]ast.Stmt, 0, len(blk.List))
for i := len(blk.List) - 1; i >= 0; i-- {
switch s := blk.List[i].(type) {
// TODO(soheil): Support switches.
case *ast.SwitchStmt:
// TODO(soheil): Add support for ifs.
case *ast.IfStmt:
default:
// TODO(soheil): It's actually more complicated that. What about
// functional calls, what about multiple return values, ...?
dks, yes := accessesDict(s, dicts)
if yes {
for _, dk := range dks {
filterIDs[dk.k] = true
usedDks[dk] = true
}
continue
}
dirty := false
rIDs, wIDs := ids(s)
for _, id := range wIDs {
if filterIDs[id] {
dirty = true
break
}
}
if !dirty {
continue
}
for _, id := range rIDs {
filterIDs[id] = true
}
filtered = append([]ast.Stmt{s}, filtered...)
}
}
blk.List = filtered
keys := make([]dictKey, 0, len(usedDks))
for dk, _ := range usedDks {
keys = append(keys, dk)
}
return blk, keys
}
示例13: bodySize
// bodySize is like nodeSize but it is specialized for *ast.BlockStmt's.
func (p *printer) bodySize(b *ast.BlockStmt, maxSize int) int {
pos1 := b.Pos()
pos2 := b.Rbrace
if pos1.IsValid() && pos2.IsValid() && p.lineFor(pos1) != p.lineFor(pos2) {
// opening and closing brace are on different lines - don't make it a one-liner
return maxSize + 1
}
if len(b.List) > 5 || p.commentBefore(p.posFor(pos2)) {
// too many statements or there is a comment inside - don't make it a one-liner
return maxSize + 1
}
// otherwise, estimate body size
bodySize := 0
for i, s := range b.List {
if i > 0 {
bodySize += 2 // space for a semicolon and blank
}
bodySize += p.nodeSize(s, maxSize)
}
return bodySize
}
示例14: rewriteTestFuncAsItStatement
/*
* Given a test func named TestDoesSomethingNeat, rewrites it as
* It("does something neat", func() { __test_body_here__ }) and adds it
* to the Describe's list of statements
*/
func rewriteTestFuncAsItStatement(testFunc *ast.FuncDecl, rootNode *ast.File, describe *ast.CallExpr) {
var funcIndex int = -1
for index, child := range rootNode.Decls {
if child == testFunc {
funcIndex = index
break
}
}
if funcIndex < 0 {
panic(fmt.Sprintf("Assert failed: Error finding index for test node %s\n", testFunc.Name.Name))
}
var block *ast.BlockStmt = blockStatementFromDescribe(describe)
block.List = append(block.List, createItStatementForTestFunc(testFunc))
replaceTestingTsWithGinkgoT(block, namedTestingTArg(testFunc))
// remove the old test func from the root node's declarations
rootNode.Decls = append(rootNode.Decls[:funcIndex], rootNode.Decls[funcIndex+1:]...)
return
}
示例15: isOneLineFunc
func (p *printer) isOneLineFunc(b *ast.BlockStmt, headerSize int) bool {
pos1 := b.Pos()
pos2 := b.Rbrace
if pos1.IsValid() && pos2.IsValid() && pos1.Line != pos2.Line {
// opening and closing brace are on different lines - don't make it a one-liner
return false
}
if len(b.List) > 5 || p.commentBefore(pos2) {
// too many statements or there is a comment inside - don't make it a one-liner
return false
}
// otherwise, estimate body size
const maxSize = 100
bodySize := 0
for i, s := range b.List {
if i > 0 {
bodySize += 2 // space for a semicolon and blank
}
bodySize += p.nodeSize(s, maxSize)
}
return headerSize+bodySize <= maxSize
}