github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/vals/repr.go (about)

     1  package vals
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/u-root/u-root/cmds/core/elvish/parse"
     7  	"github.com/u-root/u-root/cmds/core/elvish/util"
     8  )
     9  
    10  // NoPretty can be passed to Repr to suppress pretty-printing.
    11  const NoPretty = util.MinInt
    12  
    13  // Reprer wraps the Repr method.
    14  type Reprer interface {
    15  	// Repr returns a string that represents a Value. The string either be a
    16  	// literal of that Value that is preferably deep-equal to it (like `[a b c]`
    17  	// for a list), or a string enclosed in "<>" containing the kind and
    18  	// identity of the Value(like `<fn 0xdeadcafe>`).
    19  	//
    20  	// If indent is at least 0, it should be pretty-printed with the current
    21  	// indentation level of indent; the indent of the first line has already
    22  	// been written and shall not be written in Repr. The returned string
    23  	// should never contain a trailing newline.
    24  	Repr(indent int) string
    25  }
    26  
    27  // Repr returns the representation for a value, a string that is preferably (but
    28  // not necessarily) an Elvish expression that evaluates to the argument. If
    29  // indent >= 0, the representation is pretty-printed. It is implemented for the
    30  // builtin types bool and string, and types satisfying the listReprable,
    31  // mapReprable or Reprer interface. For other types, it uses fmt.Sprint with the
    32  // format "<unknown %v>".
    33  func Repr(v interface{}, indent int) string {
    34  	switch v := v.(type) {
    35  	case Reprer:
    36  		return v.Repr(indent)
    37  	case bool:
    38  		if v {
    39  			return "$true"
    40  		}
    41  		return "$false"
    42  	case string:
    43  		return parse.Quote(v)
    44  	case listReprable:
    45  		b := ListReprBuilder{Indent: indent}
    46  		for it := v.Iterator(); it.HasElem(); it.Next() {
    47  			b.WriteElem(Repr(it.Elem(), indent+1))
    48  		}
    49  		return b.String()
    50  	case mapReprable:
    51  		builder := MapReprBuilder{}
    52  		builder.Indent = indent
    53  		for it := v.Iterator(); it.HasElem(); it.Next() {
    54  			k, v := it.Elem()
    55  			builder.WritePair(Repr(k, indent+1), indent+2, Repr(v, indent+2))
    56  		}
    57  		return builder.String()
    58  	default:
    59  		return fmt.Sprintf("<unknown %v>", v)
    60  	}
    61  }
    62  
    63  type listReprable listIterable
    64  type mapReprable mapIterable