cue: fix file offsets for shared builtins

Change-Id: I289e1b7fe9ba17f6aedbb9346db6223e8ac59b02
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/1921
Reviewed-by: Marcel van Lohuizen <mpvl@google.com>
diff --git a/cue/build.go b/cue/build.go
index ba247f4..d0ee27a 100644
--- a/cue/build.go
+++ b/cue/build.go
@@ -75,11 +75,18 @@
 	freeze bool
 }
 
+const sharedOffset = 0x40000000
+
 // sharedIndex is used for indexing builtins and any other labels common to
 // all instances.
 var sharedIndex = newSharedIndex(token.NewFileSet())
 
 func newSharedIndex(f *token.FileSet) *index {
+	// TODO: nasty hack to indicate FileSet of shared index. Remove the whole
+	// FileSet idea from the API. Just take the hit of the extra pointers for
+	// positions in the ast, and then optimize the storage in an abstract
+	// machine implementation for storing graphs.
+	f.AddFile("dummy", sharedOffset, 0)
 	i := &index{
 		fset:     f,
 		labelMap: map[string]label{"": 0},
diff --git a/cue/builtin.go b/cue/builtin.go
index fa7e927..0751b1c 100644
--- a/cue/builtin.go
+++ b/cue/builtin.go
@@ -61,7 +61,7 @@
 	cue    string
 }
 
-func mustCompileBuiltins(ctx *context, p *builtinPkg) *structLit {
+func mustCompileBuiltins(ctx *context, p *builtinPkg, name string) *structLit {
 	obj := &structLit{}
 	for _, b := range p.native {
 		f := ctx.label(b.Name, false) // never starts with _
@@ -76,7 +76,7 @@
 
 	// Parse builtin CUE
 	if p.cue != "" {
-		expr, err := parser.ParseExpr(ctx.index.fset, "<builtinPkg>", p.cue)
+		expr, err := parser.ParseExpr(ctx.index.fset, name, p.cue)
 		if err != nil {
 			fmt.Println(p.cue)
 			panic(err)
@@ -232,7 +232,7 @@
 func initBuiltins(pkgs map[string]*builtinPkg) {
 	ctx := sharedIndex.newContext()
 	for k, b := range pkgs {
-		e := mustCompileBuiltins(ctx, b)
+		e := mustCompileBuiltins(ctx, b, k)
 		builtins[k] = e
 		builtins["-/"+path.Base(k)] = e
 	}
diff --git a/cue/errors.go b/cue/errors.go
index 6294d03..f15927a 100644
--- a/cue/errors.go
+++ b/cue/errors.go
@@ -89,7 +89,10 @@
 
 func appendPositions(pos []token.Position, fset *token.FileSet, src source) []token.Position {
 	if src != nil {
-		if src.Pos() != token.NoPos {
+		if p := src.Pos(); p != token.NoPos {
+			if p >= sharedOffset {
+				fset = sharedIndex.fset
+			}
 			return append(pos, fset.Position(src.Pos()))
 		}
 		if c := src.computed(); c != nil {
@@ -119,7 +122,10 @@
 
 func appendLocations(locs []string, fset *token.FileSet, src source) []string {
 	if src != nil {
-		if src.Pos() != token.NoPos {
+		if p := src.Pos(); p != token.NoPos {
+			if p >= sharedOffset {
+				fset = sharedIndex.fset
+			}
 			return append(locs, fset.Position(src.Pos()).String())
 		}
 		if c := src.computed(); c != nil {