# Tests various patterns of insertion of conjuncts.
# See https://cuelang.org/issues/2169
-- a.cue --
embeddingDirect: t1: ({
	#a: _
	_
} & {
	#a: "s"
	#a
}) @test(eq, {"s", #a: "s"})

embeddingExpr: t1: ({
	#a: _
	_
} & {
	#a: "s"
	[ #a ][0]
}) @test(eq, {"s", #a: "s"})

unifiedDirect: {
	t1: {
		#a: _
		_
	}
	t1: {
		#a
		#a: _
	}
	t1: {
		_
		#a: "s"
	}
} @test(eq, {t1: {"s", #a: "s"}})


unifiedExpr: {
	t1: {
		#a: _
		_
	}
	t1: {
		[ #a ][0]
		#a: _
	}
	t1: {
		#a: "s"
		_
	}
} @test(eq, {t1: {"s", #a: "s"}})

// These two embeddings both add fields to each other's original source, which
// then, in turn, needs to be added.
cross: t1: {
	a: {
		b: {v: 1, a: w: 2}
		// from b.a: {x: 2, b: y: 5}
	}
	b: {
		a: {x: 2, b: y: 5}
		// from a.b: {v: 1, a: v: 2}
	}
	a
	b
} @test(eq, {
	a: {b: {v: 1, a: w: 2, y: 5}, x: 2, w: 2}
	b: {a: {x: 2, b: y: 5, w: 2}, v: 1, y: 5}
	v: 1
	w: 2
	x: 2
	y: 5
})

-- complex.cue --
// Multiple levels of insertion
recursive: {
	t1: {
		e: {}
		c: d: e: f: 1
		c.d
		c: d:
			// This part gets embedded within t1, which ends up adding new fields
			// to here, when then again need to be embedded in t1, which then
			// will add more fields to node e.
			c: d: e: g: 1
	}
	t2: {
		c
		c: c: g: 1
	}
} @test(eq, {
	t1: {
		e: {f: 1, g: 1}
		c: d: {
			e: {f: 1, g: 1}
			c: d: e: g: 1
		}
	}
	t2: {
		c: {c: g: 1, g: 1}
		g: 1
	}
})

-- issue2169.cue --
// Evaluator regression where "cannot add field $X: was already used" errors
// appeared incorrectly when a field was referenced before being defined.
// https://cuelang.org/issue/2169
embeddedFunctionalExpr: {
	#fn: {
		#in: _
		_
	} & {
		#in: "str"

		({
			#t: _
			#t
		} & {
			#t: #in
			_
		}) + ""
	}
	#fn
} @test(eq, {"str", #fn: {"str", #in: "str"}, #in: "str"})
-- out/eval/stats --
Leaks:  0
Freed:  67
Reused: 45
Allocs: 22
Retain: 0

Unifications: 63
Conjuncts:    155
Disjuncts:    0
Notifications: 13

NumCloseIDs: 54
