Skip to content

Commit

Permalink
Language server refactoring
Browse files Browse the repository at this point in the history
While there's more to do here, we've got to start somewhere.

- Simplify handlers by extracting shared logic
- Use "global" vars for static slices to avoid needless allocations
- No named return values
- Add GetContentAndModule convenience function to reduce boilerplate
- Various fixes

This should not change behavior of anything, just nake server.go
a little more manageable.

Signed-off-by: Anders Eknert <[email protected]>
  • Loading branch information
anderseknert committed Jan 18, 2025
1 parent 93faa40 commit 18f7f12
Show file tree
Hide file tree
Showing 4 changed files with 198 additions and 375 deletions.
14 changes: 14 additions & 0 deletions internal/lsp/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ func (c *Cache) SetModule(fileURI string, module *ast.Module) {
c.modules.Set(fileURI, module)
}

func (c *Cache) GetContentAndModule(fileURI string) (string, *ast.Module, bool) {
content, ok := c.GetFileContents(fileURI)
if !ok {
return "", nil, false
}

module, ok := c.GetModule(fileURI)
if !ok {
return "", nil, false
}

return content, module, true
}

func (c *Cache) Rename(oldKey, newKey string) {
if content, ok := c.fileContents.Get(oldKey); ok {
c.fileContents.Set(newKey, content)
Expand Down
44 changes: 44 additions & 0 deletions internal/lsp/handler/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package handler

import (
"context"

"github.com/anderseknert/roast/pkg/encoding"
"github.com/sourcegraph/jsonrpc2"
)

type handlerFunc[T any] func(T) (any, error)

type handlerContextFunc[T any] func(context.Context, T) (any, error)

var ErrInvalidParams = &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}

func Decode[T any](req *jsonrpc2.Request, params *T) error {
if req.Params == nil {
return ErrInvalidParams
}

if err := encoding.JSON().Unmarshal(*req.Params, &params); err != nil {
return &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams, Message: err.Error()}
}

return nil
}

func WithParams[T any](req *jsonrpc2.Request, h handlerFunc[T]) (any, error) {
var params T
if err := Decode(req, &params); err != nil {
return nil, err
}

return h(params)
}

func WithContextAndParams[T any](ctx context.Context, req *jsonrpc2.Request, h handlerContextFunc[T]) (any, error) {
var params T
if err := Decode(req, &params); err != nil {
return nil, err
}

return h(ctx, params)
}
Loading

0 comments on commit 18f7f12

Please sign in to comment.