blob: 6ddf29993e5287c909553bdedf3d1d63d4ce9922 [file] [log] [blame]
Matteo Scandoloabf872d2020-12-14 08:22:06 -10001// Copyright 2017, 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.md file.
4
5package cmp
6
7// defaultReporter implements the reporter interface.
8//
9// As Equal serially calls the PushStep, Report, and PopStep methods, the
10// defaultReporter constructs a tree-based representation of the compared value
11// and the result of each comparison (see valueNode).
12//
13// When the String method is called, the FormatDiff method transforms the
14// valueNode tree into a textNode tree, which is a tree-based representation
15// of the textual output (see textNode).
16//
17// Lastly, the textNode.String method produces the final report as a string.
18type defaultReporter struct {
19 root *valueNode
20 curr *valueNode
21}
22
23func (r *defaultReporter) PushStep(ps PathStep) {
24 r.curr = r.curr.PushStep(ps)
25 if r.root == nil {
26 r.root = r.curr
27 }
28}
29func (r *defaultReporter) Report(rs Result) {
30 r.curr.Report(rs)
31}
32func (r *defaultReporter) PopStep() {
33 r.curr = r.curr.PopStep()
34}
35
36// String provides a full report of the differences detected as a structured
37// literal in pseudo-Go syntax. String may only be called after the entire tree
38// has been traversed.
39func (r *defaultReporter) String() string {
40 assert(r.root != nil && r.curr == nil)
41 if r.root.NumDiff == 0 {
42 return ""
43 }
44 return formatOptions{}.FormatDiff(r.root).String()
45}
46
47func assert(ok bool) {
48 if !ok {
49 panic("assertion failure")
50 }
51}