本文整理汇总了Golang中go/ast.Stmt类的典型用法代码示例。如果您正苦于以下问题:Golang Stmt类的具体用法?Golang Stmt怎么用?Golang Stmt使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Stmt类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: insertInWithin
// insertInWithin places before/after advice around a statement
func (wb *WithinBlock) insertInWithin(a ast.Stmt, w *Weave) string {
rout := ""
mName := grabMethodName(a)
// begin line
begin := wb.fset.Position(a.Pos()).Line - 1
after := wb.fset.Position(a.End()).Line + 1
// until this is refactored - any lines we add in our
// advice need to be accounted for w/begin
before_advice := formatAdvice(wb.aspect.advize.before, mName)
after_advice := formatAdvice(wb.aspect.advize.after, mName)
if before_advice != "" {
rout = w.writeAtLine(wb.fname, begin+wb.linecnt, before_advice)
wb.linecnt += strings.Count(before_advice, "\n") + 1
}
if after_advice != "" {
rout = w.writeAtLine(wb.fname, after+wb.linecnt-1, after_advice)
wb.linecnt += strings.Count(after_advice, "\n") + 1
}
for t := 0; t < len(wb.aspect.importz); t++ {
wb.importsNeeded = append(wb.importsNeeded, wb.aspect.importz[t])
}
return rout
}
示例2: VisitStmt
func (c *compiler) VisitStmt(stmt ast.Stmt) {
if c.logger != nil {
c.logger.Println("Compile statement:", reflect.TypeOf(stmt),
"@", c.fileset.Position(stmt.Pos()))
}
switch x := stmt.(type) {
case *ast.ReturnStmt:
c.VisitReturnStmt(x)
case *ast.AssignStmt:
c.VisitAssignStmt(x)
case *ast.IncDecStmt:
c.VisitIncDecStmt(x)
case *ast.IfStmt:
c.VisitIfStmt(x)
case *ast.ForStmt:
c.VisitForStmt(x)
case *ast.ExprStmt:
c.VisitExpr(x.X)
case *ast.BlockStmt:
c.VisitBlockStmt(x)
case *ast.DeclStmt:
c.VisitDecl(x.Decl)
case *ast.GoStmt:
c.VisitGoStmt(x)
case *ast.SwitchStmt:
c.VisitSwitchStmt(x)
default:
panic(fmt.Sprintf("Unhandled Stmt node: %s", reflect.TypeOf(stmt)))
}
}
示例3: statementBoundary
// statementBoundary finds the location in s that terminates the current basic
// block in the source.
func (f *File) statementBoundary(s ast.Stmt) token.Pos {
// Control flow statements are easy.
switch s := s.(type) {
case *ast.BlockStmt:
// Treat blocks like basic blocks to avoid overlapping counters.
return s.Lbrace
case *ast.IfStmt:
return s.Body.Lbrace
case *ast.ForStmt:
return s.Body.Lbrace
case *ast.LabeledStmt:
return f.statementBoundary(s.Stmt)
case *ast.RangeStmt:
return s.Body.Lbrace
case *ast.SwitchStmt:
return s.Body.Lbrace
case *ast.SelectStmt:
return s.Body.Lbrace
case *ast.TypeSwitchStmt:
return s.Body.Lbrace
}
// If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal.
// If it does, that's tricky because we want to exclude the body of the function from this block.
// Draw a line at the start of the body of the first function literal we find.
// TODO: what if there's more than one? Probably doesn't matter much.
var literal funcLitFinder
ast.Walk(&literal, s)
if literal.found() {
return token.Pos(literal)
}
return s.End()
}
示例4: emitTraceStmt
func emitTraceStmt(f *Function, event TraceEvent, syntax ast.Stmt) Value {
t := &Trace{
Event: event,
Start: syntax.Pos(),
End: syntax.End(),
Breakpoint: false,
syntax: syntax,
}
return emitTraceCommon(f, t)
}
示例5: makeExpr
func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
if s == nil {
return nil
}
if es, isExpr := s.(*ast.ExprStmt); isExpr {
return p.checkExpr(es.X)
}
p.Error(s.Pos(), "expected condition, found simple statement")
return &ast.BadExpr{s.Pos()}
}
示例6: VisitStmt
func (v *ShortError) VisitStmt(scope *ast.Scope, stmt ast.Stmt) ScopeVisitor {
v.stmt = stmt
switch stmt := stmt.(type) {
case *ast.BlockStmt:
return &ShortError{v.file, v.patches, v.stmt, stmt, 0, new([]byte)}
case *ast.ExprStmt:
if call := calltomust(stmt.X); call != nil {
// TODO(elazarl): depends on number of variables it returns, currently we assume one
pos := v.file.Fset.Position(stmt.Pos())
fmt.Printf("%s:%d:%d: 'must' builtin must be assigned into variable\n",
pos.Filename, pos.Line, pos.Column)
}
case *ast.AssignStmt:
if len(stmt.Rhs) != 1 {
return v
}
if rhs, ok := stmt.Rhs[0].(*ast.CallExpr); ok {
if fun, ok := rhs.Fun.(*ast.Ident); ok && fun.Name == MustKeyword {
if stmt.Tok == token.DEFINE {
tmpVar := v.tempVar("assignerr_", scope)
*v.patches = append(*v.patches,
patch.Insert(stmt.TokPos, ", "+tmpVar+" "),
patch.Replace(fun, ""),
patch.Insert(stmt.End(),
"; if "+tmpVar+" != nil "+
"{ panic("+tmpVar+") };"),
)
for _, arg := range rhs.Args {
v.VisitExpr(scope, arg)
}
return nil
} else if stmt.Tok == token.ASSIGN {
vars := []string{}
for i := 0; i < len(stmt.Lhs); i++ {
vars = append(vars, v.tempVar(fmt.Sprint("assgn", i, "_"), scope))
}
assgnerr := v.tempVar("assgnErr_", scope)
*v.patches = append(*v.patches,
patch.Insert(stmt.Pos(),
strings.Join(append(vars, assgnerr), ", ")+":="),
patch.InsertNode(stmt.Pos(), rhs.Args[0]),
patch.Insert(stmt.Pos(),
"; if "+assgnerr+" != nil "+
"{ panic("+assgnerr+") };"),
patch.Replace(rhs, strings.Join(vars, ", ")),
)
v.VisitExpr(scope, rhs.Args[0])
return nil
}
}
}
}
return v
}
示例7: wrapLoop
func (v *visitor) wrapLoop(node ast.Stmt, body *ast.BlockStmt) (block *ast.BlockStmt, loop ast.Stmt) {
block = astPrintf(`
{
scope := %s.EnteringNewChildScope()
_ = scope // placeholder
godebug.Line(ctx, scope, %s)
}`, v.scopeVar, pos2lineString(node.Pos()))[0].(*ast.BlockStmt)
block.List[1] = node
loop = node
return
}
示例8: validStmt
func (f *File) validStmt(stmt ast.Stmt) *Error {
if stmt == nil {
return nil
}
if assign, ok := stmt.(*ast.AssignStmt); ok {
if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
return &Error{errors.New("Invalid assigment statment"), assign.Pos()}
}
return nil
}
if ifstmt, ok := stmt.(*ast.IfStmt); ok {
if err := f.validExpr(ifstmt.Cond); err != nil {
return err
}
// initialization clause not allowed for if statements
if ifstmt.Init != nil {
return &Error{errors.New("ifstmt cannot have initialization clause"), ifstmt.Init.Pos()}
}
if err := f.validStmt(ifstmt.Body); err != nil {
return err
}
if err := f.validStmt(ifstmt.Else); err != nil {
return err
}
}
if blk, ok := stmt.(*ast.BlockStmt); ok {
for _, s := range blk.List {
if err := f.validStmt(s); err != nil {
return err
}
}
}
if _, ok := stmt.(*ast.EmptyStmt); ok {
return nil
}
if ret, ok := stmt.(*ast.ReturnStmt); ok {
if ret.Results == nil || len(ret.Results) == 0 {
return nil
}
if len(ret.Results) > 1 {
return &Error{errors.New("Return statement doesn't allow multiple return values"), ret.Pos()}
}
return f.validRetExpr(ret.Results[0])
}
if indec, ok := stmt.(*ast.IncDecStmt); ok {
// TODO specialize
if err := f.validExpr(indec.X); err != nil {
return err
}
}
return &Error{errors.New(fmt.Sprintf("Invalid stmt:%v", stmt)), stmt.Pos()}
}
示例9: generateCheckedAssign
func generateCheckedAssign(stmt ast.Stmt, place ast.Expr) ast.Stmt {
pos := stmt.Pos()
return &ast.IfStmt{
If: pos,
Init: stmt,
Cond: &ast.BinaryExpr{
X: place,
OpPos: pos,
Op: token.NEQ,
Y: ast.NewIdent("nil")},
Body: &ast.BlockStmt{
Lbrace: pos,
List: []ast.Stmt{&ast.ReturnStmt{}},
Rbrace: pos},
}
}
示例10: multipleDefaults
func (check *checker) multipleDefaults(list []ast.Stmt) {
var first ast.Stmt
for _, s := range list {
var d ast.Stmt
switch c := s.(type) {
case *ast.CaseClause:
if len(c.List) == 0 {
d = s
}
case *ast.CommClause:
if c.Comm == nil {
d = s
}
default:
check.invalidAST(s.Pos(), "case/communication clause expected")
}
if d != nil {
if first != nil {
check.errorf(d.Pos(), "multiple defaults (first at %s)", first.Pos())
} else {
first = d
}
}
}
}
示例11: rewriteRecvStmt
func (t *rewriteVisitor) rewriteRecvStmt(stmt ast.Stmt) []ast.Stmt {
// Prohibit inner blocks from having channel operation nodes
switch q := stmt.(type) {
case *ast.AssignStmt:
for _, expr := range q.Lhs {
// TODO: Handle channel operations inside LHS of assignments
RecurseProhibit(t, expr)
}
for _, expr := range q.Rhs {
if expr == nil {
continue
}
// TODO: Handle channel operations inside RHS of assignments
if ue := filterRecvExpr(expr); ue != nil {
RecurseProhibit(t, ue.X)
} else {
RecurseProhibit(t, expr)
}
}
case *ast.ExprStmt:
if q == nil {
break
}
// TODO: Handle channel operations inside RHS of assignments
if ue := filterRecvExpr(q.X); ue != nil {
RecurseProhibit(t, ue.X)
} else {
RecurseProhibit(t, q)
}
default:
panic("unreach")
}
// Rewrite receive statement itself
return []ast.Stmt{
makeSimpleCallStmt("vtime", "Block", stmt.Pos()),
stmt,
makeSimpleCallStmt("vtime", "Unblock", stmt.Pos()),
}
}
示例12: compileStmt
// compiles a statement
func (w *World) compileStmt(st ast.Stmt) Expr {
switch st := st.(type) {
default:
panic(err(st.Pos(), "not allowed:", typ(st)))
case *ast.EmptyStmt:
return &emptyStmt{}
case *ast.AssignStmt:
return w.compileAssignStmt(st)
case *ast.ExprStmt:
return w.compileExpr(st.X)
case *ast.IfStmt:
return w.compileIfStmt(st)
case *ast.ForStmt:
return w.compileForStmt(st)
case *ast.IncDecStmt:
return w.compileIncDecStmt(st)
case *ast.BlockStmt:
w.EnterScope()
defer w.ExitScope()
return w.compileBlockStmt_noScope(st)
}
}
示例13: statementBoundary
// statementBoundary finds the location in s that terminates the current basic
// block in the source.
func (f *File) statementBoundary(s ast.Stmt) token.Pos {
// Control flow statements are easy.
switch s := s.(type) {
case *ast.BlockStmt:
// Treat blocks like basic blocks to avoid overlapping counters.
return s.Lbrace
case *ast.IfStmt:
return s.Body.Lbrace
case *ast.ForStmt:
return s.Body.Lbrace
case *ast.LabeledStmt:
return f.statementBoundary(s.Stmt)
case *ast.RangeStmt:
// Ranges might loop over things with function literals.: for _ = range []func(){ ... } {.
// TODO: There are a few other such possibilities, but they're extremely unlikely.
found, pos := hasFuncLiteral(s.X)
if found {
return pos
}
return s.Body.Lbrace
case *ast.SwitchStmt:
return s.Body.Lbrace
case *ast.SelectStmt:
return s.Body.Lbrace
case *ast.TypeSwitchStmt:
return s.Body.Lbrace
}
// If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal.
// If it does, that's tricky because we want to exclude the body of the function from this block.
// Draw a line at the start of the body of the first function literal we find.
// TODO: what if there's more than one? Probably doesn't matter much.
found, pos := hasFuncLiteral(s)
if found {
return pos
}
return s.End()
}
示例14: stmt
// stmt typechecks statement s.
func (check *checker) stmt(s ast.Stmt) {
switch s := s.(type) {
case *ast.BadStmt, *ast.EmptyStmt:
// ignore
case *ast.DeclStmt:
d, _ := s.Decl.(*ast.GenDecl)
if d == nil || (d.Tok != token.CONST && d.Tok != token.TYPE && d.Tok != token.VAR) {
check.invalidAST(token.NoPos, "const, type, or var declaration expected")
return
}
if d.Tok == token.CONST {
check.assocInitvals(d)
}
check.decl(d)
case *ast.LabeledStmt:
// TODO(gri) anything to do with label itself?
check.stmt(s.Stmt)
case *ast.ExprStmt:
var x operand
used := false
switch e := unparen(s.X).(type) {
case *ast.CallExpr:
// function calls are permitted
used = true
// but some builtins are excluded
// (Caution: This evaluates e.Fun twice, once here and once
// below as part of s.X. This has consequences for
// check.register. Perhaps this can be avoided.)
check.expr(&x, e.Fun, nil, -1)
if x.mode != invalid {
if b, ok := x.typ.(*builtin); ok && !b.isStatement {
used = false
}
}
case *ast.UnaryExpr:
// receive operations are permitted
if e.Op == token.ARROW {
used = true
}
}
if !used {
check.errorf(s.Pos(), "%s not used", s.X)
// ok to continue
}
check.rawExpr(&x, s.X, nil, -1, false)
if x.mode == typexpr {
check.errorf(x.pos(), "%s is not an expression", &x)
}
case *ast.SendStmt:
var ch, x operand
check.expr(&ch, s.Chan, nil, -1)
check.expr(&x, s.Value, nil, -1)
if ch.mode == invalid || x.mode == invalid {
return
}
if tch, ok := underlying(ch.typ).(*Chan); !ok || tch.Dir&ast.SEND == 0 || !check.assignment(&x, tch.Elt) {
if x.mode != invalid {
check.invalidOp(ch.pos(), "cannot send %s to channel %s", &x, &ch)
}
}
case *ast.IncDecStmt:
var op token.Token
switch s.Tok {
case token.INC:
op = token.ADD
case token.DEC:
op = token.SUB
default:
check.invalidAST(s.TokPos, "unknown inc/dec operation %s", s.Tok)
return
}
var x operand
Y := &ast.BasicLit{ValuePos: s.X.Pos(), Kind: token.INT, Value: "1"} // use x's position
check.binary(&x, s.X, Y, op, -1)
if x.mode == invalid {
return
}
check.assign1to1(s.X, nil, &x, false, -1)
case *ast.AssignStmt:
switch s.Tok {
case token.ASSIGN, token.DEFINE:
if len(s.Lhs) == 0 {
check.invalidAST(s.Pos(), "missing lhs in assignment")
return
}
check.assignNtoM(s.Lhs, s.Rhs, s.Tok == token.DEFINE, -1)
default:
// assignment operations
if len(s.Lhs) != 1 || len(s.Rhs) != 1 {
check.errorf(s.TokPos, "assignment operation %s requires single-valued expressions", s.Tok)
return
}
// TODO(gri) make this conversion more efficient
//.........这里部分代码省略.........
示例15: stmt
// stmt typechecks statement s.
func (check *checker) stmt(ctxt stmtContext, s ast.Stmt) {
// statements cannot use iota in general
// (constant declarations set it explicitly)
assert(check.iota == nil)
// statements must end with the same top scope as they started with
if debug {
defer func(scope *Scope) {
// don't check if code is panicking
if p := recover(); p != nil {
panic(p)
}
assert(scope == check.topScope)
}(check.topScope)
}
inner := ctxt &^ fallthroughOk
switch s := s.(type) {
case *ast.BadStmt, *ast.EmptyStmt:
// ignore
case *ast.DeclStmt:
check.declStmt(s.Decl)
case *ast.LabeledStmt:
check.hasLabel = true
check.stmt(ctxt, s.Stmt)
case *ast.ExprStmt:
// spec: "With the exception of specific built-in functions,
// function and method calls and receive operations can appear
// in statement context. Such statements may be parenthesized."
var x operand
kind := check.rawExpr(&x, s.X, nil)
var msg string
switch x.mode {
default:
if kind == statement {
return
}
msg = "is not used"
case builtin:
msg = "must be called"
case typexpr:
msg = "is not an expression"
}
check.errorf(x.pos(), "%s %s", &x, msg)
case *ast.SendStmt:
var ch, x operand
check.expr(&ch, s.Chan)
check.expr(&x, s.Value)
if ch.mode == invalid || x.mode == invalid {
return
}
if tch, ok := ch.typ.Underlying().(*Chan); !ok || tch.dir&ast.SEND == 0 || !check.assignment(&x, tch.elem) {
if x.mode != invalid {
check.invalidOp(ch.pos(), "cannot send %s to channel %s", &x, &ch)
}
}
case *ast.IncDecStmt:
var op token.Token
switch s.Tok {
case token.INC:
op = token.ADD
case token.DEC:
op = token.SUB
default:
check.invalidAST(s.TokPos, "unknown inc/dec operation %s", s.Tok)
return
}
var x operand
Y := &ast.BasicLit{ValuePos: s.X.Pos(), Kind: token.INT, Value: "1"} // use x's position
check.binary(&x, s.X, Y, op)
if x.mode == invalid {
return
}
check.assignVar(s.X, &x)
case *ast.AssignStmt:
switch s.Tok {
case token.ASSIGN, token.DEFINE:
if len(s.Lhs) == 0 {
check.invalidAST(s.Pos(), "missing lhs in assignment")
return
}
if s.Tok == token.DEFINE {
check.shortVarDecl(s.TokPos, s.Lhs, s.Rhs)
} else {
// regular assignment
check.assignVars(s.Lhs, s.Rhs)
}
default:
// assignment operations
if len(s.Lhs) != 1 || len(s.Rhs) != 1 {
check.errorf(s.TokPos, "assignment operation %s requires single-valued expressions", s.Tok)
return
//.........这里部分代码省略.........