Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 31486a6

Browse files
committed
Auto merge of rust-lang#14141 - matklad:utf-32, r=lnicola
Support UTF-32 position encoding Looks like this is a native encoding for Emacs at least!
2 parents 2a57b01 + 9fdcf57 commit 31486a6

File tree

18 files changed

+211
-159
lines changed

18 files changed

+211
-159
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/ide-db/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,9 @@ text-edit.workspace = true
3737
hir.workspace = true
3838

3939
[dev-dependencies]
40-
xshell = "0.2.2"
4140
expect-test = "1.4.0"
41+
oorandom = "11.1.3"
42+
xshell = "0.2.2"
4243

4344
# local deps
4445
test-utils.workspace = true

crates/ide-db/src/line_index.rs

Lines changed: 103 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -7,56 +7,72 @@ use syntax::{TextRange, TextSize};
77

88
#[derive(Clone, Debug, PartialEq, Eq)]
99
pub struct LineIndex {
10-
/// Offset the the beginning of each line, zero-based
10+
/// Offset the beginning of each line, zero-based.
1111
pub(crate) newlines: Vec<TextSize>,
12-
/// List of non-ASCII characters on each line
13-
pub(crate) utf16_lines: NoHashHashMap<u32, Vec<Utf16Char>>,
12+
/// List of non-ASCII characters on each line.
13+
pub(crate) line_wide_chars: NoHashHashMap<u32, Vec<WideChar>>,
1414
}
1515

16+
/// Line/Column information in native, utf8 format.
1617
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17-
pub struct LineColUtf16 {
18+
pub struct LineCol {
1819
/// Zero-based
1920
pub line: u32,
20-
/// Zero-based
21+
/// Zero-based utf8 offset
2122
pub col: u32,
2223
}
2324

2425
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25-
pub struct LineCol {
26+
pub enum WideEncoding {
27+
Utf16,
28+
Utf32,
29+
}
30+
31+
/// Line/Column information in legacy encodings.
32+
///
33+
/// Deliberately not a generic type and different from `LineCol`.
34+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35+
pub struct WideLineCol {
2636
/// Zero-based
2737
pub line: u32,
28-
/// Zero-based utf8 offset
38+
/// Zero-based
2939
pub col: u32,
3040
}
3141

3242
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
33-
pub(crate) struct Utf16Char {
43+
pub(crate) struct WideChar {
3444
/// Start offset of a character inside a line, zero-based
3545
pub(crate) start: TextSize,
3646
/// End offset of a character inside a line, zero-based
3747
pub(crate) end: TextSize,
3848
}
3949

40-
impl Utf16Char {
50+
impl WideChar {
4151
/// Returns the length in 8-bit UTF-8 code units.
4252
fn len(&self) -> TextSize {
4353
self.end - self.start
4454
}
4555

46-
/// Returns the length in 16-bit UTF-16 code units.
47-
fn len_utf16(&self) -> usize {
48-
if self.len() == TextSize::from(4) {
49-
2
50-
} else {
51-
1
56+
/// Returns the length in UTF-16 or UTF-32 code units.
57+
fn wide_len(&self, enc: WideEncoding) -> usize {
58+
match enc {
59+
WideEncoding::Utf16 => {
60+
if self.len() == TextSize::from(4) {
61+
2
62+
} else {
63+
1
64+
}
65+
}
66+
67+
WideEncoding::Utf32 => 1,
5268
}
5369
}
5470
}
5571

5672
impl LineIndex {
5773
pub fn new(text: &str) -> LineIndex {
58-
let mut utf16_lines = NoHashHashMap::default();
59-
let mut utf16_chars = Vec::new();
74+
let mut line_wide_chars = NoHashHashMap::default();
75+
let mut wide_chars = Vec::new();
6076

6177
let mut newlines = Vec::with_capacity(16);
6278
newlines.push(TextSize::from(0));
@@ -71,8 +87,8 @@ impl LineIndex {
7187
newlines.push(curr_row);
7288

7389
// Save any utf-16 characters seen in the previous line
74-
if !utf16_chars.is_empty() {
75-
utf16_lines.insert(line, mem::take(&mut utf16_chars));
90+
if !wide_chars.is_empty() {
91+
line_wide_chars.insert(line, mem::take(&mut wide_chars));
7692
}
7793

7894
// Prepare for processing the next line
@@ -82,18 +98,18 @@ impl LineIndex {
8298
}
8399

84100
if !c.is_ascii() {
85-
utf16_chars.push(Utf16Char { start: curr_col, end: curr_col + c_len });
101+
wide_chars.push(WideChar { start: curr_col, end: curr_col + c_len });
86102
}
87103

88104
curr_col += c_len;
89105
}
90106

91107
// Save any utf-16 characters seen in the last line
92-
if !utf16_chars.is_empty() {
93-
utf16_lines.insert(line, utf16_chars);
108+
if !wide_chars.is_empty() {
109+
line_wide_chars.insert(line, wide_chars);
94110
}
95111

96-
LineIndex { newlines, utf16_lines }
112+
LineIndex { newlines, line_wide_chars }
97113
}
98114

99115
pub fn line_col(&self, offset: TextSize) -> LineCol {
@@ -109,13 +125,13 @@ impl LineIndex {
109125
.map(|offset| offset + TextSize::from(line_col.col))
110126
}
111127

112-
pub fn to_utf16(&self, line_col: LineCol) -> LineColUtf16 {
113-
let col = self.utf8_to_utf16_col(line_col.line, line_col.col.into());
114-
LineColUtf16 { line: line_col.line, col: col as u32 }
128+
pub fn to_wide(&self, enc: WideEncoding, line_col: LineCol) -> WideLineCol {
129+
let col = self.utf8_to_wide_col(enc, line_col.line, line_col.col.into());
130+
WideLineCol { line: line_col.line, col: col as u32 }
115131
}
116132

117-
pub fn to_utf8(&self, line_col: LineColUtf16) -> LineCol {
118-
let col = self.utf16_to_utf8_col(line_col.line, line_col.col);
133+
pub fn to_utf8(&self, enc: WideEncoding, line_col: WideLineCol) -> LineCol {
134+
let col = self.wide_to_utf8_col(enc, line_col.line, line_col.col);
119135
LineCol { line: line_col.line, col: col.into() }
120136
}
121137

@@ -132,12 +148,12 @@ impl LineIndex {
132148
.filter(|it| !it.is_empty())
133149
}
134150

135-
fn utf8_to_utf16_col(&self, line: u32, col: TextSize) -> usize {
151+
fn utf8_to_wide_col(&self, enc: WideEncoding, line: u32, col: TextSize) -> usize {
136152
let mut res: usize = col.into();
137-
if let Some(utf16_chars) = self.utf16_lines.get(&line) {
138-
for c in utf16_chars {
153+
if let Some(wide_chars) = self.line_wide_chars.get(&line) {
154+
for c in wide_chars {
139155
if c.end <= col {
140-
res -= usize::from(c.len()) - c.len_utf16();
156+
res -= usize::from(c.len()) - c.wide_len(enc);
141157
} else {
142158
// From here on, all utf16 characters come *after* the character we are mapping,
143159
// so we don't need to take them into account
@@ -148,11 +164,11 @@ impl LineIndex {
148164
res
149165
}
150166

151-
fn utf16_to_utf8_col(&self, line: u32, mut col: u32) -> TextSize {
152-
if let Some(utf16_chars) = self.utf16_lines.get(&line) {
153-
for c in utf16_chars {
167+
fn wide_to_utf8_col(&self, enc: WideEncoding, line: u32, mut col: u32) -> TextSize {
168+
if let Some(wide_chars) = self.line_wide_chars.get(&line) {
169+
for c in wide_chars {
154170
if col > u32::from(c.start) {
155-
col += u32::from(c.len()) - c.len_utf16() as u32;
171+
col += u32::from(c.len()) - c.wide_len(enc) as u32;
156172
} else {
157173
// From here on, all utf16 characters come *after* the character we are mapping,
158174
// so we don't need to take them into account
@@ -167,6 +183,9 @@ impl LineIndex {
167183

168184
#[cfg(test)]
169185
mod tests {
186+
use test_utils::skip_slow_tests;
187+
188+
use super::WideEncoding::{Utf16, Utf32};
170189
use super::*;
171190

172191
#[test]
@@ -210,67 +229,59 @@ mod tests {
210229
const C: char = 'x';
211230
",
212231
);
213-
assert_eq!(col_index.utf16_lines.len(), 0);
232+
assert_eq!(col_index.line_wide_chars.len(), 0);
214233
}
215234

216235
#[test]
217-
fn test_single_char() {
218-
let col_index = LineIndex::new(
219-
"
220-
const C: char = 'メ';
221-
",
222-
);
223-
224-
assert_eq!(col_index.utf16_lines.len(), 1);
225-
assert_eq!(col_index.utf16_lines[&1].len(), 1);
226-
assert_eq!(col_index.utf16_lines[&1][0], Utf16Char { start: 17.into(), end: 20.into() });
227-
228-
// UTF-8 to UTF-16, no changes
229-
assert_eq!(col_index.utf8_to_utf16_col(1, 15.into()), 15);
230-
231-
// UTF-8 to UTF-16
232-
assert_eq!(col_index.utf8_to_utf16_col(1, 22.into()), 20);
233-
234-
// UTF-16 to UTF-8, no changes
235-
assert_eq!(col_index.utf16_to_utf8_col(1, 15), TextSize::from(15));
236-
237-
// UTF-16 to UTF-8
238-
assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(21));
239-
240-
let col_index = LineIndex::new("a𐐏b");
241-
assert_eq!(col_index.utf16_to_utf8_col(0, 3), TextSize::from(5));
242-
}
243-
244-
#[test]
245-
fn test_string() {
246-
let col_index = LineIndex::new(
247-
"
248-
const C: char = \"メ メ\";
249-
",
250-
);
251-
252-
assert_eq!(col_index.utf16_lines.len(), 1);
253-
assert_eq!(col_index.utf16_lines[&1].len(), 2);
254-
assert_eq!(col_index.utf16_lines[&1][0], Utf16Char { start: 17.into(), end: 20.into() });
255-
assert_eq!(col_index.utf16_lines[&1][1], Utf16Char { start: 21.into(), end: 24.into() });
256-
257-
// UTF-8 to UTF-16
258-
assert_eq!(col_index.utf8_to_utf16_col(1, 15.into()), 15);
259-
260-
assert_eq!(col_index.utf8_to_utf16_col(1, 21.into()), 19);
261-
assert_eq!(col_index.utf8_to_utf16_col(1, 25.into()), 21);
262-
263-
assert!(col_index.utf8_to_utf16_col(2, 15.into()) == 15);
264-
265-
// UTF-16 to UTF-8
266-
assert_eq!(col_index.utf16_to_utf8_col(1, 15), TextSize::from(15));
236+
fn test_every_chars() {
237+
if skip_slow_tests() {
238+
return;
239+
}
267240

268-
// メ UTF-8: 0xE3 0x83 0xA1, UTF-16: 0x30E1
269-
assert_eq!(col_index.utf16_to_utf8_col(1, 17), TextSize::from(17)); // first メ at 17..20
270-
assert_eq!(col_index.utf16_to_utf8_col(1, 18), TextSize::from(20)); // space
271-
assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(21)); // second メ at 21..24
241+
let text: String = {
242+
let mut chars: Vec<char> = ((0 as char)..char::MAX).collect(); // Neat!
243+
chars.extend("\n".repeat(chars.len() / 16).chars());
244+
let mut rng = oorandom::Rand32::new(stdx::rand::seed());
245+
stdx::rand::shuffle(&mut chars, |i| rng.rand_range(0..i as u32) as usize);
246+
chars.into_iter().collect()
247+
};
248+
assert!(text.contains('💩')); // Sanity check.
249+
250+
let line_index = LineIndex::new(&text);
251+
252+
let mut lin_col = LineCol { line: 0, col: 0 };
253+
let mut col_utf16 = 0;
254+
let mut col_utf32 = 0;
255+
for (offset, c) in text.char_indices() {
256+
let got_offset = line_index.offset(lin_col).unwrap();
257+
assert_eq!(usize::from(got_offset), offset);
258+
259+
let got_lin_col = line_index.line_col(got_offset);
260+
assert_eq!(got_lin_col, lin_col);
261+
262+
for enc in [Utf16, Utf32] {
263+
let wide_lin_col = line_index.to_wide(enc, lin_col);
264+
let got_lin_col = line_index.to_utf8(enc, wide_lin_col);
265+
assert_eq!(got_lin_col, lin_col);
266+
267+
let want_col = match enc {
268+
Utf16 => col_utf16,
269+
Utf32 => col_utf32,
270+
};
271+
assert_eq!(wide_lin_col.col, want_col)
272+
}
272273

273-
assert_eq!(col_index.utf16_to_utf8_col(2, 15), TextSize::from(15));
274+
if c == '\n' {
275+
lin_col.line += 1;
276+
lin_col.col = 0;
277+
col_utf16 = 0;
278+
col_utf32 = 0;
279+
} else {
280+
lin_col.col += c.len_utf8() as u32;
281+
col_utf16 += c.len_utf16() as u32;
282+
col_utf32 += 1;
283+
}
284+
}
274285
}
275286

276287
#[test]

crates/ide/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ pub use ide_db::{
115115
SourceRoot, SourceRootId,
116116
},
117117
label::Label,
118-
line_index::{LineCol, LineColUtf16, LineIndex},
118+
line_index::{LineCol, LineIndex},
119119
search::{ReferenceCategory, SearchScope},
120120
source_change::{FileSystemEdit, SourceChange},
121121
symbol_index::Query,

crates/ide/src/shuffle_crate_graph.rs

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ pub(crate) fn shuffle_crate_graph(db: &mut RootDatabase) {
1818
let crate_graph = db.crate_graph();
1919

2020
let mut shuffled_ids = crate_graph.iter().collect::<Vec<_>>();
21-
shuffle(&mut shuffled_ids);
21+
22+
let mut rng = oorandom::Rand32::new(stdx::rand::seed());
23+
stdx::rand::shuffle(&mut shuffled_ids, |i| rng.rand_range(0..i as u32) as usize);
2224

2325
let mut new_graph = CrateGraph::default();
2426

@@ -52,21 +54,3 @@ pub(crate) fn shuffle_crate_graph(db: &mut RootDatabase) {
5254

5355
db.set_crate_graph_with_durability(Arc::new(new_graph), Durability::HIGH);
5456
}
55-
56-
fn shuffle<T>(slice: &mut [T]) {
57-
let mut rng = oorandom::Rand32::new(seed());
58-
59-
let mut remaining = slice.len() - 1;
60-
while remaining > 0 {
61-
let index = rng.rand_range(0..remaining as u32);
62-
slice.swap(remaining, index as usize);
63-
remaining -= 1;
64-
}
65-
}
66-
67-
fn seed() -> u64 {
68-
use std::collections::hash_map::RandomState;
69-
use std::hash::{BuildHasher, Hasher};
70-
71-
RandomState::new().build_hasher().finish()
72-
}

crates/rust-analyzer/src/caps.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
//! Advertises the capabilities of the LSP Server.
2+
use ide_db::line_index::WideEncoding;
23
use lsp_types::{
34
CallHierarchyServerCapability, ClientCapabilities, CodeActionKind, CodeActionOptions,
45
CodeActionProviderCapability, CodeLensOptions, CompletionOptions,
@@ -16,16 +17,19 @@ use lsp_types::{
1617
use serde_json::json;
1718

1819
use crate::config::{Config, RustfmtConfig};
19-
use crate::lsp_ext::supports_utf8;
20+
use crate::line_index::PositionEncoding;
21+
use crate::lsp_ext::negotiated_encoding;
2022
use crate::semantic_tokens;
2123

2224
pub fn server_capabilities(config: &Config) -> ServerCapabilities {
2325
ServerCapabilities {
24-
position_encoding: if supports_utf8(config.caps()) {
25-
Some(PositionEncodingKind::UTF8)
26-
} else {
27-
None
28-
},
26+
position_encoding: Some(match negotiated_encoding(config.caps()) {
27+
PositionEncoding::Utf8 => PositionEncodingKind::UTF8,
28+
PositionEncoding::Wide(wide) => match wide {
29+
WideEncoding::Utf16 => PositionEncodingKind::UTF16,
30+
WideEncoding::Utf32 => PositionEncodingKind::UTF32,
31+
},
32+
}),
2933
text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
3034
open_close: Some(true),
3135
change: Some(TextDocumentSyncKind::INCREMENTAL),

0 commit comments

Comments
 (0)