cue/ast: sort CommentGroups by position when adding

This is generally a good idea, as the formatter won't
format properly. Until now this was the responsibility
of the user, but for the textproto decoder this is a
bit tricky.

Change-Id: I64c8aaa1f40e75098f98df3a0f5e1cd04355276e
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/9188
Reviewed-by: CUE cueckoo <cueckoo@gmail.com>
Reviewed-by: Paul Jolly <paul@myitcv.org.uk>
diff --git a/cue/ast/ast.go b/cue/ast/ast.go
index 4bab829..5d58698 100644
--- a/cue/ast/ast.go
+++ b/cue/ast/ast.go
@@ -163,7 +163,12 @@
 		c.groups = &a
 		return
 	}
+
 	*c.groups = append(*c.groups, cg)
+	a := *c.groups
+	for i := len(a) - 2; i >= 0 && a[i].Position > cg.Position; i-- {
+		a[i], a[i+1] = a[i+1], a[i]
+	}
 }
 
 func (c *comments) SetComments(cgs []*CommentGroup) {
diff --git a/encoding/protobuf/testdata/istio.io/api/cue.mod/gen/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor_proto_gen.cue b/encoding/protobuf/testdata/istio.io/api/cue.mod/gen/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor_proto_gen.cue
index 6f068cd..4cd99e6 100644
--- a/encoding/protobuf/testdata/istio.io/api/cue.mod/gen/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor_proto_gen.cue
+++ b/encoding/protobuf/testdata/istio.io/api/cue.mod/gen/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor_proto_gen.cue
@@ -150,6 +150,8 @@
 // Describes a field within a message.
 #FieldDescriptorProto: {
 	#Type:
+		// 0 is reserved for errors.
+		// Order is weird for historical reasons.
 		"TYPE_DOUBLE" |
 		"TYPE_FLOAT" |
 
@@ -180,9 +182,6 @@
 		"TYPE_SFIXED32" |
 		"TYPE_SFIXED64" |
 		"TYPE_SINT32" | // Uses ZigZag encoding.
-
-		// 0 is reserved for errors.
-		// Order is weird for historical reasons.
 		"TYPE_SINT64" // Uses ZigZag encoding.
 
 	#Type_value: {