lsp_lang/position.rs
1//! Protocol positions: [`Position`], [`Range`], and the [`Encoding`] their
2//! columns are counted in.
3
4use jsonx_lib::Value;
5
6use crate::{
7 json::{req_object, req_str, req_u32, to_value, write_u64},
8 response::ResponseError,
9};
10
11/// A place in a document as the protocol spells it: a zero-based line and a
12/// zero-based column within that line.
13///
14/// The column, `character`, is counted in the units of the session's
15/// [`Encoding`]: UTF-16 code units unless the client offered UTF-8 during
16/// `initialize`. A [`Document`](crate::Document) converts between positions and
17/// the byte offsets the rest of the `-lang` family works in; handlers rarely
18/// build positions by hand except to answer a request.
19///
20/// Converts to and from the protocol's `{"line": …, "character": …}` shape
21/// ([`to_json`](Position::to_json), [`from_json`](Position::from_json)).
22/// Positions order by line, then column.
23///
24/// # Examples
25///
26/// ```
27/// use lsp_lang::Position;
28///
29/// let pos = Position::new(2, 4);
30/// assert_eq!((pos.line, pos.character), (2, 4));
31/// assert!(Position::new(1, 99) < Position::new(2, 0));
32///
33/// assert_eq!(pos.to_json().to_string(), r#"{"line":2,"character":4}"#);
34/// ```
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub struct Position {
37 /// Zero-based line number. Lines end at `\n`, `\r\n`, or a lone `\r`.
38 pub line: u32,
39 /// Zero-based column within the line, in the session's [`Encoding`].
40 pub character: u32,
41}
42
43impl Position {
44 /// Builds a position from a zero-based line and column.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// use lsp_lang::Position;
50 ///
51 /// assert_eq!(Position::new(0, 0), Position::default());
52 /// ```
53 #[inline]
54 #[must_use]
55 pub const fn new(line: u32, character: u32) -> Self {
56 Self { line, character }
57 }
58
59 /// The protocol's JSON for this position.
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// use lsp_lang::Position;
65 ///
66 /// assert_eq!(Position::new(1, 2).to_json()["character"], 2);
67 /// ```
68 #[must_use]
69 pub fn to_json(&self) -> Value<'static> {
70 let mut out = String::new();
71 self.write(&mut out);
72 to_value(&out)
73 }
74
75 /// Reads a position from `{"line": …, "character": …}`.
76 ///
77 /// # Errors
78 ///
79 /// [`INVALID_PARAMS`](ResponseError::INVALID_PARAMS) when either member is
80 /// missing or is not an unsigned 32-bit integer, so a handler can return it
81 /// with `?`.
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// use lsp_lang::{json, Position};
87 ///
88 /// let pos = Position::from_json(&json!({ "line": 3, "character": 9 }))?;
89 /// assert_eq!(pos, Position::new(3, 9));
90 /// assert!(Position::from_json(&json!({ "line": -1, "character": 0 })).is_err());
91 /// # Ok::<(), lsp_lang::ResponseError>(())
92 /// ```
93 pub fn from_json(value: &Value<'_>) -> Result<Self, ResponseError> {
94 if !matches!(value, Value::Object(_)) {
95 return Err(ResponseError::invalid_params(format!(
96 "invalid params: a position must be an object, not {}",
97 value.kind()
98 )));
99 }
100 Ok(Self {
101 line: req_u32(value, "line")?,
102 character: req_u32(value, "character")?,
103 })
104 }
105
106 pub(crate) fn write(&self, out: &mut String) {
107 out.push_str("{\"line\":");
108 write_u64(out, u64::from(self.line));
109 out.push_str(",\"character\":");
110 write_u64(out, u64::from(self.character));
111 out.push('}');
112 }
113}
114
115/// A stretch of a document between two [`Position`]s: `start` inclusive, `end`
116/// exclusive, as in the protocol.
117///
118/// An empty range (`start == end`) marks a point, such as a cursor.
119///
120/// # Examples
121///
122/// ```
123/// use lsp_lang::{Position, Range};
124///
125/// let word = Range::new(Position::new(3, 4), Position::new(3, 9));
126/// assert_eq!(word.start.character, 4);
127/// assert_eq!(
128/// word.to_json().to_string(),
129/// r#"{"start":{"line":3,"character":4},"end":{"line":3,"character":9}}"#
130/// );
131/// ```
132#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
133pub struct Range {
134 /// Where the range begins (inclusive).
135 pub start: Position,
136 /// Where the range ends (exclusive).
137 pub end: Position,
138}
139
140impl Range {
141 /// Builds a range from its two ends.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// use lsp_lang::{Position, Range};
147 ///
148 /// let cursor = Range::new(Position::new(1, 2), Position::new(1, 2));
149 /// assert_eq!(cursor.start, cursor.end);
150 /// ```
151 #[inline]
152 #[must_use]
153 pub const fn new(start: Position, end: Position) -> Self {
154 Self { start, end }
155 }
156
157 /// The protocol's JSON for this range.
158 ///
159 /// # Examples
160 ///
161 /// ```
162 /// use lsp_lang::{Position, Range};
163 ///
164 /// let range = Range::new(Position::new(0, 0), Position::new(0, 3));
165 /// assert_eq!(range.to_json()["end"]["character"], 3);
166 /// ```
167 #[must_use]
168 pub fn to_json(&self) -> Value<'static> {
169 let mut out = String::new();
170 self.write(&mut out);
171 to_value(&out)
172 }
173
174 /// Reads a range from `{"start": …, "end": …}`.
175 ///
176 /// # Errors
177 ///
178 /// [`INVALID_PARAMS`](ResponseError::INVALID_PARAMS) when either end is
179 /// missing or is not a position.
180 ///
181 /// # Examples
182 ///
183 /// ```
184 /// use lsp_lang::{json, Position, Range};
185 ///
186 /// let range = Range::from_json(&json!({
187 /// "start": { "line": 0, "character": 1 },
188 /// "end": { "line": 2, "character": 3 },
189 /// }))?;
190 /// assert_eq!(range, Range::new(Position::new(0, 1), Position::new(2, 3)));
191 /// # Ok::<(), lsp_lang::ResponseError>(())
192 /// ```
193 pub fn from_json(value: &Value<'_>) -> Result<Self, ResponseError> {
194 if !matches!(value, Value::Object(_)) {
195 return Err(ResponseError::invalid_params(format!(
196 "invalid params: a range must be an object, not {}",
197 value.kind()
198 )));
199 }
200 Ok(Self {
201 start: Position::from_json(req_object(value, "start")?)?,
202 end: Position::from_json(req_object(value, "end")?)?,
203 })
204 }
205
206 pub(crate) fn write(&self, out: &mut String) {
207 out.push_str("{\"start\":");
208 self.start.write(out);
209 out.push_str(",\"end\":");
210 self.end.write(out);
211 out.push('}');
212 }
213}
214
215/// The unit a [`Position`]'s column is counted in.
216///
217/// The protocol's default is UTF-16 code units, which every client supports.
218/// Since LSP 3.17 a client may offer others in `general.positionEncodings`;
219/// the server picks UTF-8 whenever it is offered, because a byte column
220/// converts to a byte offset with no scanning at all, and otherwise stays with
221/// UTF-16, the one encoding every client must accept. The choice is announced
222/// to the client in the `initialize` result and applies to every document for
223/// the whole session.
224///
225/// | Variant | Unit | `é` | `😀` |
226/// |---|---|---|---|
227/// | `Utf8` | bytes | 2 | 4 |
228/// | `Utf16` | UTF-16 code units | 1 | 2 |
229///
230/// # Examples
231///
232/// ```
233/// use lsp_lang::Encoding;
234///
235/// assert_eq!(Encoding::default(), Encoding::Utf16);
236/// ```
237#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
238#[non_exhaustive]
239pub enum Encoding {
240 /// Columns count UTF-8 bytes (`"utf-8"`).
241 Utf8,
242 /// Columns count UTF-16 code units (`"utf-16"`), the protocol default.
243 #[default]
244 Utf16,
245}
246
247impl Encoding {
248 /// The protocol's name for this encoding, as sent in `positionEncoding`.
249 #[inline]
250 pub(crate) const fn as_str(self) -> &'static str {
251 match self {
252 Encoding::Utf8 => "utf-8",
253 Encoding::Utf16 => "utf-16",
254 }
255 }
256
257 /// Picks the session encoding from the client's offered list: UTF-8 when
258 /// offered, else the protocol's mandatory UTF-16.
259 pub(crate) fn negotiate<'a>(offered: impl IntoIterator<Item = &'a str>) -> Self {
260 if offered.into_iter().any(|name| name == "utf-8") {
261 Encoding::Utf8
262 } else {
263 Encoding::Utf16
264 }
265 }
266}
267
268/// Reads `textDocument` and `position` from a request's parameters: the shape
269/// shared by hover, definition, and completion.
270pub(crate) fn document_position(params: &Value<'_>) -> Result<(String, Position), ResponseError> {
271 let uri = req_str(req_object(params, "textDocument")?, "uri")?.to_owned();
272 let position = Position::from_json(req_object(params, "position")?)?;
273 Ok((uri, position))
274}
275
276/// Reads `textDocument.uri`: the shape of document-wide requests.
277pub(crate) fn document_uri(params: &Value<'_>) -> Result<String, ResponseError> {
278 Ok(req_str(req_object(params, "textDocument")?, "uri")?.to_owned())
279}
280
281#[cfg(test)]
282mod tests {
283 use jsonx_lib::json;
284
285 use super::*;
286
287 #[test]
288 fn test_encoding_negotiate_prefers_utf8() {
289 assert_eq!(Encoding::negotiate(["utf-16", "utf-8"]), Encoding::Utf8);
290 assert_eq!(Encoding::negotiate(["utf-32", "utf-16"]), Encoding::Utf16);
291 assert_eq!(Encoding::negotiate([]), Encoding::Utf16);
292 }
293
294 #[test]
295 fn test_encoding_as_str_matches_protocol_names() {
296 assert_eq!(Encoding::Utf8.as_str(), "utf-8");
297 assert_eq!(Encoding::Utf16.as_str(), "utf-16");
298 }
299
300 #[test]
301 fn test_position_orders_by_line_then_column() {
302 assert!(Position::new(0, 9) < Position::new(1, 0));
303 assert!(Position::new(1, 1) < Position::new(1, 2));
304 }
305
306 #[test]
307 fn test_position_and_range_round_trip_through_json() {
308 let range = Range::new(Position::new(0, u32::MAX), Position::new(u32::MAX, 0));
309 assert_eq!(Range::from_json(&range.to_json()).ok(), Some(range));
310 }
311
312 #[test]
313 fn test_position_from_json_rejects_wrong_shapes() {
314 for bad in [
315 json!(null),
316 json!([1, 2]),
317 json!({ "line": 1 }),
318 json!({ "line": 1, "character": "2" }),
319 json!({ "line": 1.5, "character": 2 }),
320 json!({ "line": 4294967296_u64, "character": 2 }),
321 ] {
322 let err = Position::from_json(&bad).err();
323 assert_eq!(
324 err.map(|e| e.code()),
325 Some(ResponseError::INVALID_PARAMS),
326 "{bad}"
327 );
328 }
329 assert!(Range::from_json(&json!({ "start": {} })).is_err());
330 assert!(Range::from_json(&json!(5)).is_err());
331 }
332
333 #[test]
334 fn test_document_position_reads_the_request_shape() {
335 let params = json!({ "textDocument": { "uri": "file:///a" }, "position": { "line": 1, "character": 2 } });
336 assert_eq!(
337 document_position(¶ms).ok(),
338 Some(("file:///a".to_owned(), Position::new(1, 2)))
339 );
340 assert!(document_position(&json!({ "position": {} })).is_err());
341 assert_eq!(document_uri(¶ms).ok().as_deref(), Some("file:///a"));
342 }
343}