Debian Codegraph @

cmd/digraph/digraph.go

raw symbols SCIP
1 // Copyright 2019 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 main // import "golang.org/x/tools/cmd/digraph"
6
7 // TODO(adonovan):
8 // - support input files other than stdin
9 // - support alternative formats (AT&T GraphViz, CSV, etc),
10 // a comment syntax, etc.
11 // - allow queries to nest, like Blaze query language.
12
13 import (
14 "bufio"
15 "bytes"
16 _ "embed"
17 "errors"
18 "flag"
19 "fmt"
20 "io"
21 "iter"
22 "maps"
23 "os"
24 "slices"
25 "sort"
26 "strconv"
27 "strings"
28 "unicode"
29 "unicode/utf8"
30
31 "golang.org/x/tools/internal/graph"
32 "golang.org/x/tools/internal/graph/graphfmt"
33 )
34
35 func usage() {
36 // Extract the content of the /* ... */ comment in doc.go.
37 _, after, _ := strings.Cut(doc, "/*")
38 doc, _, _ := strings.Cut(after, "*/")
39 io.WriteString(flag.CommandLine.Output(), doc)
40 flag.PrintDefaults()
41
42 os.Exit(2)
43 }
44
45 //go:embed doc.go
46 var doc string
47
48 func main() {
49 flag.Usage = usage
50 flag.Parse()
51
52 args := flag.Args()
53 if len(args) == 0 {
54 usage()
55 }
56
57 if err := doDigraph(args[0], args[1:]); err != nil {
58 fmt.Fprintf(os.Stderr, "digraph: %s\n", err)
59 os.Exit(1)
60 }
61 }
62
63 type nodelist []string
64
65 func (l nodelist) println(sep string) {
66 for i, node := range l {
67 if i > 0 {
68 fmt.Fprint(stdout, sep)
69 }
70 fmt.Fprint(stdout, node)
71 }
72 fmt.Fprintln(stdout)
73 }
74
75 type nodeset map[string]bool
76
77 func (s nodeset) sort() nodelist {
78 nodes := make(nodelist, len(s))
79 var i int
80 for node := range s {
81 nodes[i] = node
82 i++
83 }
84 sort.Strings(nodes)
85 return nodes
86 }
87
88 // A digraph maps nodes to the non-nil set of their immediate successors.
89 type digraph map[string]nodeset
90
91 func (g digraph) Nodes() iter.Seq[string] {
92 return slices.Values(slices.Sorted(maps.Keys(g)))
93 }
94
95 func (g digraph) NumNodes() int {
96 return len(g)
97 }
98
99 func (g digraph) Out(node string) iter.Seq[string] {
100 // Out must be deterministic.
101 return slices.Values(slices.Sorted(maps.Keys(g[node])))
102 }
103
104 var _ graph.Graph[string] = digraph{}
105
106 func (g digraph) addNode(node string) nodeset {
107 edges := g[node]
108 if edges == nil {
109 edges = make(nodeset)
110 g[node] = edges
111 }
112 return edges
113 }
114
115 func (g digraph) addEdges(from string, to ...string) {
116 edges := g.addNode(from)
117 for _, to := range to {
118 g.addNode(to)
119 edges[to] = true
120 }
121 }
122
123 func (g digraph) nodelist() nodelist {
124 return nodelist(slices.Collect(g.Nodes()))
125 }
126
127 func (g digraph) sccs() []nodeset {
128 var sccs []nodeset
129 for _, comp := range graph.SCCs(g) {
130 scc := make(nodeset)
131 for _, node := range comp {
132 scc[node] = true
133 }
134 if len(scc) == 1 && !g[comp[0]][comp[0]] {
135 continue // trivial SCC without even a self-edge
136 }
137 sccs = append(sccs, scc)
138 }
139 return sccs
140 }
141
142 func (g digraph) allpaths(from, to string) error {
143 seen := graph.AllPaths(g, from, to)
144
145 // For each marked node, collect its marked successors.
146 var edges []string
147 for n := range seen {
148 for succ := range g[n] {
149 if seen[succ] {
150 edges = append(edges, n+" "+succ)
151 }
152 }
153 }
154
155 // Sort (so that this method is deterministic) and print edges.
156 sort.Strings(edges)
157 for _, e := range edges {
158 fmt.Fprintln(stdout, e)
159 }
160
161 return nil
162 }
163
164 func (g digraph) somepath(from, to string) error {
165 path := graph.ShortestPath(g, from, to)
166 if path == nil {
167 return fmt.Errorf("no path from %q to %q", from, to)
168 }
169 for i := 0; i < len(path)-1; i++ {
170 fmt.Fprintln(stdout, path[i]+" "+path[i+1])
171 }
172 return nil
173 }
174
175 func parse(rd io.Reader) (digraph, error) {
176 g := make(digraph)
177
178 var linenum int
179 // We avoid bufio.Scanner as it imposes a (configurable) limit
180 // on line length, whereas Reader.ReadString does not.
181 in := bufio.NewReader(rd)
182 for {
183 linenum++
184 line, err := in.ReadString('\n')
185 eof := false
186 if err == io.EOF {
187 eof = true
188 } else if err != nil {
189 return nil, err
190 }
191 // Split into words, honoring double-quotes per Go spec.
192 words, err := split(line)
193 if err != nil {
194 return nil, fmt.Errorf("at line %d: %v", linenum, err)
195 }
196 if len(words) > 0 {
197 g.addEdges(words[0], words[1:]...)
198 }
199 if eof {
200 break
201 }
202 }
203 return g, nil
204 }
205
206 // Overridable for redirection.
207 var stdin io.Reader = os.Stdin
208 var stdout io.Writer = os.Stdout
209
210 func doDigraph(cmd string, args []string) error {
211 // Parse the input graph.
212 g, err := parse(stdin)
213 if err != nil {
214 return err
215 }
216
217 // Parse the command line.
218 switch cmd {
219 case "nodes":
220 if len(args) != 0 {
221 return fmt.Errorf("usage: digraph nodes")
222 }
223 g.nodelist().println("\n")
224
225 case "degree":
226 if len(args) != 0 {
227 return fmt.Errorf("usage: digraph degree")
228 }
229 nodes := make(nodeset)
230 for node := range g {
231 nodes[node] = true
232 }
233 rev := graph.Transpose(g)
234 for _, node := range nodes.sort() {
235 inDegree := 0
236 for range rev.Out(node) {
237 inDegree++
238 }
239 fmt.Fprintf(stdout, "%d\t%d\t%s\n", inDegree, len(g[node]), node)
240 }
241
242 case "transpose":
243 if len(args) != 0 {
244 return fmt.Errorf("usage: digraph transpose")
245 }
246 var revEdges []string
247 rev := graph.Transpose(g)
248 for node := range rev.Nodes() {
249 for succ := range rev.Out(node) {
250 revEdges = append(revEdges, fmt.Sprintf("%s %s", node, succ))
251 }
252 }
253 sort.Strings(revEdges) // make output deterministic
254 for _, e := range revEdges {
255 fmt.Fprintln(stdout, e)
256 }
257
258 case "succs", "preds":
259 if len(args) == 0 {
260 return fmt.Errorf("usage: digraph %s <node> ... ", cmd)
261 }
262 var gr graph.Graph[string] = g
263 if cmd == "preds" {
264 gr = graph.Transpose(g)
265 }
266 result := make(nodeset)
267 for _, root := range args {
268 if g[root] == nil {
269 return fmt.Errorf("no such node %q", root)
270 }
271 for succ := range gr.Out(root) {
272 result[succ] = true
273 }
274 }
275 result.sort().println("\n")
276
277 case "forward", "reverse":
278 if len(args) == 0 {
279 return fmt.Errorf("usage: digraph %s <node> ... ", cmd)
280 }
281 roots := make(nodeset)
282 for _, root := range args {
283 if g[root] == nil {
284 return fmt.Errorf("no such node %q", root)
285 }
286 roots[root] = true
287 }
288 var gr graph.Graph[string] = g
289 if cmd == "reverse" {
290 gr = graph.Transpose(g)
291 }
292 nodeset(graph.Reachable(gr, roots.sort()...)).sort().println("\n")
293
294 case "somepath":
295 if len(args) != 2 {
296 return fmt.Errorf("usage: digraph somepath <from> <to>")
297 }
298 from, to := args[0], args[1]
299 if g[from] == nil {
300 return fmt.Errorf("no such 'from' node %q", from)
301 }
302 if g[to] == nil {
303 return fmt.Errorf("no such 'to' node %q", to)
304 }
305 if err := g.somepath(from, to); err != nil {
306 return err
307 }
308
309 case "allpaths":
310 if len(args) != 2 {
311 return fmt.Errorf("usage: digraph allpaths <from> <to>")
312 }
313 from, to := args[0], args[1]
314 if g[from] == nil {
315 return fmt.Errorf("no such 'from' node %q", from)
316 }
317 if g[to] == nil {
318 return fmt.Errorf("no such 'to' node %q", to)
319 }
320 if err := g.allpaths(from, to); err != nil {
321 return err
322 }
323
324 case "sccs":
325 if len(args) != 0 {
326 return fmt.Errorf("usage: digraph sccs")
327 }
328 buf := new(bytes.Buffer)
329 oldStdout := stdout
330 stdout = buf
331 for _, scc := range g.sccs() {
332 scc.sort().println(" ")
333 }
334 lines := strings.SplitAfter(buf.String(), "\n")
335 sort.Strings(lines)
336 stdout = oldStdout
337 io.WriteString(stdout, strings.Join(lines, ""))
338
339 case "scc":
340 if len(args) != 1 {
341 return fmt.Errorf("usage: digraph scc <node>")
342 }
343 node := args[0]
344 if g[node] == nil {
345 return fmt.Errorf("no such node %q", node)
346 }
347 for _, scc := range g.sccs() {
348 if scc[node] {
349 scc.sort().println("\n")
350 break
351 }
352 }
353
354 case "focus":
355 if len(args) != 1 {
356 return fmt.Errorf("usage: digraph focus <node>")
357 }
358 node := args[0]
359 if g[node] == nil {
360 return fmt.Errorf("no such node %q", node)
361 }
362
363 edges := make(map[string]struct{})
364 for from := range graph.Reachable(g, node) {
365 for to := range g[from] {
366 edges[fmt.Sprintf("%s %s", from, to)] = struct{}{}
367 }
368 }
369
370 gtrans := graph.Transpose(g)
371 for from := range graph.Reachable(gtrans, node) {
372 for to := range gtrans.Out(from) {
373 edges[fmt.Sprintf("%s %s", to, from)] = struct{}{}
374 }
375 }
376
377 edgesSorted := make([]string, 0, len(edges))
378 for e := range edges {
379 edgesSorted = append(edgesSorted, e)
380 }
381 sort.Strings(edgesSorted)
382 fmt.Fprintln(stdout, strings.Join(edgesSorted, "\n"))
383
384 case "to":
385 if len(args) != 1 || args[0] != "dot" {
386 return fmt.Errorf("usage: digraph to dot")
387 }
388 stdout.Write([]byte(graphfmt.Dot[string]{}.Sprint(g)))
389
390 default:
391 return fmt.Errorf("no such command %q", cmd)
392 }
393
394 return nil
395 }
396
397 // -- Utilities --------------------------------------------------------
398
399 // split splits a line into words, which are generally separated by
400 // spaces, but Go-style double-quoted string literals are also supported.
401 // (This approximates the behaviour of the Bourne shell.)
402 //
403 // `one "two three"` -> ["one" "two three"]
404 // `a"\n"b` -> ["a\nb"]
405 func split(line string) ([]string, error) {
406 var (
407 words []string
408 inWord bool
409 current bytes.Buffer
410 )
411
412 for len(line) > 0 {
413 r, size := utf8.DecodeRuneInString(line)
414 if unicode.IsSpace(r) {
415 if inWord {
416 words = append(words, current.String())
417 current.Reset()
418 inWord = false
419 }
420 } else if r == '"' {
421 var ok bool
422 size, ok = quotedLength(line)
423 if !ok {
424 return nil, errors.New("invalid quotation")
425 }
426 s, err := strconv.Unquote(line[:size])
427 if err != nil {
428 return nil, err
429 }
430 current.WriteString(s)
431 inWord = true
432 } else {
433 current.WriteRune(r)
434 inWord = true
435 }
436 line = line[size:]
437 }
438 if inWord {
439 words = append(words, current.String())
440 }
441 return words, nil
442 }
443
444 // quotedLength returns the length in bytes of the prefix of input that
445 // contain a possibly-valid double-quoted Go string literal.
446 //
447 // On success, n is at least two (""); input[:n] may be passed to
448 // strconv.Unquote to interpret its value, and input[n:] contains the
449 // rest of the input.
450 //
451 // On failure, quotedLength returns false, and the entire input can be
452 // passed to strconv.Unquote if an informative error message is desired.
453 //
454 // quotedLength does not and need not detect all errors, such as
455 // invalid hex or octal escape sequences, since it assumes
456 // strconv.Unquote will be applied to the prefix. It guarantees only
457 // that if there is a prefix of input containing a valid string literal,
458 // its length is returned.
459 //
460 // TODO(adonovan): move this into a strconv-like utility package.
461 func quotedLength(input string) (n int, ok bool) {
462 var offset int
463
464 // next returns the rune at offset, or -1 on EOF.
465 // offset advances to just after that rune.
466 next := func() rune {
467 if offset < len(input) {
468 r, size := utf8.DecodeRuneInString(input[offset:])
469 offset += size
470 return r
471 }
472 return -1
473 }
474
475 if next() != '"' {
476 return // error: not a quotation
477 }
478
479 for {
480 r := next()
481 if r == '\n' || r < 0 {
482 return // error: string literal not terminated
483 }
484 if r == '"' {
485 return offset, true // success
486 }
487 if r == '\\' {
488 var skip int
489 switch next() {
490 case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"':
491 skip = 0
492 case '0', '1', '2', '3', '4', '5', '6', '7':
493 skip = 2
494 case 'x':
495 skip = 2
496 case 'u':
497 skip = 4
498 case 'U':
499 skip = 8
500 default:
501 return // error: invalid escape
502 }
503
504 for i := 0; i < skip; i++ {
505 next()
506 }
507 }
508 }
509 }