From 26fd14455dab649a254c5e4f32a40bcd9ca20f9d Mon Sep 17 00:00:00 2001 From: Alexander Wang Date: Wed, 17 Apr 2024 15:55:39 -0700 Subject: [PATCH] d2ir: fix substitutions in imports --- ci/release/changelogs/next.md | 1 + d2ir/compile.go | 5 ++--- d2ir/import.go | 11 +++-------- .../d2compiler/TestCompile/vars-in-imports.exp.json | 2 +- 4 files changed, 7 insertions(+), 12 deletions(-) diff --git a/ci/release/changelogs/next.md b/ci/release/changelogs/next.md index 498d06ed6..58fe48b56 100644 --- a/ci/release/changelogs/next.md +++ b/ci/release/changelogs/next.md @@ -6,3 +6,4 @@ - Fix executable plugins that implement standalone router [#1910](https://github.com/terrastruct/d2/pull/1910) - Fix compiler error with multiple nested spread substitutions [#1913](https://github.com/terrastruct/d2/pull/1913) +- Fix substitutions from imports into different scopes [#1914](https://github.com/terrastruct/d2/pull/1914) diff --git a/d2ir/compile.go b/d2ir/compile.go index 995f48432..273637a9d 100644 --- a/d2ir/compile.go +++ b/d2ir/compile.go @@ -31,8 +31,7 @@ type compiler struct { imports []string // importStack is used to detect cyclic imports. importStack []string - // importCache enables reuse of files imported multiple times. - importCache map[string]*Map + seenImports map[string]struct{} utf16Pos bool // Stack of globs that must be recomputed at each new object in and below the current scope. @@ -62,7 +61,7 @@ func Compile(ast *d2ast.Map, opts *CompileOptions) (*Map, []string, error) { err: &d2parser.ParseError{}, fs: opts.FS, - importCache: make(map[string]*Map), + seenImports: make(map[string]struct{}), utf16Pos: opts.UTF16Pos, } m := &Map{} diff --git a/d2ir/import.go b/d2ir/import.go index b933298dd..c415cf138 100644 --- a/d2ir/import.go +++ b/d2ir/import.go @@ -82,16 +82,11 @@ func (c *compiler) __import(imp *d2ast.Import) (*Map, bool) { // Only get immediate imports. if len(c.importStack) == 2 { - if _, ok := c.importCache[impPath]; !ok { + if _, ok := c.seenImports[impPath]; !ok { c.imports = append(c.imports, imp.PathWithPre()) } } - ir, ok := c.importCache[impPath] - if ok { - return ir, true - } - var f fs.File var err error if c.fs == nil { @@ -113,13 +108,13 @@ func (c *compiler) __import(imp *d2ast.Import) (*Map, bool) { return nil, false } - ir = &Map{} + ir := &Map{} ir.initRoot() ir.parent.(*Field).References[0].Context_.Scope = ast c.compileMap(ir, ast, ast) - c.importCache[impPath] = ir + c.seenImports[impPath] = struct{}{} return ir, true } diff --git a/testdata/d2compiler/TestCompile/vars-in-imports.exp.json b/testdata/d2compiler/TestCompile/vars-in-imports.exp.json index 31dc0f878..05c63f5e3 100644 --- a/testdata/d2compiler/TestCompile/vars-in-imports.exp.json +++ b/testdata/d2compiler/TestCompile/vars-in-imports.exp.json @@ -371,7 +371,7 @@ ], "attributes": { "label": { - "value": "Dev Environment" + "value": "Qa Environment" }, "labelDimensions": { "width": 0,