Source file src/go/ast/walk_test.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package ast_test
     6  
     7  import (
     8  	"go/ast"
     9  	"go/parser"
    10  	"go/token"
    11  	"testing"
    12  )
    13  
    14  func TestPreorderBreak(t *testing.T) {
    15  	// This test checks that Preorder correctly handles a break statement while
    16  	// in the middle of walking a node. Previously, incorrect handling of the
    17  	// boolean returned by the yield function resulted in the iterator calling
    18  	// yield for sibling nodes even after yield had returned false. With that
    19  	// bug, this test failed with a runtime panic.
    20  	src := "package p\ntype T struct {\n\tF int `json:\"f\"` // a field\n}\n"
    21  
    22  	fset := token.NewFileSet()
    23  	f, err := parser.ParseFile(fset, "", src, 0)
    24  	if err != nil {
    25  		panic(err)
    26  	}
    27  
    28  	for n := range ast.Preorder(f) {
    29  		if id, ok := n.(*ast.Ident); ok && id.Name == "F" {
    30  			break
    31  		}
    32  	}
    33  }
    34  

View as plain text