Debian Codegraph @

syntax/parse_test.go

raw
1 // Copyright 2017 The Bazel 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 syntax_test
6
7 import (
8 "bufio"
9 "bytes"
10 "fmt"
11 "go/ast"
12 "go/build"
13 "go/parser"
14 "go/token"
15 "os"
16 "path/filepath"
17 "reflect"
18 "slices"
19 "strings"
20 "testing"
21
22 "go.starlark.net/internal/chunkedfile"
23 "go.starlark.net/starlarktest"
24 "go.starlark.net/syntax"
25 )
26
27 func TestExprParseTrees(t *testing.T) {
28 for _, test := range []struct {
29 input, want string
30 }{
31 {`print(1)`,
32 `(CallExpr Fn=print Args=(1))`},
33 {"print(1)\n",
34 `(CallExpr Fn=print Args=(1))`},
35 {`x + 1`,
36 `(BinaryExpr X=x Op=+ Y=1)`},
37 {`[x for x in y]`,
38 `(Comprehension Body=x Clauses=((ForClause Vars=x X=y)))`},
39 {`[x for x in (a if b else c)]`,
40 `(Comprehension Body=x Clauses=((ForClause Vars=x X=(ParenExpr X=(CondExpr Cond=b True=a False=c)))))`},
41 {`x[i].f(42)`,
42 `(CallExpr Fn=(DotExpr X=(IndexExpr X=x Y=i) Name=f) Args=(42))`},
43 {`x.f()`,
44 `(CallExpr Fn=(DotExpr X=x Name=f))`},
45 {`x+y*z`,
46 `(BinaryExpr X=x Op=+ Y=(BinaryExpr X=y Op=* Y=z))`},
47 {`x%y-z`,
48 `(BinaryExpr X=(BinaryExpr X=x Op=% Y=y) Op=- Y=z)`},
49 {`a + b not in c`,
50 `(BinaryExpr X=(BinaryExpr X=a Op=+ Y=b) Op=not in Y=c)`},
51 {`lambda x, *args, **kwargs: None`,
52 `(LambdaExpr Params=(x (UnaryExpr Op=* X=args) (UnaryExpr Op=** X=kwargs)) Body=None)`},
53 {`{"one": 1}`,
54 `(DictExpr List=((DictEntry Key="one" Value=1)))`},
55 {`a[i]`,
56 `(IndexExpr X=a Y=i)`},
57 {`a[i:]`,
58 `(SliceExpr X=a Lo=i)`},
59 {`a[:j]`,
60 `(SliceExpr X=a Hi=j)`},
61 {`a[::]`,
62 `(SliceExpr X=a)`},
63 {`a[::k]`,
64 `(SliceExpr X=a Step=k)`},
65 {`[]`,
66 `(ListExpr)`},
67 {`[1]`,
68 `(ListExpr List=(1))`},
69 {`[1,]`,
70 `(ListExpr List=(1))`},
71 {`[1, 2]`,
72 `(ListExpr List=(1 2))`},
73 {`()`,
74 `(TupleExpr)`},
75 {`(4,)`,
76 `(ParenExpr X=(TupleExpr List=(4)))`},
77 {`(4)`,
78 `(ParenExpr X=4)`},
79 {`(4, 5)`,
80 `(ParenExpr X=(TupleExpr List=(4 5)))`},
81 {`1, 2, 3`,
82 `(TupleExpr List=(1 2 3))`},
83 {`1, 2,`,
84 `unparenthesized tuple with trailing comma`},
85 {`{}`,
86 `(DictExpr)`},
87 {`{"a": 1}`,
88 `(DictExpr List=((DictEntry Key="a" Value=1)))`},
89 {`{"a": 1,}`,
90 `(DictExpr List=((DictEntry Key="a" Value=1)))`},
91 {`{"a": 1, "b": 2}`,
92 `(DictExpr List=((DictEntry Key="a" Value=1) (DictEntry Key="b" Value=2)))`},
93 {`{x: y for (x, y) in z}`,
94 `(Comprehension Curly Body=(DictEntry Key=x Value=y) Clauses=((ForClause Vars=(ParenExpr X=(TupleExpr List=(x y))) X=z)))`},
95 {`{x: y for a in b if c}`,
96 `(Comprehension Curly Body=(DictEntry Key=x Value=y) Clauses=((ForClause Vars=a X=b) (IfClause Cond=c)))`},
97 {`-1 + +2`,
98 `(BinaryExpr X=(UnaryExpr Op=- X=1) Op=+ Y=(UnaryExpr Op=+ X=2))`},
99 {`"foo" + "bar"`,
100 `(BinaryExpr X="foo" Op=+ Y="bar")`},
101 {`-1 * 2`, // prec(unary -) > prec(binary *)
102 `(BinaryExpr X=(UnaryExpr Op=- X=1) Op=* Y=2)`},
103 {`-x[i]`, // prec(unary -) < prec(x[i])
104 `(UnaryExpr Op=- X=(IndexExpr X=x Y=i))`},
105 {`a | b & c | d`, // prec(|) < prec(&)
106 `(BinaryExpr X=(BinaryExpr X=a Op=| Y=(BinaryExpr X=b Op=& Y=c)) Op=| Y=d)`},
107 {`a or b and c or d`,
108 `(BinaryExpr X=(BinaryExpr X=a Op=or Y=(BinaryExpr X=b Op=and Y=c)) Op=or Y=d)`},
109 {`a and b or c and d`,
110 `(BinaryExpr X=(BinaryExpr X=a Op=and Y=b) Op=or Y=(BinaryExpr X=c Op=and Y=d))`},
111 {`f(1, x=y)`,
112 `(CallExpr Fn=f Args=(1 (BinaryExpr X=x Op== Y=y)))`},
113 {`f(*args, **kwargs)`,
114 `(CallExpr Fn=f Args=((UnaryExpr Op=* X=args) (UnaryExpr Op=** X=kwargs)))`},
115 {`lambda *args, *, x=1, **kwargs: 0`,
116 `(LambdaExpr Params=((UnaryExpr Op=* X=args) (UnaryExpr Op=*) (BinaryExpr X=x Op== Y=1) (UnaryExpr Op=** X=kwargs)) Body=0)`},
117 {`lambda *, a, *b: 0`,
118 `(LambdaExpr Params=((UnaryExpr Op=*) a (UnaryExpr Op=* X=b)) Body=0)`},
119 {`a if b else c`,
120 `(CondExpr Cond=b True=a False=c)`},
121 {`a and not b`,
122 `(BinaryExpr X=a Op=and Y=(UnaryExpr Op=not X=b))`},
123 {`[e for x in y if cond1 if cond2]`,
124 `(Comprehension Body=e Clauses=((ForClause Vars=x X=y) (IfClause Cond=cond1) (IfClause Cond=cond2)))`}, // github.com/google/skylark/issues/53
125 } {
126 e, err := syntax.ParseExpr("foo.star", test.input, 0)
127 var got string
128 if err != nil {
129 got = stripPos(err)
130 } else {
131 got = treeString(e)
132 }
133 if test.want != got {
134 t.Errorf("parse `%s` = %s, want %s", test.input, got, test.want)
135 }
136 }
137 }
138
139 func TestStmtParseTrees(t *testing.T) {
140 for _, test := range []struct {
141 input, want string
142 }{
143 {`print(1)`,
144 `(ExprStmt X=(CallExpr Fn=print Args=(1)))`},
145 {`return 1, 2`,
146 `(ReturnStmt Result=(TupleExpr List=(1 2)))`},
147 {`return`,
148 `(ReturnStmt)`},
149 {`for i in "abc": break`,
150 `(ForStmt Vars=i X="abc" Body=((BranchStmt Token=break)))`},
151 {`for i in "abc": continue`,
152 `(ForStmt Vars=i X="abc" Body=((BranchStmt Token=continue)))`},
153 {`for x, y in z: pass`,
154 `(ForStmt Vars=(TupleExpr List=(x y)) X=z Body=((BranchStmt Token=pass)))`},
155 {`if True: pass`,
156 `(IfStmt Cond=True True=((BranchStmt Token=pass)))`},
157 {`if True: break`,
158 `(IfStmt Cond=True True=((BranchStmt Token=break)))`},
159 {`if True: continue`,
160 `(IfStmt Cond=True True=((BranchStmt Token=continue)))`},
161 {`if True: pass
162 else:
163 pass`,
164 `(IfStmt Cond=True True=((BranchStmt Token=pass)) False=((BranchStmt Token=pass)))`},
165 {"if a: pass\nelif b: pass\nelse: pass",
166 `(IfStmt Cond=a True=((BranchStmt Token=pass)) False=((IfStmt Cond=b True=((BranchStmt Token=pass)) False=((BranchStmt Token=pass)))))`},
167 {`x, y = 1, 2`,
168 `(AssignStmt Op== LHS=(TupleExpr List=(x y)) RHS=(TupleExpr List=(1 2)))`},
169 {`x[i] = 1`,
170 `(AssignStmt Op== LHS=(IndexExpr X=x Y=i) RHS=1)`},
171 {`x.f = 1`,
172 `(AssignStmt Op== LHS=(DotExpr X=x Name=f) RHS=1)`},
173 {`(x, y) = 1`,
174 `(AssignStmt Op== LHS=(ParenExpr X=(TupleExpr List=(x y))) RHS=1)`},
175 {`load("", "a", b="c")`,
176 `(LoadStmt Module="" From=(a c) To=(a b))`},
177 {`if True: load("", "a", b="c")`, // load needn't be at toplevel
178 `(IfStmt Cond=True True=((LoadStmt Module="" From=(a c) To=(a b))))`},
179 {`def f(x, *args, **kwargs):
180 pass`,
181 `(DefStmt Name=f Params=(x (UnaryExpr Op=* X=args) (UnaryExpr Op=** X=kwargs)) Body=((BranchStmt Token=pass)))`},
182 {`def f(**kwargs, *args): pass`,
183 `(DefStmt Name=f Params=((UnaryExpr Op=** X=kwargs) (UnaryExpr Op=* X=args)) Body=((BranchStmt Token=pass)))`},
184 {`def f(a, b, c=d): pass`,
185 `(DefStmt Name=f Params=(a b (BinaryExpr X=c Op== Y=d)) Body=((BranchStmt Token=pass)))`},
186 {`def f(a, b=c, d): pass`,
187 `(DefStmt Name=f Params=(a (BinaryExpr X=b Op== Y=c) d) Body=((BranchStmt Token=pass)))`}, // TODO(adonovan): fix this
188 {`def f():
189 def g():
190 pass
191 pass
192 def h():
193 pass`,
194 `(DefStmt Name=f Body=((DefStmt Name=g Body=((BranchStmt Token=pass))) (BranchStmt Token=pass)))`},
195 {"f();g()",
196 `(ExprStmt X=(CallExpr Fn=f))`},
197 {"f();",
198 `(ExprStmt X=(CallExpr Fn=f))`},
199 {"f();g()\n",
200 `(ExprStmt X=(CallExpr Fn=f))`},
201 {"f();\n",
202 `(ExprStmt X=(CallExpr Fn=f))`},
203 } {
204 f, err := syntax.Parse("foo.star", test.input, 0)
205 if err != nil {
206 t.Errorf("parse `%s` failed: %v", test.input, stripPos(err))
207 continue
208 }
209 if got := treeString(f.Stmts[0]); test.want != got {
210 t.Errorf("parse `%s` = %s, want %s", test.input, got, test.want)
211 }
212 }
213 }
214
215 // TestFileParseTrees tests sequences of statements, and particularly
216 // handling of indentation, newlines, line continuations, and blank lines.
217 func TestFileParseTrees(t *testing.T) {
218 for _, test := range []struct {
219 input, want string
220 }{
221 {`x = 1
222 print(x)`,
223 `(AssignStmt Op== LHS=x RHS=1)
224 (ExprStmt X=(CallExpr Fn=print Args=(x)))`},
225 {"if cond:\n\tpass",
226 `(IfStmt Cond=cond True=((BranchStmt Token=pass)))`},
227 {"if cond:\n\tpass\nelse:\n\tpass",
228 `(IfStmt Cond=cond True=((BranchStmt Token=pass)) False=((BranchStmt Token=pass)))`},
229 {`def f():
230 pass
231 pass
232
233 pass`,
234 `(DefStmt Name=f Body=((BranchStmt Token=pass)))
235 (BranchStmt Token=pass)
236 (BranchStmt Token=pass)`},
237 {`pass; pass`,
238 `(BranchStmt Token=pass)
239 (BranchStmt Token=pass)`},
240 {"pass\npass",
241 `(BranchStmt Token=pass)
242 (BranchStmt Token=pass)`},
243 {"pass\n\npass",
244 `(BranchStmt Token=pass)
245 (BranchStmt Token=pass)`},
246 {`x = (1 +
247 2)`,
248 `(AssignStmt Op== LHS=x RHS=(ParenExpr X=(BinaryExpr X=1 Op=+ Y=2)))`},
249 {`x = 1 \
250 + 2`,
251 `(AssignStmt Op== LHS=x RHS=(BinaryExpr X=1 Op=+ Y=2))`},
252 } {
253 f, err := syntax.Parse("foo.star", test.input, 0)
254 if err != nil {
255 t.Errorf("parse `%s` failed: %v", test.input, stripPos(err))
256 continue
257 }
258 var buf bytes.Buffer
259 for i, stmt := range f.Stmts {
260 if i > 0 {
261 buf.WriteByte('\n')
262 }
263 writeTree(&buf, reflect.ValueOf(stmt))
264 }
265 if got := buf.String(); test.want != got {
266 t.Errorf("parse `%s` = %s, want %s", test.input, got, test.want)
267 }
268 }
269 }
270
271 // TestCompoundStmt tests handling of REPL-style compound statements.
272 func TestCompoundStmt(t *testing.T) {
273 for _, test := range []struct {
274 input, want string
275 }{
276 // blank lines
277 {"\n",
278 ``},
279 {" \n",
280 ``},
281 {"# comment\n",
282 ``},
283 // simple statement
284 {"1\n",
285 `(ExprStmt X=1)`},
286 {"print(1)\n",
287 `(ExprStmt X=(CallExpr Fn=print Args=(1)))`},
288 {"1;2;3;\n",
289 `(ExprStmt X=1)(ExprStmt X=2)(ExprStmt X=3)`},
290 {"f();g()\n",
291 `(ExprStmt X=(CallExpr Fn=f))(ExprStmt X=(CallExpr Fn=g))`},
292 {"f();\n",
293 `(ExprStmt X=(CallExpr Fn=f))`},
294 {"f(\n\n\n\n\n\n\n)\n",
295 `(ExprStmt X=(CallExpr Fn=f))`},
296 // complex statements
297 {"def f():\n pass\n\n",
298 `(DefStmt Name=f Body=((BranchStmt Token=pass)))`},
299 {"if cond:\n pass\n\n",
300 `(IfStmt Cond=cond True=((BranchStmt Token=pass)))`},
301 // Even as a 1-liner, the following blank line is required.
302 {"if cond: pass\n\n",
303 `(IfStmt Cond=cond True=((BranchStmt Token=pass)))`},
304 // github.com/google/starlark-go/issues/121
305 {"a; b; c\n",
306 `(ExprStmt X=a)(ExprStmt X=b)(ExprStmt X=c)`},
307 {"a; b c\n",
308 `invalid syntax`},
309 } {
310
311 // Fake readline input from string.
312 // The ! suffix, which would cause a parse error,
313 // tests that the parser doesn't read more than necessary.
314 sc := bufio.NewScanner(strings.NewReader(test.input + "!"))
315 readline := func() ([]byte, error) {
316 if sc.Scan() {
317 return []byte(sc.Text() + "\n"), nil
318 }
319 return nil, sc.Err()
320 }
321
322 var got string
323 f, err := syntax.ParseCompoundStmt("foo.star", readline)
324 if err != nil {
325 got = stripPos(err)
326 } else {
327 for _, stmt := range f.Stmts {
328 got += treeString(stmt)
329 }
330 }
331 if test.want != got {
332 t.Errorf("parse `%s` = %s, want %s", test.input, got, test.want)
333 }
334 }
335 }
336
337 func stripPos(err error) string {
338 s := err.Error()
339 if i := strings.Index(s, ": "); i >= 0 {
340 s = s[i+len(": "):] // strip file:line:col
341 }
342 return s
343 }
344
345 // treeString prints a syntax node as a parenthesized tree.
346 // Idents are printed as foo and Literals as "foo" or 42.
347 // Structs are printed as (type name=value ...).
348 // Only non-empty fields are shown.
349 func treeString(n syntax.Node) string {
350 var buf bytes.Buffer
351 writeTree(&buf, reflect.ValueOf(n))
352 return buf.String()
353 }
354
355 func writeTree(out *bytes.Buffer, x reflect.Value) {
356 switch x.Kind() {
357 case reflect.String, reflect.Int, reflect.Bool:
358 fmt.Fprintf(out, "%v", x.Interface())
359 case reflect.Pointer, reflect.Interface:
360 if elem := x.Elem(); elem.Kind() == 0 {
361 out.WriteString("nil")
362 } else {
363 writeTree(out, elem)
364 }
365 case reflect.Struct:
366 switch v := x.Interface().(type) {
367 case syntax.Literal:
368 switch v.Token {
369 case syntax.STRING:
370 fmt.Fprintf(out, "%q", v.Value)
371 case syntax.BYTES:
372 fmt.Fprintf(out, "b%q", v.Value)
373 case syntax.INT:
374 fmt.Fprintf(out, "%d", v.Value)
375 }
376 return
377 case syntax.Ident:
378 out.WriteString(v.Name)
379 return
380 }
381 fmt.Fprintf(out, "(%s", strings.TrimPrefix(x.Type().String(), "syntax."))
382 for i, n := 0, x.NumField(); i < n; i++ {
383 f := x.Field(i)
384 if f.Type() == reflect.TypeFor[syntax.Position]() {
385 continue // skip positions
386 }
387 name := x.Type().Field(i).Name
388 if name == "commentsRef" {
389 continue // skip comments fields
390 }
391 if f.Type() == reflect.TypeFor[syntax.Token]() {
392 fmt.Fprintf(out, " %s=%s", name, f.Interface())
393 continue
394 }
395
396 switch f.Kind() {
397 case reflect.Slice:
398 if n := f.Len(); n > 0 {
399 fmt.Fprintf(out, " %s=(", name)
400 for i := range n {
401 if i > 0 {
402 out.WriteByte(' ')
403 }
404 writeTree(out, f.Index(i))
405 }
406 out.WriteByte(')')
407 }
408 continue
409 case reflect.Pointer, reflect.Interface:
410 if f.IsNil() {
411 continue
412 }
413 case reflect.Int:
414 if f.Int() != 0 {
415 fmt.Fprintf(out, " %s=%d", name, f.Int())
416 }
417 continue
418 case reflect.Bool:
419 if f.Bool() {
420 fmt.Fprintf(out, " %s", name)
421 }
422 continue
423 }
424 fmt.Fprintf(out, " %s=", name)
425 writeTree(out, f)
426 }
427 fmt.Fprintf(out, ")")
428 default:
429 fmt.Fprintf(out, "%T", x.Interface())
430 }
431 }
432
433 func TestParseErrors(t *testing.T) {
434 filename := starlarktest.DataFile("syntax", "testdata/errors.star")
435 for _, chunk := range chunkedfile.Read(filename, t) {
436 _, err := syntax.Parse(filename, chunk.Source, 0)
437 switch err := err.(type) {
438 case nil:
439 // ok
440 case syntax.Error:
441 chunk.GotError(int(err.Pos.Line), err.Msg)
442 default:
443 t.Error(err)
444 }
445 chunk.Done()
446 }
447 }
448
449 func TestFilePortion(t *testing.T) {
450 // Imagine that the Starlark file or expression print(x.f) is extracted
451 // from the middle of a file in some hypothetical template language;
452 // see https://github.com/google/starlark-go/issues/346. For example:
453 // --
454 // {{loop x seq}}
455 // {{print(x.f)}}
456 // {{end}}
457 // --
458 fp := syntax.FilePortion{Content: []byte("print(x.f)"), FirstLine: 2, FirstCol: 4}
459 file, err := syntax.Parse("foo.template", fp, 0)
460 if err != nil {
461 t.Fatal(err)
462 }
463 span := fmt.Sprint(file.Stmts[0].Span())
464 want := "foo.template:2:4 foo.template:2:14"
465 if span != want {
466 t.Errorf("wrong span: got %q, want %q", span, want)
467 }
468 }
469
470 func TestDepthLimit(t *testing.T) {
471 // Rather than exceed the stack during parsing, deeply nested
472 // expressions and statements are rejected by the recursion
473 // counters in the scanner and/or parser.
474 for _, src := range []string{
475 strings.Repeat("(", 1e7), // (rejected in scanner)
476 strings.Repeat("not ", 1e7) + "0",
477 strings.Repeat("-", 1e7) + "0",
478 strings.Repeat("0 if a else ", 1e7) + "0",
479 strings.Repeat("lambda: ", 1e7) + "0",
480 } {
481 t.Run("", func(t *testing.T) {
482 t.Logf("%.65s...", src)
483 _, err := syntax.Parse("limit.star", src, 0)
484 if err == nil {
485 t.Errorf("Parse succeeded unexpectedly")
486 } else if !strings.Contains(err.Error(), "excessive nesting") {
487 t.Errorf("got error %q, want excessive nesting error", err)
488 }
489 })
490 }
491 }
492
493 // dataFile is the same as starlarktest.DataFile.
494 // We make a copy to avoid a dependency cycle.
495 var dataFile = func(pkgdir, filename string) string {
496 return filepath.Join(build.Default.GOPATH, "src/go.starlark.net", pkgdir, filename)
497 }
498
499 func BenchmarkParse(b *testing.B) {
500 filename := dataFile("syntax", "testdata/scan.star")
501 b.StopTimer()
502 data, err := os.ReadFile(filename)
503 if err != nil {
504 b.Fatal(err)
505 }
506 b.StartTimer()
507
508 for i := 0; i < b.N; i++ {
509 _, err := syntax.Parse(filename, data, 0)
510 if err != nil {
511 b.Fatal(err)
512 }
513 }
514 }
515
516 // TestParserCallGraphCycles extracts a static call graph from every
517 // function in parse.go then reports any cyclic path starting from
518 // ParseFile that does not pass through a function that uses the
519 // enter/leave mechanism to break cycles.
520 func TestParserCallGraphCycles(t *testing.T) {
521 fset := token.NewFileSet()
522 file, err := parser.ParseFile(fset, "parse.go", nil, 0)
523 if err != nil {
524 t.Fatal(err)
525 }
526
527 // function is a node in static call graph.
528 type function struct {
529 name string
530 callees map[*function]bool
531 cyclebreaking bool
532 }
533 functions := make(map[string]*function)
534 node := func(name string) *function {
535 fn, ok := functions[name]
536 if !ok {
537 fn = &function{
538 name: name,
539 callees: make(map[*function]bool),
540 }
541 t.Logf("node %q", name)
542 functions[name] = fn
543 }
544 return fn
545 }
546 addEdge := func(caller, callee *function) {
547 pre := len(caller.callees)
548 caller.callees[callee] = true
549 if len(caller.callees) > pre {
550 t.Logf("edge %q -> %q", caller.name, callee.name)
551 }
552 }
553
554 // Extract the functions and the static calls between them.
555 var current *function // (nil if uninteresting)
556 ast.Inspect(file, func(n ast.Node) bool {
557 switch n := n.(type) {
558 case *ast.FuncDecl:
559 // decl of function or parser method
560 current = nil
561 name := n.Name.Name
562 if n.Recv != nil && len(n.Recv.List) > 0 {
563 if star, ok := n.Recv.List[0].Type.(*ast.StarExpr); ok {
564 if id, ok := star.X.(*ast.Ident); ok && id.Name == "parser" {
565 current = node("parser." + name)
566 }
567 }
568 } else {
569 current = node(name)
570 }
571
572 case *ast.CallExpr:
573 if current != nil {
574 // call within function of interest
575 switch fun := n.Fun.(type) {
576 case *ast.SelectorExpr:
577 // method call
578 // Assume p.method() is a method of parser.
579 // Ignore all other methods.
580 if id, ok := fun.X.(*ast.Ident); ok && id.Name == "p" {
581 callee := node("parser." + fun.Sel.Name)
582
583 // A call to p.enter indicates a cycle-breaking function.
584 if callee.name == "parser.enter" {
585 current.cyclebreaking = true
586 }
587
588 addEdge(current, callee)
589 }
590
591 case *ast.Ident:
592 // function call
593 // (incl. junk like: int, len, append, panic)
594 addEdge(current, node(fun.Name))
595 }
596 }
597 }
598 return true
599 })
600
601 // Check that no node belongs to an unbroken cycle.
602 // by doing a DFS rooted at each node in turn.
603 // (We cannot check once for the whole graph as a
604 // cycle may be reached through a cycle-breaking
605 // node, but that is not sufficient.)
606 for _, f := range functions {
607 color := make(map[*function]int) // 0=new, 1=on stack, 2=done
608 var stack []*function
609 var visit func(*function)
610 visit = func(f *function) {
611 switch color[f] {
612 case 0:
613 color[f] = 1
614 if !f.cyclebreaking {
615 stack = append(stack, f) // push
616 for callee := range f.callees {
617 visit(callee)
618 }
619 stack = stack[:len(stack)-1] // pop
620 }
621 color[f] = 2
622 case 1:
623 t.Errorf("cycle: %v", f.name)
624 for _, caller := range slices.Backward(stack) {
625 t.Logf("- %v", caller.name)
626 }
627 }
628 }
629 visit(f)
630 }
631
632 }