shuck-server 0.1.0

Language server scaffold for shuck
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use anyhow::Error;
use lsp_types as types;
use shuck_ast::{Command, CompoundCommand, Span, Stmt, StmtSeq, TextRange};
use shuck_formatter::FormattedSource;

use crate::edit::RangeExt;
use crate::session::{Client, DocumentSnapshot};

pub(crate) type FormatResponse = Option<Vec<types::TextEdit>>;

pub(crate) fn format_document(
    snapshot: DocumentSnapshot,
    _client: &Client,
    _params: types::DocumentFormattingParams,
) -> crate::server::Result<FormatResponse> {
    let query = snapshot.query();
    let file_path = query.file_path();
    if snapshot
        .shuck_settings()
        .is_format_excluded(file_path.as_deref())
    {
        return Ok(None);
    }
    let source = query.document().contents();
    let formatted = shuck_formatter::format_source(
        source,
        file_path.as_deref(),
        snapshot.shuck_settings().formatter(),
    )
    .map_err(Error::new)?;

    Ok(Some(match formatted {
        FormattedSource::Unchanged => Vec::new(),
        FormattedSource::Formatted(code) => crate::edit::single_replacement_edit(
            source,
            &code,
            query.document().index(),
            snapshot.encoding(),
        )
        .into_iter()
        .collect(),
    }))
}

pub(crate) fn format_range(
    snapshot: DocumentSnapshot,
    _client: &Client,
    params: types::DocumentRangeFormattingParams,
) -> crate::server::Result<FormatResponse> {
    let file_path = snapshot.query().file_path();
    if snapshot
        .shuck_settings()
        .is_format_excluded(file_path.as_deref())
    {
        return Ok(None);
    }
    let Some(analysis) = snapshot.analysis() else {
        return Ok(None);
    };
    let source = analysis.source();
    let requested = params
        .range
        .to_text_range(source, analysis.line_index(), snapshot.encoding());
    let Some(statement_span) =
        smallest_statement_span_containing(&analysis.parse_result().file.body, requested)
    else {
        return Ok(None);
    };
    let statement_range = statement_span.to_range();
    let statement_source =
        &source[usize::from(statement_range.start())..usize::from(statement_range.end())];
    let formatted = shuck_formatter::format_source(
        statement_source,
        file_path.as_deref(),
        snapshot.shuck_settings().formatter(),
    )
    .map_err(Error::new)?;

    Ok(Some(format_response_for_range(
        source,
        statement_range,
        formatted,
        analysis.line_index(),
        snapshot.encoding(),
    )))
}

fn format_response_for_range(
    source: &str,
    range: TextRange,
    formatted: FormattedSource,
    line_index: &shuck_indexer::LineIndex,
    encoding: crate::PositionEncoding,
) -> Vec<types::TextEdit> {
    match formatted {
        FormattedSource::Unchanged => Vec::new(),
        FormattedSource::Formatted(code) => crate::edit::single_replacement_edit_in_range(
            source, range, &code, line_index, encoding,
        )
        .into_iter()
        .collect(),
    }
}

fn smallest_statement_span_containing(body: &StmtSeq, range: TextRange) -> Option<Span> {
    let mut best = None;
    collect_statement_span(body, range, &mut best);
    best
}

fn collect_statement_span(body: &StmtSeq, range: TextRange, best: &mut Option<Span>) {
    for stmt in body.as_slice() {
        if !span_contains_text_range(stmt.span, range) {
            continue;
        }
        record_smaller_span(best, stmt.span);
        collect_nested_statement_spans(stmt, range, best);
    }
}

fn collect_nested_statement_spans(stmt: &Stmt, range: TextRange, best: &mut Option<Span>) {
    match &stmt.command {
        Command::Binary(command) => {
            collect_nested_statement_spans(&command.left, range, best);
            collect_nested_statement_spans(&command.right, range, best);
        }
        Command::Compound(command) => collect_compound_statement_spans(command, range, best),
        Command::Function(command) => collect_nested_statement_spans(&command.body, range, best),
        Command::AnonymousFunction(command) => {
            collect_nested_statement_spans(&command.body, range, best);
        }
        Command::Simple(_) | Command::Builtin(_) | Command::Decl(_) => {}
    }
}

fn collect_compound_statement_spans(
    command: &CompoundCommand,
    range: TextRange,
    best: &mut Option<Span>,
) {
    match command {
        CompoundCommand::If(command) => {
            collect_statement_span(&command.condition, range, best);
            collect_statement_span(&command.then_branch, range, best);
            for (condition, body) in &command.elif_branches {
                collect_statement_span(condition, range, best);
                collect_statement_span(body, range, best);
            }
            if let Some(body) = &command.else_branch {
                collect_statement_span(body, range, best);
            }
        }
        CompoundCommand::For(command) => collect_statement_span(&command.body, range, best),
        CompoundCommand::Repeat(command) => collect_statement_span(&command.body, range, best),
        CompoundCommand::Foreach(command) => collect_statement_span(&command.body, range, best),
        CompoundCommand::ArithmeticFor(command) => {
            collect_statement_span(&command.body, range, best)
        }
        CompoundCommand::While(command) => {
            collect_statement_span(&command.condition, range, best);
            collect_statement_span(&command.body, range, best);
        }
        CompoundCommand::Until(command) => {
            collect_statement_span(&command.condition, range, best);
            collect_statement_span(&command.body, range, best);
        }
        CompoundCommand::Case(command) => {
            for item in &command.cases {
                collect_statement_span(&item.body, range, best);
            }
        }
        CompoundCommand::Select(command) => collect_statement_span(&command.body, range, best),
        CompoundCommand::Subshell(body) | CompoundCommand::BraceGroup(body) => {
            collect_statement_span(body, range, best);
        }
        CompoundCommand::Time(command) => {
            if let Some(command) = &command.command {
                collect_nested_statement_spans(command, range, best);
            }
        }
        CompoundCommand::Coproc(command) => {
            collect_nested_statement_spans(&command.body, range, best);
        }
        CompoundCommand::Always(command) => {
            collect_statement_span(&command.body, range, best);
            collect_statement_span(&command.always_body, range, best);
        }
        CompoundCommand::Arithmetic(_) | CompoundCommand::Conditional(_) => {}
    }
}

fn record_smaller_span(best: &mut Option<Span>, candidate: Span) {
    if best.is_none_or(|current| span_width(candidate) < span_width(current)) {
        *best = Some(candidate);
    }
}

fn span_width(span: Span) -> usize {
    span.end.offset().saturating_sub(span.start.offset())
}

fn span_contains_text_range(span: Span, range: TextRange) -> bool {
    span.start.offset() <= usize::from(range.start())
        && usize::from(range.end()) <= span.end.offset()
}

#[cfg(test)]
mod tests {
    use crossbeam::channel;
    use lsp_types::{ClientCapabilities, PositionEncodingKind, Url};

    use super::*;
    use crate::{
        Client, GlobalOptions, PositionEncoding, Session, TextDocument, Workspace, Workspaces,
    };

    #[test]
    fn document_formatting_uses_shuck_formatter() {
        let (main_loop_sender, _main_loop_receiver) = channel::unbounded();
        let (client_sender, _client_receiver) = channel::unbounded();
        let client = Client::new(main_loop_sender, client_sender);
        let workspace_root = std::env::temp_dir().join("shuck-server-format-document-tests");
        let workspace_uri =
            Url::from_file_path(&workspace_root).expect("workspace path should convert to a URL");
        let workspaces = Workspaces::new(vec![Workspace::default(workspace_uri)]);
        let global = GlobalOptions::default().into_settings(client.clone());
        let mut session = Session::new(
            &ClientCapabilities::default(),
            PositionEncoding::UTF16,
            global,
            &workspaces,
            &client,
        )
        .expect("test session should initialize");

        let uri = Url::from_file_path(workspace_root.join("script.sh"))
            .expect("script path should convert to a URL");
        session.open_text_document(
            uri.clone(),
            TextDocument::new("if true; then\necho ok\nfi\n".to_owned(), 1)
                .with_language_id("shellscript"),
        );
        let snapshot = session
            .take_snapshot(uri.clone())
            .expect("test document should produce a snapshot");

        let edits = format_document(
            snapshot,
            &client,
            types::DocumentFormattingParams {
                text_document: types::TextDocumentIdentifier { uri },
                options: types::FormattingOptions::default(),
                work_done_progress_params: types::WorkDoneProgressParams::default(),
            },
        )
        .expect("document formatting should succeed")
        .expect("document formatting should return an edit list");

        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].range.start, types::Position::new(1, 0));
        assert_eq!(edits[0].range.end, types::Position::new(1, 0));
        assert_eq!(edits[0].new_text, "\t");
    }

    #[test]
    fn formatting_returns_none_for_config_excluded_document() {
        let tempdir = tempfile::tempdir().expect("workspace should be created");
        std::fs::write(
            tempdir.path().join("shuck.toml"),
            "[format]\nexclude = ['**/*p10k.zsh']\n",
        )
        .expect("config should be written");

        let (main_loop_sender, _main_loop_receiver) = channel::unbounded();
        let (client_sender, _client_receiver) = channel::unbounded();
        let client = Client::new(main_loop_sender, client_sender);
        let workspace_uri =
            Url::from_file_path(tempdir.path()).expect("workspace path should convert to a URL");
        let workspaces = Workspaces::new(vec![Workspace::default(workspace_uri)]);
        let global = GlobalOptions::default().into_settings(client.clone());
        let mut session = Session::new(
            &ClientCapabilities::default(),
            PositionEncoding::UTF16,
            global,
            &workspaces,
            &client,
        )
        .expect("test session should initialize");

        let uri = Url::from_file_path(tempdir.path().join(".p10k.zsh"))
            .expect("script path should convert to a URL");
        session.open_text_document(
            uri.clone(),
            TextDocument::new("if true; then\nprint ok\nfi\n".to_owned(), 1)
                .with_language_id("shellscript"),
        );

        let document_response = format_document(
            session
                .take_snapshot(uri.clone())
                .expect("test document should produce a snapshot"),
            &client,
            types::DocumentFormattingParams {
                text_document: types::TextDocumentIdentifier { uri: uri.clone() },
                options: types::FormattingOptions::default(),
                work_done_progress_params: types::WorkDoneProgressParams::default(),
            },
        )
        .expect("document formatting should succeed");
        assert!(document_response.is_none());

        let range_response = format_range(
            session
                .take_snapshot(uri.clone())
                .expect("test document should produce a snapshot"),
            &client,
            types::DocumentRangeFormattingParams {
                text_document: types::TextDocumentIdentifier { uri },
                range: types::Range::new(types::Position::new(0, 0), types::Position::new(2, 2)),
                options: types::FormattingOptions::default(),
                work_done_progress_params: types::WorkDoneProgressParams::default(),
            },
        )
        .expect("range formatting should succeed");
        assert!(range_response.is_none());
    }

    #[test]
    fn range_formatting_returns_empty_edits_for_already_formatted_buffer() {
        let (main_loop_sender, _main_loop_receiver) = channel::unbounded();
        let (client_sender, _client_receiver) = channel::unbounded();
        let client = Client::new(main_loop_sender, client_sender);
        let workspace_root = std::env::temp_dir().join("shuck-server-format-tests");
        let workspace_uri =
            Url::from_file_path(&workspace_root).expect("workspace path should convert to a URL");
        let workspaces = Workspaces::new(vec![Workspace::default(workspace_uri)]);
        let global = GlobalOptions::default().into_settings(client.clone());
        let mut session = Session::new(
            &ClientCapabilities {
                general: Some(lsp_types::GeneralClientCapabilities {
                    position_encodings: Some(vec![PositionEncodingKind::UTF16]),
                    ..Default::default()
                }),
                ..Default::default()
            },
            PositionEncoding::UTF16,
            global,
            &workspaces,
            &client,
        )
        .expect("test session should initialize");

        let uri = Url::from_file_path(workspace_root.join("script.sh"))
            .expect("script path should convert to a URL");
        session.open_text_document(
            uri.clone(),
            TextDocument::new("echo hi\n".to_owned(), 1).with_language_id("shellscript"),
        );
        let snapshot = session
            .take_snapshot(uri.clone())
            .expect("test document should produce a snapshot");

        let edits = format_range(
            snapshot,
            &client,
            types::DocumentRangeFormattingParams {
                text_document: types::TextDocumentIdentifier { uri },
                range: types::Range::new(types::Position::new(0, 0), types::Position::new(0, 7)),
                options: types::FormattingOptions::default(),
                work_done_progress_params: types::WorkDoneProgressParams::default(),
            },
        )
        .expect("range formatting should succeed")
        .expect("range formatting should return an edit list");

        assert!(edits.is_empty());
    }

    #[test]
    fn range_formatting_returns_none_for_ranges_without_one_complete_statement() {
        let (main_loop_sender, _main_loop_receiver) = channel::unbounded();
        let (client_sender, _client_receiver) = channel::unbounded();
        let client = Client::new(main_loop_sender, client_sender);
        let workspace_root = std::env::temp_dir().join("shuck-server-format-tests-partial");
        let workspace_uri =
            Url::from_file_path(&workspace_root).expect("workspace path should convert to a URL");
        let workspaces = Workspaces::new(vec![Workspace::default(workspace_uri)]);
        let global = GlobalOptions::default().into_settings(client.clone());
        let mut session = Session::new(
            &ClientCapabilities::default(),
            PositionEncoding::UTF16,
            global,
            &workspaces,
            &client,
        )
        .expect("test session should initialize");

        let uri = Url::from_file_path(workspace_root.join("script.sh"))
            .expect("script path should convert to a URL");
        session.open_text_document(
            uri.clone(),
            TextDocument::new("echo one\necho two\n".to_owned(), 1).with_language_id("shellscript"),
        );
        let snapshot = session
            .take_snapshot(uri.clone())
            .expect("test document should produce a snapshot");

        let edits = format_range(
            snapshot,
            &client,
            types::DocumentRangeFormattingParams {
                text_document: types::TextDocumentIdentifier { uri },
                range: types::Range::new(types::Position::new(0, 2), types::Position::new(1, 2)),
                options: types::FormattingOptions::default(),
                work_done_progress_params: types::WorkDoneProgressParams::default(),
            },
        )
        .expect("range formatting should succeed");

        assert!(edits.is_none());
    }

    #[test]
    fn range_formatting_edit_helper_does_not_escape_statement_range() {
        let source = "echo one\necho two\n";
        let index = shuck_indexer::LineIndex::new(source);
        let edits = format_response_for_range(
            source,
            TextRange::new(shuck_ast::TextSize::new(9), shuck_ast::TextSize::new(18)),
            FormattedSource::Formatted("printf two\n".to_owned()),
            &index,
            PositionEncoding::UTF16,
        );

        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].range.start, types::Position::new(1, 0));
        assert_eq!(edits[0].range.end, types::Position::new(1, 4));
        assert_eq!(edits[0].new_text, "printf");
    }
}