genMap.go 24.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
package gengo

import (
	"io"

	"github.com/ipld/go-ipld-prime/schema"
	"github.com/ipld/go-ipld-prime/schema/gen/go/mixins"
)

type mapGenerator struct {
	AdjCfg *AdjunctCfg
	mixins.MapTraits
	PkgName string
	Type    schema.TypeMap
}

// --- native content and specializations --->

func (g mapGenerator) EmitNativeType(w io.Writer) {
	// Maps do double bookkeeping.
	// - 'm' is used for quick lookup.
	// - 't' is used for both for order maintainence, and for allocation amortization for both keys and values.
	// Note that the key in 'm' is *not* a pointer.
24
	// The value in 'm' is a pointer into 't' (except when it's a maybe; maybes are already pointers).
25 26
	doTemplate(`
		type _{{ .Type | TypeSymbol }} struct {
27
			m map[_{{ .Type.KeyType | TypeSymbol }}]{{if .Type.ValueIsNullable }}Maybe{{else}}*_{{end}}{{ .Type.ValueType | TypeSymbol }}
28 29 30 31 32 33 34 35 36 37 38
			t []_{{ .Type | TypeSymbol }}__entry
		}
		type {{ .Type | TypeSymbol }} = *_{{ .Type | TypeSymbol }}
	`, w, g.AdjCfg, g)
	// - address of 'k' is used when we return keys as nodes, such as in iterators.
	//    Having these in the 't' slice above amortizes moving all of them to heap at once,
	//     which makes iterators that have to return them as an interface much (much) lower cost -- no 'runtime.conv*' pain.
	// - address of 'v' is used in map values, to return, and of course also in iterators.
	doTemplate(`
		type _{{ .Type | TypeSymbol }}__entry struct {
			k _{{ .Type.KeyType | TypeSymbol }}
Eric Myhre's avatar
Eric Myhre committed
39
			v _{{ .Type.ValueType | TypeSymbol }}{{if .Type.ValueIsNullable }}__Maybe{{end}}
40 41 42 43 44
		}
	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitNativeAccessors(w io.Writer) {
45 46 47 48 49 50 51 52 53
	// Generate a speciated Lookup as well as LookupMaybe method.
	// The LookupMaybe method is needed if the map value is nullable and you're going to distinguish nulls
	//  (and may also be convenient if you would rather handle Maybe_Absent than an error for not-found).
	// The Lookup method works fine if the map value isn't nullable
	//  (and should be preferred in that case, because boxing something into a maybe when it wasn't already stored that way costs an alloc(!),
	//   and may additionally incur a memcpy if the maybe for the value type doesn't use pointers internally).
	// REVIEW: is there a way we can make this less twisty?  it is VERY unfortunate if the user has to know what sort of map it is to know which method to prefer.
	//  Maybe the Lookup method on maps that have nullable values should just always have a MaybeT return type?
	//   But then this means the Lookup method doesn't "need" an error as part of its return signiture, which just shuffles differences around.
54
	doTemplate(`
55
		func (n *_{{ .Type | TypeSymbol }}) LookupMaybe(k {{ .Type.KeyType | TypeSymbol }}) Maybe{{ .Type.ValueType | TypeSymbol }} {
56 57
			v, ok := n.m[*k]
			if !ok {
58
				return &_{{ .Type | TypeSymbol }}__valueAbsent
59 60
			}
			{{- if .Type.ValueIsNullable }}
61
			return v
62
			{{- else}}
63 64 65 66
			return &_{{ .Type.ValueType | TypeSymbol }}__Maybe{
				m: schema.Maybe_Value,
				v: {{ if not (MaybeUsesPtr .Type.ValueType) }}*{{end}}v,
			}
67 68
			{{- end}}
		}
69 70 71 72

		var _{{ .Type | TypeSymbol }}__valueAbsent = _{{ .Type.ValueType | TypeSymbol }}__Maybe{m:schema.Maybe_Absent}

		// TODO generate also a plain Lookup method that doesn't box and alloc if this type contains non-nullable values!
73 74 75 76 77 78 79 80 81
	`, w, g.AdjCfg, g)
	// FUTURE: also a speciated iterator?
}

func (g mapGenerator) EmitNativeBuilder(w io.Writer) {
	// Not yet clear what exactly might be most worth emitting here.
}

func (g mapGenerator) EmitNativeMaybe(w io.Writer) {
82
	emitNativeMaybe(w, g.AdjCfg, g)
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
}

// --- type info --->

func (g mapGenerator) EmitTypeConst(w io.Writer) {
	doTemplate(`
		// TODO EmitTypeConst
	`, w, g.AdjCfg, g)
}

// --- TypedNode interface satisfaction --->

func (g mapGenerator) EmitTypedNodeMethodType(w io.Writer) {
	doTemplate(`
		func ({{ .Type | TypeSymbol }}) Type() schema.Type {
			return nil /*TODO:typelit*/
		}
	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitTypedNodeMethodRepresentation(w io.Writer) {
104
	emitTypicalTypedNodeMethodRepresentation(w, g.AdjCfg, g)
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
}

// --- Node interface satisfaction --->

func (g mapGenerator) EmitNodeType(w io.Writer) {
	// No additional types needed.  Methods all attach to the native type.
}

func (g mapGenerator) EmitNodeTypeAssertions(w io.Writer) {
	doTemplate(`
		var _ ipld.Node = ({{ .Type | TypeSymbol }})(&_{{ .Type | TypeSymbol }}{})
		var _ schema.TypedNode = ({{ .Type | TypeSymbol }})(&_{{ .Type | TypeSymbol }}{})
	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitNodeMethodLookupString(w io.Writer) {
121 122 123 124 125
	// What should be coercible in which directions (and how surprising that is) is an interesting question.
	//  Most of the answer comes from considering what needs to be possible when working with PathSegment:
	//   we *must* be able to accept a string in a PathSegment and be able to use it to navigate a map -- even if the map has complex keys.
	//   For that to work out, it means if the key type doesn't have a string type kind, we must be willing to reach into its representation and use the fromString there.
	//  If the key type *does* have a string kind at the type level, we'll use that; no need to consider going through the representation.
126
	doTemplate(`
Eric Myhre's avatar
Eric Myhre committed
127 128
		func (n {{ .Type | TypeSymbol }}) LookupString(k string) (ipld.Node, error) {
			var k2 _{{ .Type.KeyType | TypeSymbol }}
129
			{{- if eq .Type.KeyType.Kind.String "String" }}
Eric Myhre's avatar
Eric Myhre committed
130 131 132
			if err := (_{{ .Type.KeyType | TypeSymbol }}__Style{}).fromString(&k2, k); err != nil {
				return nil, err // TODO wrap in some kind of ErrInvalidKey
			}
133
			{{- else}}
Eric Myhre's avatar
Eric Myhre committed
134 135 136
			if err := (_{{ .Type.KeyType | TypeSymbol }}__ReprStyle{}).fromString(&k2, k); err != nil {
				return nil, err // TODO wrap in some kind of ErrInvalidKey
			}
137 138 139
			{{- end}}
			v, exists := n.m[k2]
			if !exists {
Eric Myhre's avatar
Eric Myhre committed
140
				return ipld.Undef, ipld.ErrNotExists{ipld.PathSegmentOfString(k)}
141 142 143 144 145 146 147 148 149
			}
			{{- if .Type.ValueIsNullable }}
			if v.m == schema.Maybe_Null {
				return ipld.Null, nil
			}
			return {{ if not (MaybeUsesPtr .Type.ValueType) }}&{{end}}v.v, nil
			{{- else}}
			return v, nil
			{{- end}}
150 151 152 153 154
		}
	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitNodeMethodLookup(w io.Writer) {
155 156 157 158
	// LookupNode will procede by cast if it can; or simply error if that doesn't work.
	//  There's no attempt to turn the node (or its repr) into a string and then reify that into a key;
	//   if you used a Node here, you should've meant it.
	// REVIEW: by comparison structs will coerce anything stringish silently...!  so we should figure out if that inconsistency is acceptable, and at least document it if so.
159
	doTemplate(`
Eric Myhre's avatar
Eric Myhre committed
160 161
		func (n {{ .Type | TypeSymbol }}) Lookup(k ipld.Node) (ipld.Node, error) {
			k2, ok := k.({{ .Type.KeyType | TypeSymbol }})
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
			if !ok {
				panic("todo invalid key type error")
				// 'ipld.ErrInvalidKey{TypeName:"{{ .PkgName }}.{{ .Type.Name }}", Key:&_String{k}}' doesn't quite cut it: need room to explain the type, and it's not guaranteed k can be turned into a string at all
			}
			v, exists := n.m[*k2]
			if !exists {
				return ipld.Undef, ipld.ErrNotExists{ipld.PathSegmentOfString(k2.String())}
			}
			{{- if .Type.ValueIsNullable }}
			if v.m == schema.Maybe_Null {
				return ipld.Null, nil
			}
			return {{ if not (MaybeUsesPtr .Type.ValueType) }}&{{end}}v.v, nil
			{{- else}}
			return v, nil
			{{- end}}
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
		}
	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitNodeMethodMapIterator(w io.Writer) {
	doTemplate(`
		func (n {{ .Type | TypeSymbol }}) MapIterator() ipld.MapIterator {
			return &_{{ .Type | TypeSymbol }}__MapItr{n, 0}
		}

		type _{{ .Type | TypeSymbol }}__MapItr struct {
			n {{ .Type | TypeSymbol }}
			idx  int
		}

		func (itr *_{{ .Type | TypeSymbol }}__MapItr) Next() (k ipld.Node, v ipld.Node, _ error) {
			if itr.idx >= len(itr.n.t) {
				return nil, nil, ipld.ErrIteratorOverread{}
			}
197
			x := &itr.n.t[itr.idx]
198
			k = &x.k
199 200 201 202 203
			{{- if .Type.ValueIsNullable }}
			switch x.v.m {
			case schema.Maybe_Null:
				v = ipld.Null
			case schema.Maybe_Value:
204
				v = {{ if not (MaybeUsesPtr .Type.ValueType) }}&{{end}}x.v.v
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
			}
			{{- else}}
			v = &x.v
			{{- end}}
			itr.idx++
			return
		}
		func (itr *_{{ .Type | TypeSymbol }}__MapItr) Done() bool {
			return itr.idx >= len(itr.n.t)
		}

	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitNodeMethodLength(w io.Writer) {
	doTemplate(`
		func (n {{ .Type | TypeSymbol }}) Length() int {
			return len(n.t)
		}
	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitNodeMethodStyle(w io.Writer) {
	// REVIEW: this appears to be standard even across kinds; can we extract it?
	doTemplate(`
		func ({{ .Type | TypeSymbol }}) Style() ipld.NodeStyle {
			return _{{ .Type | TypeSymbol }}__Style{}
		}
	`, w, g.AdjCfg, g)
}

func (g mapGenerator) EmitNodeStyleType(w io.Writer) {
	// REVIEW: this appears to be standard even across kinds; can we extract it?
	doTemplate(`
		type _{{ .Type | TypeSymbol }}__Style struct{}

		func (_{{ .Type | TypeSymbol }}__Style) NewBuilder() ipld.NodeBuilder {
			var nb _{{ .Type | TypeSymbol }}__Builder
			nb.Reset()
			return &nb
		}
	`, w, g.AdjCfg, g)
}

// --- NodeBuilder and NodeAssembler --->

func (g mapGenerator) GetNodeBuilderGenerator() NodeBuilderGenerator {
	return mapBuilderGenerator{
		g.AdjCfg,
		mixins.MapAssemblerTraits{
			g.PkgName,
			g.TypeName,
			"_" + g.AdjCfg.TypeSymbol(g.Type) + "__",
		},
		g.PkgName,
		g.Type,
	}
}

type mapBuilderGenerator struct {
	AdjCfg *AdjunctCfg
	mixins.MapAssemblerTraits
	PkgName string
	Type    schema.TypeMap
}

func (g mapBuilderGenerator) EmitNodeBuilderType(w io.Writer) {
	doTemplate(`
		type _{{ .Type | TypeSymbol }}__Builder struct {
			_{{ .Type | TypeSymbol }}__Assembler
		}
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) EmitNodeBuilderMethods(w io.Writer) {
	doTemplate(`
		func (nb *_{{ .Type | TypeSymbol }}__Builder) Build() ipld.Node {
			if nb.state != maState_finished {
				panic("invalid state: assembler for {{ .PkgName }}.{{ .Type.Name }} must be 'finished' before Build can be called!")
			}
			return nb.w
		}
		func (nb *_{{ .Type | TypeSymbol }}__Builder) Reset() {
			var w _{{ .Type | TypeSymbol }}
			var m schema.Maybe
			*nb = _{{ .Type | TypeSymbol }}__Builder{_{{ .Type | TypeSymbol }}__Assembler{w: &w, m: &m, state: maState_initial}}
		}
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) EmitNodeAssemblerType(w io.Writer) {
	// - 'w' is the "**w**ip" pointer.
	// - 'm' is the **m**aybe which communicates our completeness to the parent if we're a child assembler.
	// - 'state' is what it says on the tin.  this is used for the map state (the broad transitions between null, start-map, and finish are handled by 'm' for consistency.)
	// - there's no equivalent of the 'f' (**f**ocused next) field in struct assemblers -- that's implicitly the last row of the 'w.t'.
	//
299 300 301 302 303 304
	// - 'cm' is **c**hild **m**aybe and is used for the completion message from children.
	//    It's used for values if values aren't allowed to be nullable and thus don't have their own per-value maybe slot we can use.
	//    It's always used for key assembly, since keys are never allowed to be nullable and thus etc.
	// - 'ka' and 'va' are the key assembler and value assembler respectively.
	//    Perhaps surprisingly, we can get away with using the assemblers for each type just straight up, no wrappers necessary;
	//     All of the required magic is handled through maybe pointers and some tidy methods used during state transitions.
305 306 307 308 309 310 311
	doTemplate(`
		type _{{ .Type | TypeSymbol }}__Assembler struct {
			w *_{{ .Type | TypeSymbol }}
			m *schema.Maybe
			state maState

			cm schema.Maybe
312
			ka _{{ .Type.KeyType | TypeSymbol }}__Assembler
313
			va _{{ .Type.ValueType | TypeSymbol }}__Assembler
314
		}
315 316 317 318 319 320

		func (na *_{{ .Type | TypeSymbol }}__Assembler) reset() {
			na.state = maState_initial
			na.ka.reset()
			na.va.reset()
		}
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) EmitNodeAssemblerMethodBeginMap(w io.Writer) {
	// This method contains a branch to support MaybeUsesPtr because new memory may need to be allocated.
	//  This allocation only happens if the 'w' ptr is nil, which means we're being used on a Maybe;
	//  otherwise, the 'w' ptr should already be set, and we fill that memory location without allocating, as usual.
	doTemplate(`
		func (na *_{{ .Type | TypeSymbol }}__Assembler) BeginMap(sizeHint int) (ipld.MapAssembler, error) {
			switch *na.m {
			case schema.Maybe_Value, schema.Maybe_Null:
				panic("invalid state: cannot assign into assembler that's already finished")
			case midvalue:
				panic("invalid state: it makes no sense to 'begin' twice on the same assembler!")
			}
			*na.m = midvalue
			if sizeHint < 0 {
				sizeHint = 0
			}
			{{- if .Type | MaybeUsesPtr }}
			if na.w == nil {
				na.w = &_{{ .Type | TypeSymbol }}{}
			}
			{{- end}}
344
			na.w.m = make(map[_{{ .Type.KeyType | TypeSymbol }}]{{if .Type.ValueIsNullable }}Maybe{{else}}*_{{end}}{{ .Type.ValueType | TypeSymbol }}, sizeHint)
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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
			na.w.t = make([]_{{ .Type | TypeSymbol }}__entry, 0, sizeHint)
			return na, nil
		}
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) EmitNodeAssemblerMethodAssignNull(w io.Writer) {
	// DRY: this seems awfully similar -- almost exact, even -- amongst anything mapoid.  Can we extract?
	//  Might even be something we can turn into a util function, not just a template dry.  Only parameters are '*m', kind mixin, and type name.
	doTemplate(`
		func (na *_{{ .Type | TypeSymbol }}__Assembler) AssignNull() error {
			switch *na.m {
			case allowNull:
				*na.m = schema.Maybe_Null
				return nil
			case schema.Maybe_Absent:
				return mixins.MapAssembler{"{{ .PkgName }}.{{ .TypeName }}"}.AssignNull()
			case schema.Maybe_Value, schema.Maybe_Null:
				panic("invalid state: cannot assign into assembler that's already finished")
			case midvalue:
				panic("invalid state: cannot assign null into an assembler that's already begun working on recursive structures!")
			}
			panic("unreachable")
		}
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) EmitNodeAssemblerMethodAssignNode(w io.Writer) {
	// AssignNode goes through three phases:
	// 1. is it null?  Jump over to AssignNull (which may or may not reject it).
	// 2. is it our own type?  Handle specially -- we might be able to do efficient things.
	// 3. is it the right kind to morph into us?  Do so.
	//
	// We do not set m=midvalue in phase 3 -- it shouldn't matter unless you're trying to pull off concurrent access, which is wrong and unsafe regardless.
	//
	// DRY: this seems awfully similar -- almost exact, even -- amongst anything mapoid.  Can we extract?
	doTemplate(`
		func (na *_{{ .Type | TypeSymbol }}__Assembler) AssignNode(v ipld.Node) error {
			if v.IsNull() {
				return na.AssignNull()
			}
			if v2, ok := v.(*_{{ .Type | TypeSymbol }}); ok {
				switch *na.m {
				case schema.Maybe_Value, schema.Maybe_Null:
					panic("invalid state: cannot assign into assembler that's already finished")
				case midvalue:
					panic("invalid state: cannot assign null into an assembler that's already begun working on recursive structures!")
				}
				{{- if .Type | MaybeUsesPtr }}
				if na.w == nil {
					na.w = v2
					*na.m = schema.Maybe_Value
					return nil
				}
				{{- end}}
				*na.w = *v2
				*na.m = schema.Maybe_Value
				return nil
			}
			if v.ReprKind() != ipld.ReprKind_Map {
				return ipld.ErrWrongKind{TypeName: "{{ .PkgName }}.{{ .Type.Name }}", MethodName: "AssignNode", AppropriateKind: ipld.ReprKindSet_JustMap, ActualKind: v.ReprKind()}
			}
			itr := v.MapIterator()
			for !itr.Done() {
				k, v, err := itr.Next()
				if err != nil {
					return err
				}
				if err := na.AssembleKey().AssignNode(k); err != nil {
					return err
				}
				if err := na.AssembleValue().AssignNode(v); err != nil {
					return err
				}
			}
			return na.Finish()
		}
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) EmitNodeAssemblerOtherBits(w io.Writer) {
423 424
	g.emitMapAssemblerKeyTidyHelper(w)
	g.emitMapAssemblerValueTidyHelper(w)
425 426
	g.emitMapAssemblerMethods(w)
}
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
func (g mapBuilderGenerator) emitMapAssemblerKeyTidyHelper(w io.Writer) {
	// This function attempts to clean up the state machine to acknolwedge key assembly finish.
	//  If the child was finished and we just collected it, return true and update state to maState_expectValue.
	//   Collecting the child includes updating the 'ma.w.m' to point into the relevant row of 'ma.w.t', since that couldn't be done earlier,
	//    AND initializing the 'ma.va' (since we're already holding relevant offsets into 'ma.w.t').
	//  Otherwise, if it wasn't done, return false;
	//   and the caller is almost certain to emit an error momentarily.
	// The function will only be called when the current state is maState_midKey.
	//  (In general, the idea is that if the user is doing things correctly,
	//   this function will only be called when the child is in fact finished.)
	// Completion info always comes via 'cm', and we reset it to its initial condition of Maybe_Absent here.
	//  At the same time, we nil the 'w' pointer for the child assembler; otherwise its own state machine would probably let it modify 'w' again!
	doTemplate(`
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) keyFinishTidy() bool {
			switch ma.cm {
			case schema.Maybe_Value:
				ma.ka.w = nil
				tz := &ma.w.t[len(ma.w.t)-1]
				ma.cm = schema.Maybe_Absent
				ma.state = maState_expectValue
Eric Myhre's avatar
Eric Myhre committed
447
				ma.w.m[tz.k] = &tz.v
448 449 450 451 452 453 454 455 456 457
				{{- if .Type.ValueIsNullable }}
				{{- if not (MaybeUsesPtr .Type.ValueType) }}
				ma.va.w = &tz.v.v
				{{- end}}
				ma.va.m = &tz.v.m
				tz.v.m = allowNull
				{{- else}}
				ma.va.w = &tz.v
				ma.va.m = &ma.cm
				{{- end}}
458
				ma.ka.reset()
459 460 461 462 463 464 465 466 467
				return true
			default:
				return false
			}
		}
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) emitMapAssemblerValueTidyHelper(w io.Writer) {
	// This function attempts to clean up the state machine to acknolwedge child value assembly finish.
468 469 470 471 472 473 474 475 476 477 478
	//  If the child was finished and we just collected it, return true and update state to maState_initial.
	//  Otherwise, if it wasn't done, return false;
	//   and the caller is almost certain to emit an error momentarily.
	// The function will only be called when the current state is maState_midValue.
	//  (In general, the idea is that if the user is doing things correctly,
	//   this function will only be called when the child is in fact finished.)
	// If 'cm' is used, we reset it to its initial condition of Maybe_Absent here.
	//  At the same time, we nil the 'w' pointer for the child assembler; otherwise its own state machine would probably let it modify 'w' again!
	doTemplate(`
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) valueFinishTidy() bool {
			{{- if .Type.ValueIsNullable }}
479
			tz := &ma.w.t[len(ma.w.t)-1]
480
			switch tz.v.m {
481 482
			case schema.Maybe_Null:
				ma.state = maState_initial
483
				ma.va.reset()
484 485
				return true
			case schema.Maybe_Value:
486 487
				{{- if (MaybeUsesPtr .Type.ValueType) }}
				tz.v.v = ma.va.w
488 489
				{{- end}}
				ma.state = maState_initial
490
				ma.va.reset()
491 492
				return true
			{{- else}}
493
			switch ma.cm {
494 495 496 497
			case schema.Maybe_Value:
				ma.va.w = nil
				ma.cm = schema.Maybe_Absent
				ma.state = maState_initial
498
				ma.va.reset()
499
				return true
500 501 502 503 504 505 506 507 508 509
			{{- end}}
			default:
				return false
			}
		}
	`, w, g.AdjCfg, g)
}
func (g mapBuilderGenerator) emitMapAssemblerMethods(w io.Writer) {
	// FUTURE: some of the setup of the child assemblers could probably be DRY'd up.
	// DRY: a lot of the state transition fences again are common for all mapoids, and could probably even be a function over '*state'... crap, except for the valueFinishTidy function, which is definitely not extractable.
Eric Myhre's avatar
Eric Myhre committed
510 511 512 513
	// REVIEW: there's a copy-by-value of k2 that's avoidable.  But it simplifies the error path.  Worth working on?
	// REVIEW: processing the key via the reprStyle of the key if it's type kind isn't string is currently supported, but should it be?  or is that more confusing than valuable?
	//  Very possible that it shouldn't be supported: the full-on keyAssembler route won't accept this, so consistency with that might be best.
	//  On the other hand, lookups by string *do* support this kind of processing (and it must, or PathSegment utility becomes unacceptably damaged), so either way, something feels surprising.
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
	doTemplate(`
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) AssembleEntry(k string) (ipld.NodeAssembler, error) {
			switch ma.state {
			case maState_initial:
				// carry on
			case maState_midKey:
				panic("invalid state: AssembleEntry cannot be called when in the middle of assembling another key")
			case maState_expectValue:
				panic("invalid state: AssembleEntry cannot be called when expecting start of value assembly")
			case maState_midValue:
				if !ma.valueFinishTidy() {
					panic("invalid state: AssembleEntry cannot be called when in the middle of assembling a value")
				} // if tidy success: carry on
			case maState_finished:
				panic("invalid state: AssembleEntry cannot be called on an assembler that's already finished")
			}

Eric Myhre's avatar
Eric Myhre committed
531
			var k2 _{{ .Type.KeyType | TypeSymbol }}
532
			{{- if eq .Type.KeyType.Kind.String "String" }}
Eric Myhre's avatar
Eric Myhre committed
533 534 535
			if err := (_{{ .Type.KeyType | TypeSymbol }}__Style{}).fromString(&k2, k); err != nil {
				return nil, err // TODO wrap in some kind of ErrInvalidKey
			}
536
			{{- else}}
Eric Myhre's avatar
Eric Myhre committed
537 538 539
			if err := (_{{ .Type.KeyType | TypeSymbol }}__ReprStyle{}).fromString(&k2, k); err != nil {
				return nil, err // TODO wrap in some kind of ErrInvalidKey
			}
540 541
			{{- end}}
			if _, exists := ma.w.m[k2]; exists {
Eric Myhre's avatar
Eric Myhre committed
542
				return nil, ipld.ErrRepeatedMapKey{&k2}
543 544
			}
			ma.w.t = append(ma.w.t, _{{ .Type | TypeSymbol }}__entry{k: k2})
545
			tz := &ma.w.t[len(ma.w.t)-1]
546 547
			ma.state = maState_midValue

Eric Myhre's avatar
Eric Myhre committed
548
			ma.w.m[k2] = &tz.v
549
			{{- if .Type.ValueIsNullable }}
550 551 552 553 554
			{{- if not (MaybeUsesPtr .Type.ValueType) }}
			ma.va.w = &tz.v.v
			{{- end}}
			ma.va.m = &tz.v.m
			tz.v.m = allowNull
555
			{{- else}}
556
			ma.va.w = &tz.v
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
			ma.va.m = &ma.cm
			{{- end}}
			return &ma.va, nil
		}
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) AssembleKey() ipld.NodeAssembler {
			switch ma.state {
			case maState_initial:
				// carry on
			case maState_midKey:
				panic("invalid state: AssembleKey cannot be called when in the middle of assembling another key")
			case maState_expectValue:
				panic("invalid state: AssembleKey cannot be called when expecting start of value assembly")
			case maState_midValue:
				if !ma.valueFinishTidy() {
					panic("invalid state: AssembleKey cannot be called when in the middle of assembling a value")
				} // if tidy success: carry on
			case maState_finished:
				panic("invalid state: AssembleKey cannot be called on an assembler that's already finished")
			}
576
			ma.w.t = append(ma.w.t, _{{ .Type | TypeSymbol }}__entry{})
577
			ma.state = maState_midKey
578 579
			ma.ka.m = &ma.cm
			ma.ka.w = &ma.w.t[len(ma.w.t)-1].k
580
			return &ma.ka
581 582 583 584 585 586
		}
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) AssembleValue() ipld.NodeAssembler {
			switch ma.state {
			case maState_initial:
				panic("invalid state: AssembleValue cannot be called when no key is primed")
			case maState_midKey:
587 588 589
				if !ma.keyFinishTidy() {
					panic("invalid state: AssembleValue cannot be called when in the middle of assembling a key")
				} // if tidy success: carry on
590 591 592 593 594 595 596 597
			case maState_expectValue:
				// carry on
			case maState_midValue:
				panic("invalid state: AssembleValue cannot be called when in the middle of assembling another value")
			case maState_finished:
				panic("invalid state: AssembleValue cannot be called on an assembler that's already finished")
			}
			ma.state = maState_midValue
598
			return &ma.va
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
		}
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) Finish() error {
			switch ma.state {
			case maState_initial:
				// carry on
			case maState_midKey:
				panic("invalid state: Finish cannot be called when in the middle of assembling a key")
			case maState_expectValue:
				panic("invalid state: Finish cannot be called when expecting start of value assembly")
			case maState_midValue:
				if !ma.valueFinishTidy() {
					panic("invalid state: Finish cannot be called when in the middle of assembling a value")
				} // if tidy success: carry on
			case maState_finished:
				panic("invalid state: Finish cannot be called on an assembler that's already finished")
			}
			ma.state = maState_finished
			*ma.m = schema.Maybe_Value
			return nil
		}
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) KeyStyle() ipld.NodeStyle {
			return _{{ .Type.KeyType | TypeSymbol }}__Style{}
		}
		func (ma *_{{ .Type | TypeSymbol }}__Assembler) ValueStyle(_ string) ipld.NodeStyle {
			return _{{ .Type.ValueType | TypeSymbol }}__Style{}
		}
	`, w, g.AdjCfg, g)
}