clerk/internal/lsp/textdocument_rename.go (view raw)
Oleksandr Smirnov
Oleksandr Smirnov
olexsmir@gmail.com perf: lsp: resolve positions and entries via cached line index..., 1 month ago
olexsmir@gmail.com perf: lsp: resolve positions and entries via cached line index..., 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.analysis() |
| 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.analysis() |
| 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) |
| 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 | // symbolRef is a symbol under the cursor, ready to be resolved or renamed. |
| 167 | type symbolRef struct { |
| 168 | kind symbolKind |
| 169 | name string |
| 170 | span token.Span |
| 171 | } |
| 172 | |
| 173 | // renameTo returns the replacement rext for an occurrence of the nodeKind with the given name. |
| 174 | func (ref *symbolRef) renameTo(nodeKind symbolKind, name, newName string) (text string, renamed bool) { |
| 175 | if ref.kind != nodeKind { |
| 176 | return "", false |
| 177 | } |
| 178 | if ref.kind == symbolAccount { |
| 179 | if !accountMatches(name, ref.name) { |
| 180 | return "", false |
| 181 | } |
| 182 | return newName + strings.TrimPrefix(name, ref.name), true |
| 183 | } |
| 184 | if name != ref.name { |
| 185 | return "", false |
| 186 | } |
| 187 | return newName, true |
| 188 | } |
| 189 | |
| 190 | func accountMatches(name, old string) bool { |
| 191 | return name == old || strings.HasPrefix(name, old+":") |
| 192 | } |
| 193 | |
| 194 | func tagRefInComment(content string, c *ast.Comment, cursor int) *symbolRef { |
| 195 | if c == nil { |
| 196 | return nil |
| 197 | } |
| 198 | for i := range c.Tags { |
| 199 | t := &c.Tags[i] |
| 200 | if span := tagKeySpan(content, t); spanContains(content, span, cursor) { |
| 201 | return &symbolRef{symbolTag, t.Key, span} |
| 202 | } |
| 203 | } |
| 204 | return nil |
| 205 | } |
| 206 | |
| 207 | func commodityRef(content string, am *ast.Amount, cursor int) *symbolRef { |
| 208 | if am == nil || am.Commodity == "" || !spanContains(content, am.CommoditySpan, cursor) { |
| 209 | return nil |
| 210 | } |
| 211 | return &symbolRef{symbolCommodity, am.Commodity, am.CommoditySpan} |
| 212 | } |
| 213 | |
| 214 | func symbolInPostings(content string, postings []*ast.Posting, cursor int) *symbolRef { |
| 215 | for _, p := range postings { |
| 216 | if spanContains(content, p.Account.Span, cursor) { |
| 217 | return &symbolRef{symbolAccount, p.Account.String(), p.Account.Span} |
| 218 | } |
| 219 | if ref := commodityRef(content, p.Amount, cursor); ref != nil { |
| 220 | return ref |
| 221 | } |
| 222 | if p.Cost != nil { |
| 223 | if ref := commodityRef(content, &p.Cost.Amount, cursor); ref != nil { |
| 224 | return ref |
| 225 | } |
| 226 | } |
| 227 | if p.Balance != nil { |
| 228 | if ref := commodityRef(content, &p.Balance.Amount, cursor); ref != nil { |
| 229 | return ref |
| 230 | } |
| 231 | } |
| 232 | if ref := tagRefInComment(content, p.Comment, cursor); ref != nil { |
| 233 | return ref |
| 234 | } |
| 235 | for i := range p.Comments { |
| 236 | if ref := tagRefInComment(content, &p.Comments[i], cursor); ref != nil { |
| 237 | return ref |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | return nil |
| 242 | } |
| 243 | |
| 244 | // renameChanges collects the workspace edits renaming ref to newName |
| 245 | func renameChanges(an *analyzer.Analysis, ref *symbolRef, newName string) map[uri.URI][]protocol.TextEdit { |
| 246 | changes := make(map[uri.URI][]protocol.TextEdit) |
| 247 | for _, pf := range an.Files { |
| 248 | content := string(pf.Src) |
| 249 | // LineIndex is built lazily: most files have no matching edits, and |
| 250 | // each edit needs an O(log n) offset-to-position lookup, not a scan. |
| 251 | var li *lsputil.LineIndex |
| 252 | var edits []protocol.TextEdit |
| 253 | add := func(span token.Span, text string) { |
| 254 | if li == nil { |
| 255 | li = lsputil.NewLineIndex(content) |
| 256 | } |
| 257 | edits = append(edits, protocol.TextEdit{ |
| 258 | Range: li.SpanRange(span), |
| 259 | NewText: text, |
| 260 | }) |
| 261 | } |
| 262 | for _, e := range pf.Ast.Entries { |
| 263 | renameEntry(add, ref, newName, content, e) |
| 264 | } |
| 265 | if len(edits) > 0 { |
| 266 | changes[uri.File(pf.Path)] = edits |
| 267 | } |
| 268 | } |
| 269 | sortAndDedup(changes) |
| 270 | return changes |
| 271 | } |
| 272 | |
| 273 | func renameEntry(add func(token.Span, string), ref *symbolRef, newName, content string, e ast.Entry) { |
| 274 | switch e := e.(type) { |
| 275 | case *ast.Transaction: |
| 276 | renamePayee(add, ref, newName, e.Payee) |
| 277 | renameCommentTags(add, ref, newName, content, e.Comment) |
| 278 | for _, c := range e.HeaderComments { |
| 279 | renameCommentTags(add, ref, newName, content, c) |
| 280 | } |
| 281 | renamePostings(add, ref, newName, content, e.Postings) |
| 282 | case *ast.PeriodicTransaction: |
| 283 | renameCommentTags(add, ref, newName, content, e.Comment) |
| 284 | for _, c := range e.HeaderComments { |
| 285 | renameCommentTags(add, ref, newName, content, c) |
| 286 | } |
| 287 | renamePostings(add, ref, newName, content, e.Postings) |
| 288 | case *ast.AutomatedTransaction: |
| 289 | renameCommentTags(add, ref, newName, content, e.Comment) |
| 290 | for _, c := range e.HeaderComments { |
| 291 | renameCommentTags(add, ref, newName, content, c) |
| 292 | } |
| 293 | renamePostings(add, ref, newName, content, e.Postings) |
| 294 | case *ast.Comment: |
| 295 | renameCommentTags(add, ref, newName, content, e) |
| 296 | case *ast.AccountDirective: |
| 297 | if text, ok := ref.renameTo(symbolAccount, e.Account.String(), newName); ok { |
| 298 | add(e.Account.Span, text) |
| 299 | } |
| 300 | for _, sd := range e.Subdirectives { |
| 301 | if sd.Name == "alias" { |
| 302 | if text, ok := ref.renameTo(symbolAccount, sd.Value, newName); ok { |
| 303 | add(sd.ValueSpan, text) |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | case *ast.AliasDirective: |
| 308 | if text, ok := ref.renameTo(symbolAccount, e.From.String(), newName); ok { |
| 309 | add(e.From.Span, text) |
| 310 | } |
| 311 | if text, ok := ref.renameTo(symbolAccount, e.To.String(), newName); ok { |
| 312 | add(e.To.Span, text) |
| 313 | } |
| 314 | case *ast.CommodityDirective: |
| 315 | if text, ok := ref.renameTo(symbolCommodity, e.Commodity, newName); ok { |
| 316 | add(e.CommoditySpan, text) |
| 317 | } |
| 318 | case *ast.PayeeDirective: |
| 319 | renamePayee(add, ref, newName, e.Name) |
| 320 | case *ast.TagDirective: |
| 321 | if text, ok := ref.renameTo(symbolTag, e.Name, newName); ok { |
| 322 | if span, ok := tagDirectiveSpan(content, e); ok { |
| 323 | add(span, text) |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | func renamePostings(add func(token.Span, string), ref *symbolRef, newName, content string, postings []*ast.Posting) { |
| 330 | for _, p := range postings { |
| 331 | if text, ok := ref.renameTo(symbolAccount, p.Account.String(), newName); ok { |
| 332 | add(p.Account.Span, text) |
| 333 | } |
| 334 | renameCommodity(add, ref, newName, p.Amount) |
| 335 | if p.Cost != nil { |
| 336 | renameCommodity(add, ref, newName, &p.Cost.Amount) |
| 337 | } |
| 338 | if p.Balance != nil { |
| 339 | renameCommodity(add, ref, newName, &p.Balance.Amount) |
| 340 | } |
| 341 | renameCommentTags(add, ref, newName, content, p.Comment) |
| 342 | for i := range p.Comments { |
| 343 | renameCommentTags(add, ref, newName, content, &p.Comments[i]) |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | func renameCommodity(add func(token.Span, string), ref *symbolRef, newName string, am *ast.Amount) { |
| 349 | if am == nil { |
| 350 | return |
| 351 | } |
| 352 | if text, ok := ref.renameTo(symbolCommodity, am.Commodity, newName); ok { |
| 353 | add(am.CommoditySpan, text) |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | func renamePayee(add func(token.Span, string), ref *symbolRef, newName string, p *ast.Payee) { |
| 358 | if p == nil { |
| 359 | return |
| 360 | } |
| 361 | if text, ok := ref.renameTo(symbolPayee, p.Name, newName); ok { |
| 362 | add(p.Span, text) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | func renameCommentTags(add func(token.Span, string), ref *symbolRef, newName, content string, c *ast.Comment) { |
| 367 | if c == nil { |
| 368 | return |
| 369 | } |
| 370 | for i := range c.Tags { |
| 371 | t := &c.Tags[i] |
| 372 | if text, ok := ref.renameTo(symbolTag, t.Key, newName); ok { |
| 373 | add(tagKeySpan(content, t), text) |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | func tagDirectiveSpan(content string, d *ast.TagDirective) (token.Span, bool) { |
| 379 | end := d.Span.End.Offset |
| 380 | if d.Comment != nil { |
| 381 | end = d.Comment.Span.Start.Offset |
| 382 | } |
| 383 | return betweenSpan(content, d.Span.Start.File, d.Span.Start.Offset+len("tag"), end) |
| 384 | } |
| 385 | |
| 386 | func tagKeySpan(content string, t *ast.Tag) token.Span { |
| 387 | end := t.Span.End.Offset |
| 388 | for off := t.Span.Start.Offset; off < end; off++ { |
| 389 | if content[off] == ':' || content[off] == ',' { |
| 390 | end = off |
| 391 | break |
| 392 | } |
| 393 | } |
| 394 | for end > t.Span.Start.Offset && (content[end-1] == ' ' || content[end-1] == '\t') { |
| 395 | end-- |
| 396 | } |
| 397 | return token.Span{Start: t.Span.Start, End: offsetPos(t.Span.Start.File, end)} |
| 398 | } |
| 399 | |
| 400 | func sortAndDedup(changes map[uri.URI][]protocol.TextEdit) { |
| 401 | for u, edits := range changes { |
| 402 | sort.Slice(edits, func(i, j int) bool { |
| 403 | ri, rj := edits[i].Range, edits[j].Range |
| 404 | if ri.Start.Line != rj.Start.Line { |
| 405 | return ri.Start.Line < rj.Start.Line |
| 406 | } |
| 407 | return ri.Start.Character < rj.Start.Character |
| 408 | }) |
| 409 | dedup := edits[:0] |
| 410 | for _, e := range edits { |
| 411 | if len(dedup) == 0 || dedup[len(dedup)-1] != e { |
| 412 | dedup = append(dedup, e) |
| 413 | } |
| 414 | } |
| 415 | changes[u] = dedup |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // Validation |
| 420 | |
| 421 | func validateAccountName(name string) error { return validateRenameName(name, "account", ";") } |
| 422 | func validateCommodityName(name string) error { return validateRenameName(name, "commodity", ";") } |
| 423 | func validatePayeeName(name string) error { return validateRenameName(name, "payee", ";|") } |
| 424 | func validateTagName(name string) error { return validateRenameName(name, "tag", ":,; \t") } |
| 425 | func validateRenameName(name, what, forbidden string) error { |
| 426 | if name == "" { |
| 427 | return fmt.Errorf("%s name must not be empty", what) |
| 428 | } |
| 429 | if name != strings.TrimSpace(name) { |
| 430 | return fmt.Errorf("%s name must not have leading or trailing whitespace", what) |
| 431 | } |
| 432 | for _, r := range name { |
| 433 | if strings.ContainsRune(forbidden, r) || r == '\n' || r == '\r' { |
| 434 | return fmt.Errorf("%s name contains illegal character %q", what, r) |
| 435 | } |
| 436 | } |
| 437 | return nil |
| 438 | } |