clerk/internal/lsp/textdocument_rename.go (view raw)
Oleksandr Smirnov
Oleksandr Smirnov
olexsmir@gmail.com perf: lsp: index-driven rename edits..., 1 month ago
olexsmir@gmail.com perf: lsp: index-driven rename edits..., 1 month ago
| 1 | package lsp |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "sort" |
| 7 | "strings" |
| 8 | |
| 9 | "go.lsp.dev/protocol" |
| 10 | "go.lsp.dev/uri" |
| 11 | |
| 12 | "olexsmir.xyz/clerk/internal/analyzer" |
| 13 | "olexsmir.xyz/clerk/internal/lsp/lsputil" |
| 14 | "olexsmir.xyz/clerk/journal/ast" |
| 15 | "olexsmir.xyz/clerk/journal/token" |
| 16 | ) |
| 17 | |
| 18 | func (s *server) PrepareRename(_ context.Context, params *protocol.PrepareRenameParams) (protocol.PrepareRenameResult, error) { |
| 19 | state, ok := s.getDocState(params.TextDocument.URI) |
| 20 | if !ok { |
| 21 | return nil, nil |
| 22 | } |
| 23 | |
| 24 | an := s.analysisFor(params.TextDocument.URI) |
| 25 | cursor := state.lineIdx.Offset(int(params.Position.Line), int(params.Position.Character)) |
| 26 | ref := findSymbolUnderCursor(an, params.TextDocument.URI.Path(), state.text, cursor) |
| 27 | if ref == nil { |
| 28 | return nil, nil |
| 29 | } |
| 30 | |
| 31 | return &protocol.PrepareRenamePlaceholder{ |
| 32 | Range: state.lineIdx.SpanRange(ref.span), |
| 33 | Placeholder: ref.name, |
| 34 | }, nil |
| 35 | } |
| 36 | |
| 37 | func (s *server) Rename(_ context.Context, params *protocol.RenameParams) (*protocol.WorkspaceEdit, error) { |
| 38 | state, ok := s.getDocState(params.TextDocument.URI) |
| 39 | if !ok { |
| 40 | return nil, nil |
| 41 | } |
| 42 | |
| 43 | an := s.analysisFor(params.TextDocument.URI) |
| 44 | cursor := state.lineIdx.Offset(int(params.Position.Line), int(params.Position.Character)) |
| 45 | ref := findSymbolUnderCursor(an, params.TextDocument.URI.Path(), state.text, cursor) |
| 46 | if ref == nil { |
| 47 | return nil, nil |
| 48 | } |
| 49 | |
| 50 | switch ref.kind { |
| 51 | case symbolAccount: |
| 52 | if err := validateAccountName(params.NewName); err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | case symbolCommodity: |
| 56 | if err := validateCommodityName(params.NewName); err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | case symbolPayee: |
| 60 | if err := validatePayeeName(params.NewName); err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | case symbolTag: |
| 64 | if err := validateTagName(params.NewName); err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | default: |
| 68 | return nil, nil |
| 69 | } |
| 70 | |
| 71 | changes := renameChanges(an, ref, params.NewName, state.lineIdx) |
| 72 | if len(changes) == 0 { |
| 73 | return nil, nil |
| 74 | } |
| 75 | return &protocol.WorkspaceEdit{Changes: changes}, nil |
| 76 | } |
| 77 | |
| 78 | func findSymbolUnderCursor(an *analyzer.Analysis, docPath, content string, cursor int) *symbolRef { |
| 79 | for _, pf := range an.Files { |
| 80 | if pf.Path != docPath { |
| 81 | continue |
| 82 | } |
| 83 | if entry := entryAt(pf.Ast.Entries, cursor); entry != nil { |
| 84 | return symbolInEntry(content, entry, cursor) |
| 85 | } |
| 86 | return nil |
| 87 | } |
| 88 | return nil |
| 89 | } |
| 90 | |
| 91 | func symbolInEntry(content string, e ast.Entry, cursor int) *symbolRef { |
| 92 | switch e := e.(type) { |
| 93 | case *ast.Transaction: |
| 94 | if e.Payee != nil && spanContains(content, e.Payee.Span, cursor) { |
| 95 | return &symbolRef{symbolPayee, e.Payee.Name, e.Payee.Span} |
| 96 | } |
| 97 | if ref := tagRefInComment(content, e.Comment, cursor); ref != nil { |
| 98 | return ref |
| 99 | } |
| 100 | for _, c := range e.HeaderComments { |
| 101 | if ref := tagRefInComment(content, c, cursor); ref != nil { |
| 102 | return ref |
| 103 | } |
| 104 | } |
| 105 | return symbolInPostings(content, e.Postings, cursor) |
| 106 | case *ast.PeriodicTransaction: |
| 107 | if ref := tagRefInComment(content, e.Comment, cursor); ref != nil { |
| 108 | return ref |
| 109 | } |
| 110 | for _, c := range e.HeaderComments { |
| 111 | if ref := tagRefInComment(content, c, cursor); ref != nil { |
| 112 | return ref |
| 113 | } |
| 114 | } |
| 115 | return symbolInPostings(content, e.Postings, cursor) |
| 116 | case *ast.AutomatedTransaction: |
| 117 | if ref := tagRefInComment(content, e.Comment, cursor); ref != nil { |
| 118 | return ref |
| 119 | } |
| 120 | for _, c := range e.HeaderComments { |
| 121 | if ref := tagRefInComment(content, c, cursor); ref != nil { |
| 122 | return ref |
| 123 | } |
| 124 | } |
| 125 | return symbolInPostings(content, e.Postings, cursor) |
| 126 | case *ast.Comment: |
| 127 | return tagRefInComment(content, e, cursor) |
| 128 | case *ast.AccountDirective: |
| 129 | if spanContains(content, e.Account.Span, cursor) { |
| 130 | return &symbolRef{symbolAccount, e.Account.String(), e.Account.Span} |
| 131 | } |
| 132 | for _, sd := range e.Subdirectives { |
| 133 | if sd.Name == "alias" && spanContains(content, sd.ValueSpan, cursor) { |
| 134 | return &symbolRef{symbolAccount, sd.Value, sd.ValueSpan} |
| 135 | } |
| 136 | } |
| 137 | case *ast.AliasDirective: |
| 138 | if spanContains(content, e.From.Span, cursor) { |
| 139 | return &symbolRef{symbolAccount, e.From.String(), e.From.Span} |
| 140 | } |
| 141 | if spanContains(content, e.To.Span, cursor) { |
| 142 | return &symbolRef{symbolAccount, e.To.String(), e.To.Span} |
| 143 | } |
| 144 | case *ast.CommodityDirective: |
| 145 | if spanContains(content, e.CommoditySpan, cursor) { |
| 146 | return &symbolRef{symbolCommodity, e.Commodity, e.CommoditySpan} |
| 147 | } |
| 148 | case *ast.PayeeDirective: |
| 149 | if e.Name != nil && spanContains(content, e.Name.Span, cursor) { |
| 150 | return &symbolRef{symbolPayee, e.Name.Name, e.Name.Span} |
| 151 | } |
| 152 | } |
| 153 | return nil |
| 154 | } |
| 155 | |
| 156 | // symbolKind is the kind of symbol under the cursor. |
| 157 | type symbolKind int |
| 158 | |
| 159 | const ( |
| 160 | symbolAccount symbolKind = iota |
| 161 | symbolCommodity |
| 162 | symbolPayee |
| 163 | symbolTag |
| 164 | ) |
| 165 | |
| 166 | func (s symbolKind) ToProtocol() protocol.SymbolKind { |
| 167 | switch s { |
| 168 | case symbolAccount: |
| 169 | return protocol.SymbolKindClass |
| 170 | case symbolCommodity: |
| 171 | return protocol.SymbolKindVariable |
| 172 | case symbolPayee: |
| 173 | return protocol.SymbolKindObject |
| 174 | case symbolTag: |
| 175 | return protocol.SymbolKindProperty |
| 176 | } |
| 177 | return protocol.SymbolKindFile |
| 178 | } |
| 179 | |
| 180 | // symbolRef is a symbol under the cursor, ready to be resolved or renamed. |
| 181 | type symbolRef struct { |
| 182 | kind symbolKind |
| 183 | name string |
| 184 | span token.Span |
| 185 | } |
| 186 | |
| 187 | // renameTo returns the replacement rext for an occurrence of the nodeKind with the given name. |
| 188 | func (ref *symbolRef) renameTo(nodeKind symbolKind, name, newName string) (text string, renamed bool) { |
| 189 | if ref.kind != nodeKind { |
| 190 | return "", false |
| 191 | } |
| 192 | if ref.kind == symbolAccount { |
| 193 | if !accountMatches(name, ref.name) { |
| 194 | return "", false |
| 195 | } |
| 196 | return newName + strings.TrimPrefix(name, ref.name), true |
| 197 | } |
| 198 | if name != ref.name { |
| 199 | return "", false |
| 200 | } |
| 201 | return newName, true |
| 202 | } |
| 203 | |
| 204 | func accountMatches(name, old string) bool { |
| 205 | return name == old || strings.HasPrefix(name, old+":") |
| 206 | } |
| 207 | |
| 208 | func tagRefInComment(content string, c *ast.Comment, cursor int) *symbolRef { |
| 209 | if c == nil { |
| 210 | return nil |
| 211 | } |
| 212 | for i := range c.Tags { |
| 213 | t := &c.Tags[i] |
| 214 | if span := tagKeySpan(content, t); spanContains(content, span, cursor) { |
| 215 | return &symbolRef{symbolTag, t.Key, span} |
| 216 | } |
| 217 | } |
| 218 | return nil |
| 219 | } |
| 220 | |
| 221 | func commodityRef(content string, am *ast.Amount, cursor int) *symbolRef { |
| 222 | if am == nil || am.Commodity == "" || !spanContains(content, am.CommoditySpan, cursor) { |
| 223 | return nil |
| 224 | } |
| 225 | return &symbolRef{symbolCommodity, am.Commodity, am.CommoditySpan} |
| 226 | } |
| 227 | |
| 228 | func symbolInPostings(content string, postings []*ast.Posting, cursor int) *symbolRef { |
| 229 | for _, p := range postings { |
| 230 | if spanContains(content, p.Account.Span, cursor) { |
| 231 | return &symbolRef{symbolAccount, p.Account.String(), p.Account.Span} |
| 232 | } |
| 233 | if ref := commodityRef(content, p.Amount, cursor); ref != nil { |
| 234 | return ref |
| 235 | } |
| 236 | if p.Cost != nil { |
| 237 | if ref := commodityRef(content, &p.Cost.Amount, cursor); ref != nil { |
| 238 | return ref |
| 239 | } |
| 240 | } |
| 241 | if p.Balance != nil { |
| 242 | if ref := commodityRef(content, &p.Balance.Amount, cursor); ref != nil { |
| 243 | return ref |
| 244 | } |
| 245 | } |
| 246 | if ref := tagRefInComment(content, p.Comment, cursor); ref != nil { |
| 247 | return ref |
| 248 | } |
| 249 | for i := range p.Comments { |
| 250 | if ref := tagRefInComment(content, &p.Comments[i], cursor); ref != nil { |
| 251 | return ref |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | return nil |
| 256 | } |
| 257 | |
| 258 | func renameChanges(an *analyzer.Analysis, ref *symbolRef, newName string, primaryLI *lsputil.LineIndex) map[uri.URI][]protocol.TextEdit { |
| 259 | type fileEdits struct { |
| 260 | li *lsputil.LineIndex |
| 261 | edits []protocol.TextEdit |
| 262 | } |
| 263 | files := make(map[int]*fileEdits) |
| 264 | add := func(fileIdx int, span token.Span, text string) { |
| 265 | fe := files[fileIdx] |
| 266 | if fe == nil { |
| 267 | fe = &fileEdits{} |
| 268 | if fileIdx == 0 { |
| 269 | fe.li = primaryLI |
| 270 | } else { |
| 271 | fe.li = lsputil.NewLineIndex(string(an.Files[fileIdx].Src)) |
| 272 | } |
| 273 | files[fileIdx] = fe |
| 274 | } |
| 275 | fe.edits = append(fe.edits, protocol.TextEdit{ |
| 276 | Range: fe.li.SpanRange(span), |
| 277 | NewText: text, |
| 278 | }) |
| 279 | } |
| 280 | |
| 281 | switch ref.kind { |
| 282 | case symbolAccount: |
| 283 | renameAccountEdits(an, ref, newName, add) |
| 284 | case symbolCommodity: |
| 285 | renameCommodityEdits(an, ref, newName, add) |
| 286 | case symbolPayee: |
| 287 | renamePayeeEdits(an, ref, newName, add) |
| 288 | case symbolTag: |
| 289 | renameTagEdits(an, ref, newName, add) |
| 290 | } |
| 291 | |
| 292 | changes := make(map[uri.URI][]protocol.TextEdit, len(files)) |
| 293 | for fileIdx, fe := range files { |
| 294 | changes[uri.File(an.Files[fileIdx].Path)] = fe.edits |
| 295 | } |
| 296 | sortAndDedup(changes) |
| 297 | return changes |
| 298 | } |
| 299 | |
| 300 | func renameAccountEdits(an *analyzer.Analysis, ref *symbolRef, newName string, add func(int, token.Span, string)) { |
| 301 | for _, name := range an.AccountNames { |
| 302 | if !accountMatches(name, ref.name) { |
| 303 | continue |
| 304 | } |
| 305 | info := an.Accounts[name] |
| 306 | text := newName + strings.TrimPrefix(name, ref.name) |
| 307 | for _, u := range info.Usages { |
| 308 | add(u.FileIndex, u.Posting.Account.Span, text) |
| 309 | } |
| 310 | } |
| 311 | for _, info := range an.Accounts { |
| 312 | for _, d := range info.Directives { |
| 313 | fileIdx := fileIndexForEntry(an, d) |
| 314 | if fileIdx < 0 { |
| 315 | continue |
| 316 | } |
| 317 | if accountMatches(d.Account.String(), ref.name) { |
| 318 | add(fileIdx, d.Account.Span, newName+strings.TrimPrefix(d.Account.String(), ref.name)) |
| 319 | } |
| 320 | for _, sd := range d.Subdirectives { |
| 321 | if sd.Name == "alias" && accountMatches(sd.Value, ref.name) { |
| 322 | add(fileIdx, sd.ValueSpan, newName+strings.TrimPrefix(sd.Value, ref.name)) |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | for _, ad := range an.AliasDirectives { |
| 328 | fileIdx := fileIndexForEntry(an, ad) |
| 329 | if fileIdx < 0 { |
| 330 | continue |
| 331 | } |
| 332 | if accountMatches(ad.From.String(), ref.name) { |
| 333 | add(fileIdx, ad.From.Span, newName+strings.TrimPrefix(ad.From.String(), ref.name)) |
| 334 | } |
| 335 | if accountMatches(ad.To.String(), ref.name) { |
| 336 | add(fileIdx, ad.To.Span, newName+strings.TrimPrefix(ad.To.String(), ref.name)) |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | func renameCommodityEdits(an *analyzer.Analysis, ref *symbolRef, newName string, add func(int, token.Span, string)) { |
| 342 | info := an.Commodities[ref.name] |
| 343 | if info == nil { |
| 344 | return |
| 345 | } |
| 346 | for _, d := range info.Directives { |
| 347 | if fileIdx := fileIndexForEntry(an, d); fileIdx >= 0 { |
| 348 | add(fileIdx, d.CommoditySpan, newName) |
| 349 | } |
| 350 | } |
| 351 | for _, u := range info.Usages { |
| 352 | add(u.FileIndex, u.Amount.CommoditySpan, newName) |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | func renamePayeeEdits(an *analyzer.Analysis, ref *symbolRef, newName string, add func(int, token.Span, string)) { |
| 357 | info := an.Payees[ref.name] |
| 358 | if info == nil { |
| 359 | return |
| 360 | } |
| 361 | for _, d := range info.Directives { |
| 362 | if d.Name != nil { |
| 363 | if fileIdx := fileIndexForEntry(an, d); fileIdx >= 0 { |
| 364 | add(fileIdx, d.Name.Span, newName) |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | for _, u := range info.Usage { |
| 369 | add(u.FileIndex, u.Payee.Span, newName) |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | func renameTagEdits(an *analyzer.Analysis, ref *symbolRef, newName string, add func(int, token.Span, string)) { |
| 374 | info := an.Tags[ref.name] |
| 375 | if info == nil { |
| 376 | return |
| 377 | } |
| 378 | contents := make(map[int]string) // file index → source, converted once per file |
| 379 | content := func(fileIdx int) string { |
| 380 | s, ok := contents[fileIdx] |
| 381 | if !ok { |
| 382 | s = string(an.Files[fileIdx].Src) |
| 383 | contents[fileIdx] = s |
| 384 | } |
| 385 | return s |
| 386 | } |
| 387 | for _, d := range info.Directives { |
| 388 | fileIdx := fileIndexForEntry(an, d) |
| 389 | if fileIdx < 0 { |
| 390 | continue |
| 391 | } |
| 392 | if span, ok := tagDirectiveSpan(content(fileIdx), d); ok { |
| 393 | add(fileIdx, span, newName) |
| 394 | } |
| 395 | } |
| 396 | for _, u := range info.Usage { |
| 397 | span := tagKeySpan(content(u.FileIndex), u.Tag) |
| 398 | add(u.FileIndex, span, newName) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | func tagDirectiveSpan(content string, d *ast.TagDirective) (token.Span, bool) { |
| 403 | end := d.Span.End.Offset |
| 404 | if d.Comment != nil { |
| 405 | end = d.Comment.Span.Start.Offset |
| 406 | } |
| 407 | return betweenSpan(content, d.Span.Start.File, d.Span.Start.Offset+len("tag"), end) |
| 408 | } |
| 409 | |
| 410 | func tagKeySpan(content string, t *ast.Tag) token.Span { |
| 411 | end := t.Span.End.Offset |
| 412 | for off := t.Span.Start.Offset; off < end; off++ { |
| 413 | if content[off] == ':' || content[off] == ',' { |
| 414 | end = off |
| 415 | break |
| 416 | } |
| 417 | } |
| 418 | for end > t.Span.Start.Offset && (content[end-1] == ' ' || content[end-1] == '\t') { |
| 419 | end-- |
| 420 | } |
| 421 | return token.Span{Start: t.Span.Start, End: offsetPos(t.Span.Start.File, end)} |
| 422 | } |
| 423 | |
| 424 | func sortAndDedup(changes map[uri.URI][]protocol.TextEdit) { |
| 425 | for u, edits := range changes { |
| 426 | sort.Slice(edits, func(i, j int) bool { |
| 427 | ri, rj := edits[i].Range, edits[j].Range |
| 428 | if ri.Start.Line != rj.Start.Line { |
| 429 | return ri.Start.Line < rj.Start.Line |
| 430 | } |
| 431 | return ri.Start.Character < rj.Start.Character |
| 432 | }) |
| 433 | dedup := edits[:0] |
| 434 | for _, e := range edits { |
| 435 | if len(dedup) == 0 || dedup[len(dedup)-1] != e { |
| 436 | dedup = append(dedup, e) |
| 437 | } |
| 438 | } |
| 439 | changes[u] = dedup |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | // Validation |
| 444 | |
| 445 | func validateAccountName(name string) error { return validateRenameName(name, "account", ";") } |
| 446 | func validateCommodityName(name string) error { return validateRenameName(name, "commodity", ";") } |
| 447 | func validatePayeeName(name string) error { return validateRenameName(name, "payee", ";|") } |
| 448 | func validateTagName(name string) error { return validateRenameName(name, "tag", ":,; \t") } |
| 449 | func validateRenameName(name, what, forbidden string) error { |
| 450 | if name == "" { |
| 451 | return fmt.Errorf("%s name must not be empty", what) |
| 452 | } |
| 453 | if name != strings.TrimSpace(name) { |
| 454 | return fmt.Errorf("%s name must not have leading or trailing whitespace", what) |
| 455 | } |
| 456 | for _, r := range name { |
| 457 | if strings.ContainsRune(forbidden, r) || r == '\n' || r == '\r' { |
| 458 | return fmt.Errorf("%s name contains illegal character %q", what, r) |
| 459 | } |
| 460 | } |
| 461 | return nil |
| 462 | } |