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
This commit is contained in:
Barry Nolte 2023-08-04 12:31:36 -07:00
parent 5436cb6b5f
commit 9b463d5c9f
No known key found for this signature in database
GPG key ID: 97D97D823FB7D867

View file

@ -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,