| 1 | // Copyright 2024 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package protocol |
| 6 | |
| 7 | import ( |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | ) |
| 11 | |
| 12 | // InsertReplaceEdit is used instead of TextEdit in CompletionItem |
| 13 | // in editors that support it. These two types are alike in appearance |
| 14 | // but can be differentiated by the presence or absence of |
| 15 | // certain properties. UnmarshalJSON of the sum type tries to |
| 16 | // unmarshal as TextEdit only if unmarshal as InsertReplaceEdit fails. |
| 17 | // However, due to this similarity, unmarshal with the other type |
| 18 | // never fails. This file has a custom JSON unmarshaller for |
| 19 | // InsertReplaceEdit, that fails if the required fields are missing. |
| 20 | |
| 21 | // UnmarshalJSON unmarshals InsertReplaceEdit with extra |
| 22 | // checks on the presence of "insert" and "replace" properties. |
| 23 | func (e *InsertReplaceEdit) UnmarshalJSON(data []byte) error { |
| 24 | var required struct { |
| 25 | NewText string |
| 26 | Insert *Range `json:"insert,omitempty"` |
| 27 | Replace *Range `json:"replace,omitempty"` |
| 28 | } |
| 29 | |
| 30 | if err := json.Unmarshal(data, &required); err != nil { |
| 31 | return err |
| 32 | } |
| 33 | if required.Insert == nil && required.Replace == nil { |
| 34 | return fmt.Errorf("not InsertReplaceEdit") |
| 35 | } |
| 36 | e.NewText = required.NewText |
| 37 | e.Insert = *required.Insert |
| 38 | e.Replace = *required.Replace |
| 39 | return nil |
| 40 | } |