~mna/snow unlisted

snow/pkg/codegen/mangle.go -rw-r--r-- 8.9 KiB
424066c5Martin Angers doc: v0.0.5 1 year, 6 months 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
package codegen

import (
	"fmt"
	"strconv"
	"strings"

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

const (
	exportedChar   = 'X'
	unexportedChar = '_'
	invalidChar    = '🤦'
)

// mangle mangles all identifiers declared in decls. The logic is as follows.
// For each declared identifier:
//   - If it is a basic type or identifier in the universe, mangle it to its
//     corresponding Go identifier and stop here.
//   - If it is the main function, mangle it to its corresponding Go identifier
//     and stop here.
//   - If it is an unused variable (not struct property or function parameter),
//     mangle it as "_" so that it doesn't generate unused error, and stop here.
//   Otherwise, go through all of the following that apply, where `$` stands for the name
//   mangling separator:
//   - If it is any top-level identifier, a struct, a struct variable or a struct
//     method, prefix it as `_$` or `X$` (unexported or exported)
//   - If it is a non-top-level struct, add the ID of the scope to the prefix,
//     followed with `$`
//   - Append the original identifier
//   - If at this point the resulting identifier is a Go reserved keyword,
//     prefix it with `$`
//
func mangle(unit *semantic.Unit) *nameResolver {
	ruses := make(map[semantic.Decl]bool, len(unit.ValueUses))
	for _, decl := range unit.ValueUses {
		ruses[decl] = true
	}

	names := make(map[semantic.Decl]string)
	InspectScope(unit.Scope(), func(s *semantic.Scope) bool {
		if s == nil {
			return false
		}

		for _, decl := range s.Symbols {
			// first, process the standard cases for all decls
			if decl == unit.Main {
				names[decl] = basicIdentsToGo[decl.Ident()]
				continue
			}
			if decl.Scope().IsUniverse() {
				if _, ok := decl.Type().(*semantic.BasicType); ok {
					names[decl] = basicIdentsToGo[decl.Ident()]
					continue
				}
			}

			if decl.IsGeneric() {
				// the actual name will be mangled on-the-fly as the Go AST is generated,
				// but a mangled name can be required if a generic is used as left-hand side
				// of a selector, e.g. A.B where A is a generic struct and B is a struct.
				// In the final AST, the mangled name of A will not be used, but during the
				// translate pass it will be accessed, so register an invalid name so that
				// it is easy to tell (fail noisily) if it does end up in the generated code.
				names[decl] = string(invalidChar) + decl.Ident()
				continue
			}

			var b fmtBuilder
			switch decl := decl.(type) {
			case *semantic.Fn:
				b.withPrefixFor(decl)
				names[decl] = b.get(decl.Ident())

			case *semantic.Var:
				// if this is a variable (not a struct field nor a function parameter)
				// and its value is unused, mangle as "_".
				if !ruses[decl] && decl.ParamOf == nil && decl.PropOf == nil {
					// TODO: unless public/exported
					names[decl] = "_"
					break
				}
				b.withPrefixFor(decl)
				names[decl] = b.get(decl.Ident())

			case *semantic.Struct:
				b.withPrefixFor(decl)
				names[decl] = b.get(decl.Ident())

			case *semantic.Interface:
				b.withPrefixFor(decl)
				names[decl] = b.get(decl.Ident())
			}
		}
		return true
	})

	typesSets := make(map[semantic.Decl][][]semantic.Type)
	return &nameResolver{names: names, typesSets: typesSets}
}

type nameResolver struct {
	// mangled names for declarations
	names map[semantic.Decl]string
	// map of generic declaration to list of instantiation types, to mangle unique
	// names per identical instantiation.
	typesSets map[semantic.Decl][][]semantic.Type
}

func (r *nameResolver) NameForDecl(n semantic.Decl) string {
	nm := r.names[n]
	if nm == "" {
		panic(fmt.Sprintf("no name recorded for %s", semantic.TypeIdentString(n)))
	}
	return nm
}

func (r *nameResolver) NameForStructType(st *semantic.StructType, resolve map[*semantic.GenericType]semantic.Type) string {
	if !st.Decl.IsGeneric() {
		return r.NameForDecl(st.Decl)
	}
	return r.NameForGenericDeclAndTypes(st.Decl, st.Inst, resolve)
}

func (r *nameResolver) NameForInterfaceType(it *semantic.InterfaceType, resolve map[*semantic.GenericType]semantic.Type) string {
	if !it.Decl.IsGeneric() {
		return r.NameForDecl(it.Decl)
	}
	return r.NameForGenericDeclAndTypes(it.Decl, it.Inst, resolve)
}

func (r *nameResolver) NameForGenericInst(gi *semantic.GenericInst, resolve map[*semantic.GenericType]semantic.Type) string {
	gd := gi.GenericDecl.Ref.(semantic.GenericDecl)
	_, insts := gd.GenInsts()
	types := insts[gi]
	return r.NameForGenericDeclAndTypes(gd, types, resolve)
}

func (r *nameResolver) NameForGenericDeclAndTypes(decl semantic.Decl, types []semantic.Type, resolve map[*semantic.GenericType]semantic.Type) string {
	for i, typ := range types {
		types[i] = typ.ResolveGeneric(resolve)
	}

	var b fmtBuilder
	b.withPrefixFor(decl)
	typesID := r.idForGenericInst(decl, types)

	return b.get(decl.Ident() +
		string(scanner.NameManglingSeparator) +
		strconv.Itoa(typesID))
}

func (r *nameResolver) idForGenericInst(genDecl semantic.Decl, types []semantic.Type) int {
	list := r.typesSets[genDecl]

outer:
	for i, set := range list {
		for j, typ1 := range set {
			if j >= len(types) {
				continue outer
			}
			typ2 := types[j]
			if !typ1.IdenticalTo(typ2) {
				continue outer
			}
		}
		return i
	}

	list = append(list, types)
	r.typesSets[genDecl] = list
	return len(list) - 1
}

func (r *nameResolver) NameForTuple(index int, exported bool) string {
	var b fmtBuilder
	b.withExport(exported)
	return b.get(strconv.Itoa(index))
}

func (r *nameResolver) NameForStructInit(baseName string) string {
	// TODO: for now, just append the separator and "new", so it gets exported if
	// the struct is exported. This will require more thought when pub gets added,
	// as some struct fields might be exported but others not, and the struct
	// still has to be fully initialized on return. Possibly a static analysis
	// that makes sure all fields are assigned in the initializer.
	return baseName + string(scanner.NameManglingSeparator) + "new"
}

// NameForConv returns the Go name for an automatically- generated function to
// convert tuples for type-reconciliation. As it is not an identifier in the
// Snow code, care must be taken to avoid conflicts, so its name must be
// impossible in Snow.
func (r *nameResolver) NameForConv(index int) string {
	var b fmtBuilder
	b.withExport(false)
	return b.get(string(scanner.NameManglingSeparator) + "convert_" + strconv.Itoa(index))
}

type fmtBuilder struct {
	name strings.Builder
}

func (b *fmtBuilder) withPrefixFor(decl semantic.Decl) {
	switch decl := decl.(type) {
	case *semantic.Fn:
		if decl.Scope().IsTopLevel() || decl.MethodOf != nil || decl.AbstractMethodOf != nil {
			// TODO: this will be an issue with pub/exported methods eventually: the mangling of
			// an interface method might not match the one of an otherwise matching struct method.
			b.withExport(false)
		}
	case *semantic.Var:
		if decl.Scope().IsTopLevel() || decl.PropOf != nil {
			b.withExport(false)
		}
	case *semantic.Struct:
		b.withExport(false)
		if !decl.Scope().IsTopLevel() {
			b.withScope(decl.Scope())
		}
	case *semantic.Interface:
		b.withExport(false)
		if !decl.Scope().IsTopLevel() {
			b.withScope(decl.Scope())
		}
	default:
		panic(fmt.Sprintf("invalid declaration type for mangler prefix: %T", decl))
	}
}

func (b *fmtBuilder) withExport(exported bool) {
	if exported {
		b.name.WriteByte(exportedChar)
	} else {
		b.name.WriteByte(unexportedChar)
	}
	b.name.WriteRune(scanner.NameManglingSeparator)
}

func (b *fmtBuilder) withScope(s *semantic.Scope) {
	b.name.WriteString(strconv.Itoa(s.ID))
	b.name.WriteRune(scanner.NameManglingSeparator)
}

func (b *fmtBuilder) get(nm string) string {
	if b.name.Len() == 0 && goKeywords[nm] {
		b.name.WriteRune(scanner.NameManglingSeparator)
	}
	b.name.WriteString(nm)
	return b.name.String()
}

var basicIdentsToGo = map[string]string{
	semantic.Bool.String():   "bool",
	semantic.Int.String():    "int",
	semantic.I8.String():     "int8",
	semantic.I16.String():    "int16",
	semantic.I32.String():    "int32",
	semantic.I64.String():    "int64",
	semantic.Uint.String():   "uint",
	semantic.U8.String():     "uint8",
	semantic.U16.String():    "uint16",
	semantic.U32.String():    "uint32",
	semantic.U64.String():    "uint64",
	semantic.Float.String():  "float64",
	semantic.F32.String():    "float32",
	semantic.F64.String():    "float64",
	semantic.String.String(): "string",
	semantic.TrueLitName:     "true",
	semantic.FalseLitName:    "false",
	semantic.MainFnName:      "main",
}

var goKeywords = map[string]bool{
	"break":       true,
	"case":        true,
	"chan":        true,
	"const":       true,
	"continue":    true,
	"default":     true,
	"defer":       true,
	"else":        true,
	"fallthrough": true,
	"for":         true,
	"func":        true,
	"go":          true,
	"goto":        true,
	"if":          true,
	"import":      true,
	"interface":   true,
	"map":         true,
	"package":     true,
	"range":       true,
	"return":      true,
	"select":      true,
	"struct":      true,
	"switch":      true,
	"type":        true,
	"var":         true,
}