diff --git a/d2cli/main.go b/d2cli/main.go index 02ef4f3a9..f879bf6d8 100644 --- a/d2cli/main.go +++ b/d2cli/main.go @@ -2,6 +2,7 @@ package d2cli import ( "context" + "encoding/json" "errors" "fmt" "io" @@ -21,6 +22,7 @@ import ( "oss.terrastruct.com/util-go/go2" "oss.terrastruct.com/util-go/xmain" + "oss.terrastruct.com/d2/d2ast" "oss.terrastruct.com/d2/d2graph" "oss.terrastruct.com/d2/d2lib" "oss.terrastruct.com/d2/d2parser" @@ -430,6 +432,26 @@ func compile(ctx context.Context, ms *xmain.State, plugins []d2plugin.Plugin, fs FS: fs, } + if os.Getenv("D2_LSP_MODE") == "1" { + // only the parse result is needed if running d2 for lsp + ast, err := d2lib.Parse(ctx, string(input), opts) + if err != nil { + return nil, false, err + } + + type LspOutputData struct { + Ast *d2ast.Map + Err error + } + jsonOutput, err := json.Marshal(LspOutputData{Ast: ast, Err: err}) + if err != nil { + return nil, false, err + } + fmt.Print(string(jsonOutput)) + os.Exit(42) + return nil, false, nil + } + cancel := background.Repeat(func() { ms.Log.Info.Printf("compiling & running layout algorithms...") }, time.Second*5) diff --git a/d2lib/d2.go b/d2lib/d2.go index 3713d5967..50d64945a 100644 --- a/d2lib/d2.go +++ b/d2lib/d2.go @@ -7,11 +7,13 @@ import ( "os" "strings" + "oss.terrastruct.com/d2/d2ast" "oss.terrastruct.com/d2/d2compiler" "oss.terrastruct.com/d2/d2exporter" "oss.terrastruct.com/d2/d2graph" "oss.terrastruct.com/d2/d2layouts" "oss.terrastruct.com/d2/d2layouts/d2dagrelayout" + "oss.terrastruct.com/d2/d2parser" "oss.terrastruct.com/d2/d2renderers/d2fonts" "oss.terrastruct.com/d2/d2renderers/d2svg" "oss.terrastruct.com/d2/d2target" @@ -40,6 +42,17 @@ type CompileOptions struct { InputPath string } +func Parse(ctx context.Context, input string, compileOpts *CompileOptions) (*d2ast.Map, error) { + if compileOpts == nil { + compileOpts = &CompileOptions{} + } + + ast, err := d2parser.Parse(compileOpts.InputPath, strings.NewReader(input), &d2parser.ParseOptions{ + UTF16Pos: compileOpts.UTF16Pos, + }) + return ast, err +} + func Compile(ctx context.Context, input string, compileOpts *CompileOptions, renderOpts *d2svg.RenderOpts) (*d2target.Diagram, *d2graph.Graph, error) { if compileOpts == nil { compileOpts = &CompileOptions{}