1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package eval

import (
	"fmt"
	"strings"
)

// PrintValue serializes v to the same string representation that `nix eval`
// produces. It deep-forces thunks before printing.
//
// The output format matches the C++ Printer in print.cc:
//
//	integer  → 42
//	float    → 3.5   (Go %g, same as C++ ostream << double)
//	bool     → true / false
//	null     → null
//	string   → "hello\nworld"  (escaped)
//	path     → /nix/store/...  (unquoted)
//	list     → [ 1 2 3 ]
//	attrset  → { a = 1; b = 2; }  (sorted by name, attrs already sorted in Bindings)
//	lambda   → «lambda»
//	primop   → «primop name»
func PrintValue(s *EvalState, v Value) (string, error) {
	p := &printer{state: s, seenAttr: make(map[*Bindings]bool), seenList: make(map[*VList]bool)}
	if err := p.print(v); err != nil {
		return "", err
	}
	return p.buf.String(), nil
}

type printer struct {
	state    *EvalState
	buf      strings.Builder
	seenAttr map[*Bindings]bool // cycle detection for attrsets
	seenList map[*VList]bool    // cycle detection for lists
}

func (p *printer) print(v Value) error {
	if err := p.state.forceValue(&v, NoPosIdx); err != nil {
		return err
	}
	switch t := v.(type) {
	case VInt:
		fmt.Fprintf(&p.buf, "%d", t.V)

	case VFloat:
		// C++ ostream << double uses 6 significant digits (%.6g equivalent).
		p.buf.WriteString(fmt.Sprintf("%.6g", t.V))

	case VBool:
		if t.V {
			p.buf.WriteString("true")
		} else {
			p.buf.WriteString("false")
		}

	case VNull:
		p.buf.WriteString("null")

	case VString:
		p.buf.WriteString(escapeNixString(t.V))

	case VPath:
		p.buf.WriteString(p.state.FS.RealPath(fsPath(t.V), t.Relative))

	case *VList:
		if p.seenList[t] {
			p.buf.WriteString("«repeated»")
			return nil
		}
		p.seenList[t] = true
		defer delete(p.seenList, t)

		if len(t.Elems) == 0 {
			p.buf.WriteString("[ ]")
		} else {
			p.buf.WriteString("[ ")
			for i, elem := range t.Elems {
				if i > 0 {
					p.buf.WriteByte(' ')
				}
				if err := p.print(elem); err != nil {
					return err
				}
			}
			p.buf.WriteString(" ]")
		}

	case VAttrs:
		if p.seenAttr[t.Bindings] {
			p.buf.WriteString("«repeated»")
			return nil
		}
		p.seenAttr[t.Bindings] = true
		defer delete(p.seenAttr, t.Bindings)

		if t.Bindings.Len() == 0 {
			p.buf.WriteString("{ }")
		} else {
			p.buf.WriteString("{ ")
			all := t.Bindings.All()
			for _, i := range lexicoOrder(p.state, t.Bindings) {
				attr := &all[i]
				p.buf.WriteString(nixIdentifier(p.state.Symbols.Str(attr.Name)))
				p.buf.WriteString(" = ")
				if err := p.print(attr.Value); err != nil {
					return err
				}
				p.buf.WriteString("; ")
			}
			p.buf.WriteByte('}')
		}

	case *VLambda:
		p.buf.WriteString("<LAMBDA>")

	case VPrimOp:
		p.buf.WriteString("<PRIMOP>")

	case VPrimOpApp:
		p.buf.WriteString("<PRIMOP-APP>")

	case *VThunk:
		p.buf.WriteString("«thunk»")

	default:
		fmt.Fprintf(&p.buf, "«unknown:%T»", v)
	}
	return nil
}

// escapeNixString wraps s in double quotes and escapes special characters,
// matching C++ escapeString() in escape-string.cc.
func escapeNixString(s string) string {
	var b strings.Builder
	b.WriteByte('"')
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch c {
		case '"', '\\':
			b.WriteByte('\\')
			b.WriteByte(c)
		case '\n':
			b.WriteString("\\n")
		case '\r':
			b.WriteString("\\r")
		case '\t':
			b.WriteString("\\t")
		case '$':
			if i+1 < len(s) && s[i+1] == '{' {
				b.WriteString("\\$")
			} else {
				b.WriteByte(c)
			}
		default:
			b.WriteByte(c)
		}
	}
	b.WriteByte('"')
	return b.String()
}

// nixKeywords is the set of Nix keywords that cannot be bare identifiers.
var nixKeywords = map[string]bool{
	"if": true, "then": true, "else": true, "assert": true,
	"with": true, "let": true, "in": true, "rec": true,
	"inherit": true, "or": true,
}

// nixIdentifier prints a Nix attribute name, quoting it if it is not a valid
// bare identifier (matching the C++ printIdentifier() in print.cc).
func nixIdentifier(name string) string {
	if isSimpleIdent(name) {
		return name
	}
	return escapeNixString(name)
}

// isSimpleIdent returns true if name can appear unquoted as an attribute name.
// Nix simple identifiers match [a-zA-Z_][a-zA-Z0-9_'-]* and are not keywords.
func isSimpleIdent(name string) bool {
	if len(name) == 0 || nixKeywords[name] {
		return false
	}
	for i, r := range name {
		if i == 0 {
			if !isAlpha(r) && r != '_' {
				return false
			}
		} else {
			if !isAlpha(r) && !isDigit(r) && r != '_' && r != '-' && r != '\'' {
				return false
			}
		}
	}
	return true
}

func isAlpha(r rune) bool {
	return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
}

func isDigit(r rune) bool {
	return r >= '0' && r <= '9'
}