~mna/snow

ref: f403078a7866d9f7107b7c666ea16f424050c5c6 snow/pkg/printer/printer.go -rw-r--r-- 9.1 KiB
f403078aMartin Angers pkg/codegen: done with generating nodes for struct generics and all 2 years ago
                                                                                
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package printer

import (
	"fmt"
	"io"
	"strconv"
	"strings"

	"git.sr.ht/~mna/snow/pkg/ast"
	"git.sr.ht/~mna/snow/pkg/semantic"
	"git.sr.ht/~mna/snow/pkg/token"
)

// PosMode is the mode that controls printing of position information.
type PosMode int

// List of supported position modes.
const (
	PosNone    PosMode = iota
	PosOffsets         // [startoffset:endoffset]
	PosLong            // [filename:startline:col:endline:col]
	PosRaw             // [%d:%d] of the raw uninterpreted gotoken.Pos values
)

// FormatPos formats the position according to the mode. If filename is false and the
// mode is PosLong, the filename is not included (useful to print a range of from:to
// positions, where the filename is already part of the from label).
func FormatPos(mode PosMode, file *token.File, pos token.Pos, filename bool) string {
	var lbl string
	switch mode {
	case PosOffsets:
		lbl = "-"
		if pos.IsValid() {
			lbl = strconv.Itoa(file.Offset(pos))
		}

	case PosLong:
		if pos.IsValid() {
			lpos := file.Position(pos)
			if filename {
				lbl = fmt.Sprintf("%s:%d:%d", lpos.Filename, lpos.Line, lpos.Column)
			} else {
				lbl = fmt.Sprintf(":%d:%d", lpos.Line, lpos.Column)
			}
		} else if filename {
			lbl = fmt.Sprintf("%s:-:-", file.Name())
		} else {
			lbl = ":-:-"
		}

	case PosRaw:
		lbl = strconv.Itoa(int(pos))
	}
	return lbl
}

// Printer controls pretty-printing of the AST.
type Printer struct {
	// W is the io.Writer to print to.
	W io.Writer
	// Pos indicates the position mode.
	Pos PosMode
	// WithComments controls printing of comments.
	WithComments bool

	// set during printing
	file   *token.File
	maxPos token.Pos
	depth  int
	err    error
}

// PrintAST pretty-prints the AST node n from the specified file.
func (p *Printer) PrintAST(n ast.Node, file *token.File) error {
	if file == nil {
		return nil
	}

	p.file = file
	p.maxPos = token.Pos(p.file.Base() + p.file.Size())
	p.depth = 0
	p.err = nil
	ast.Walk(&astPrinter{p}, n)
	return p.err
}

// PrintSemantic pretty-prints the semantic node n from the specified file.
func (p *Printer) PrintSemantic(n semantic.Node, file *token.File) error {
	if file == nil {
		return nil
	}

	p.file = file
	p.maxPos = token.Pos(p.file.Base() + p.file.Size())
	p.depth = 0
	p.err = nil
	semantic.Walk(&semanticPrinter{p}, n)
	return p.err
}

func (p *Printer) printMsg(s string, indent bool) {
	if p.err != nil {
		return
	}
	repeat := p.depth - 1
	if !indent {
		repeat = 0
	}
	_, p.err = fmt.Fprintf(p.W, "%s%s", strings.Repeat("  ", repeat), s)
}

func (p *Printer) clamp(pos token.Pos) token.Pos {
	if pos > p.maxPos {
		return p.maxPos
	}
	return pos
}

type posNode interface {
	Pos() token.Pos
	End() token.Pos
}

type ender struct {
	semantic.Node
}

func (e ender) End() token.Pos { return e.Pos() }

func (p *Printer) printPosln(n posNode) {
	if p.err != nil {
		return
	}
	_, p.err = fmt.Fprintf(p.W, " [%s:%s]\n",
		FormatPos(p.Pos, p.file, n.Pos(), true),
		FormatPos(p.Pos, p.file, p.clamp(n.End()), false),
	)
}

type semanticPrinter struct {
	*Printer
}

type typedExpr interface {
	Type() semantic.Type
	TypeContext() semantic.TypeContext
}

func (p *semanticPrinter) Visit(n semantic.Node) semantic.Visitor {
	if n == nil || p.err != nil {
		p.depth--
		return nil
	}
	p.depth++

	switch n := n.(type) {
	case *semantic.File:
		p.printMsg(fmt.Sprintf("file %s [%d, %d, %d]", p.file.Name(), len(n.Vars), len(n.Fns), len(n.Structs)), true)
	case *semantic.Fn:
		format := "fn %s"
		args := []interface{}{n.Ident()}
		if n.IsRef {
			format = "ref " + format
		}
		if n.GenericParams != nil {
			format += " [$%d]"
			args = append(args, len(n.GenericParams.Elems))
		}
		p.printMsg(fmt.Sprintf(format, args...), true)
	case *semantic.Var:
		lbl := n.Ctx.String()
		if n.TypeExpr != nil {
			lbl += ":"
		}
		if n.Value != nil {
			lbl += "="
		}
		p.printMsg(fmt.Sprintf("%s %s", lbl, n.Ident()), true)
	case *semantic.Struct:
		format := "struct %s [%d, %d, %d"
		args := []interface{}{n.Ident(), len(n.Vars), len(n.Fns), len(n.Structs)}
		if n.GenericParams != nil {
			format += ", $%d"
			args = append(args, len(n.GenericParams.Elems))
		}
		format += "]"
		p.printMsg(fmt.Sprintf(format, args...), true)
	case *semantic.Block:
		p.printMsg(fmt.Sprintf("block [%d]", len(n.Stmts)), true)
	case *semantic.Return:
		p.printMsg("return", true)
	case *semantic.Assign:
		p.printMsg("assign", true)
	case *semantic.ExprStmt:
		p.printMsg("expr", true)
	case *semantic.If:
		p.printMsg(fmt.Sprintf("if [%d]", len(n.Conds)), true)
	case *semantic.Guard:
		p.printMsg(fmt.Sprintf("guard [%d]", len(n.Conds)), true)
	case *semantic.FnTypeExpr:
		ret := 0
		if n.Return != nil {
			ret = 1
		}
		p.printMsg(fmt.Sprintf("sig [%d->%d]", len(n.Params), ret), true)
	case *semantic.TupleTypeExpr:
		p.printMsg(fmt.Sprintf("tuple type [%d]", len(n.Fields)), true)
	case *semantic.TupleVal:
		p.printMsg(fmt.Sprintf("tuple value [%d]", len(n.Values)), true)
	case *semantic.Binary:
		p.printMsg(fmt.Sprintf("binary [%s]", n.Op), true)
	case *semantic.Unary:
		p.printMsg(fmt.Sprintf("unary [%s]", n.Op), true)
	case *semantic.Paren:
		p.printMsg("paren", true)
	case *semantic.Call:
		var buf strings.Builder
		var hasLbls bool

		buf.WriteByte('[')
		for i, lbl := range n.Labels {
			if i > 0 {
				buf.WriteString(", ")
			}
			buf.WriteString(lbl)
			if !hasLbls {
				hasLbls = lbl != ""
			}
		}
		buf.WriteByte(']')

		typ := "call"
		if n.AttrOf != nil {
			typ = "@"
		}
		if hasLbls {
			p.printMsg(fmt.Sprintf("%s %s [%d]", typ, buf.String(), len(n.Args)), true)
		} else {
			p.printMsg(fmt.Sprintf("%s [%d]", typ, len(n.Args)), true)
		}
	case *semantic.Selector:
		p.printMsg("select", true)
	case *semantic.LitString:
		p.printMsg(fmt.Sprintf("string [%s]", n.Repr), true)
	case *semantic.LitInt:
		p.printMsg(fmt.Sprintf("int [%s]", n.Repr), true)
	case *semantic.GenericInst:
		p.printMsg(fmt.Sprintf("generic inst [%d]", len(n.TypeExprs)), true)
	case *semantic.GenericElem:
		p.printMsg(fmt.Sprintf("generic type %s", n.Ident()), true)
	case *semantic.Ident:
		p.printMsg(fmt.Sprintf("ident %s", n.Name), true)
	case *semantic.ImplicitConv:
		p.printMsg("implicit conv", true)
	}

	if te, ok := n.(typedExpr); ok {
		p.printMsg(fmt.Sprintf(" [%s: %s]", te.TypeContext(), te.Type()), false)
	}

	if p.Pos != PosNone {
		p.printPosln(ender{n})
	} else {
		p.printMsg("\n", false)
	}

	return p
}

type astPrinter struct {
	*Printer
}

func (p *astPrinter) Visit(n ast.Node) ast.Visitor {
	if n == nil || p.err != nil {
		p.depth--
		return nil
	}
	p.depth++

	switch n := n.(type) {
	case *ast.File:
		p.printMsg(fmt.Sprintf("file [%d, #%d]", len(n.Decls), len(n.Comments)), true)
	case *ast.FnDecl:
		if n.Ref.IsValid() {
			p.printMsg("ref fn", true)
		} else {
			p.printMsg("fn", true)
		}
	case *ast.FnSig:
		ret := 0
		if n.RetType != nil {
			ret = 1
		}
		p.printMsg(fmt.Sprintf("sig [%d->%d]", len(n.Params), ret), true)
	case *ast.FnType:
		ret := 0
		if n.RetType != nil {
			ret = 1
		}
		p.printMsg(fmt.Sprintf("sig [%d->%d]", len(n.Params), ret), true)
	case *ast.TupleType:
		p.printMsg(fmt.Sprintf("tuple type [%d]", len(n.Types)), true)
	case *ast.TupleExpr:
		p.printMsg(fmt.Sprintf("tuple value [%d]", len(n.Values)), true)
	case *ast.ParamDef:
		p.printMsg("param", true)
	case *ast.GenericClause:
		p.printMsg("generic", true)
	case *ast.Block:
		p.printMsg(fmt.Sprintf("block [%d]", len(n.Stmts)), true)
	case *ast.Attr:
		p.printMsg(fmt.Sprintf("@ [%d]", len(n.Fields)), true)
	case *ast.KeyValue:
		p.printMsg("field", true)
	case *ast.VarDecl:
		p.printMsg(n.Kw.String(), true)
	case *ast.VarDef:
		lbl := n.Name.Name
		if n.Colon.IsValid() {
			lbl += ":"
		}
		if n.Assign.IsValid() {
			lbl += "="
		}
		p.printMsg(lbl, true)
	case *ast.StructDecl:
		p.printMsg(fmt.Sprintf("struct [%d]", len(n.Decls)), true)
	case *ast.ReturnStmt:
		p.printMsg("return", true)
	case *ast.BinaryExpr:
		p.printMsg(fmt.Sprintf("binary [%s]", n.Op), true)
	case *ast.UnaryExpr:
		p.printMsg(fmt.Sprintf("unary [%s]", n.Op), true)
	case *ast.ParenExpr:
		p.printMsg("paren", true)
	case *ast.CallExpr:
		p.printMsg(fmt.Sprintf("call [%d]", len(n.Args)), true)
	case *ast.SelectorExpr:
		p.printMsg("select", true)
	case *ast.ExprItem:
		lbl := "item"
		if n.Label != nil {
			lbl += ":"
		}
		p.printMsg(lbl, true)
	case *ast.AssignStmt:
		p.printMsg("assign", true)
	case *ast.ExprStmt:
		p.printMsg("expr", true)
	case *ast.IfStmt:
		p.printMsg(fmt.Sprintf("if [%d]", len(n.Conds)), true)
	case *ast.GuardStmt:
		p.printMsg(fmt.Sprintf("guard [%d]", len(n.Conds)), true)
	case *ast.ElseClause:
		p.printMsg("else", true)
	case *ast.BasicLit:
		p.printMsg(fmt.Sprintf("%s [%s]", n.Literal, n.Value), true)
	case *ast.GenericIdent:
		p.printMsg("generic ident", true)
	case *ast.Ident:
		p.printMsg(fmt.Sprintf("ident [%s]", n.Name), true)
	case *ast.BadStmt:
		p.printMsg("bad stmt", true)
	case *ast.BadExpr:
		p.printMsg("bad expr", true)
	case *ast.CommentGroup:
		if !p.WithComments {
			return nil
		}
		p.printMsg(fmt.Sprintf("comments [%d]", len(n.List)), true)
	case *ast.Comment:
		if !p.WithComments {
			return nil
		}
		p.printMsg(fmt.Sprintf("comment [%s]", n.Text), true)

	default:
		panic(fmt.Sprintf("printer: unexpected node type %T", n))
	}

	if p.Pos != PosNone {
		p.printPosln(n)
	} else {
		p.printMsg("\n", false)
	}

	return p
}