From 9b463d5c9f7cbd2f9522b37c1cc3a43ebbe44a3c Mon Sep 17 00:00:00 2001 From: Barry Nolte Date: Fri, 4 Aug 2023 12:31:36 -0700 Subject: [PATCH] d2-vscode LanguageServerChanges These changes are for the language server in d2-vscode. When the D2_LSP_MODE environment variable is set, the d2 cli will read the d2 file, produce the ast (and possible errors), convert it to JSON, print it out to stdout, then terminate. This was done this way to keep the changes to the d2 cli code to a minimum. PR for d2-vscode to come after this is accepted --- d2compiler/compile.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/d2compiler/compile.go b/d2compiler/compile.go index f777ff3dd..dc3d87e1c 100644 --- a/d2compiler/compile.go +++ b/d2compiler/compile.go @@ -1,11 +1,13 @@ package d2compiler import ( + "encoding/json" "encoding/xml" "fmt" "io" "io/fs" "net/url" + "os" "strconv" "strings" @@ -27,18 +29,46 @@ type CompileOptions struct { FS fs.FS } +// Changes for Language Server 'mode' +type LspOutputData struct { + Ast *d2ast.Map + Err error +} + +var lod LspOutputData + +func LspOutput(m bool) { + if !m { + return + } + + jsonOutput, _ := json.Marshal(lod) + fmt.Print(string(jsonOutput)) + os.Exit(42) +} + func Compile(p string, r io.Reader, opts *CompileOptions) (*d2graph.Graph, *d2target.Config, error) { if opts == nil { opts = &CompileOptions{} } + lspMode := os.Getenv("D2_LSP_MODE") == "1" + defer LspOutput(lspMode) + ast, err := d2parser.Parse(p, r, &d2parser.ParseOptions{ UTF16Pos: opts.UTF16Pos, }) + + lod.Ast = ast if err != nil { + lod.Err = err return nil, nil, err } + if lspMode { + return nil, nil, nil + } + ir, err := d2ir.Compile(ast, &d2ir.CompileOptions{ UTF16Pos: opts.UTF16Pos, FS: opts.FS,