only-semantic 0.4.0

Semantic analysis for the only task language.
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use std::collections::HashSet;

use only_diagnostic::{Diagnostic, DiagnosticCode, DiagnosticPhase, DiagnosticSeverity};
use text_size::TextRange;

use crate::interpolation::scan_interpolations;
use crate::{
    DirectiveAst, DirectiveKind, DocumentAst, GuardKind, MetadataKind, ShellKind, ShellOperator,
    ShellSelection, SymbolIndex, TaskAst,
};

pub(crate) fn validate_document(document: &DocumentAst, symbols: &SymbolIndex) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    let task_names: HashSet<_> = symbols.tasks.iter().map(|task| task.name.clone()).collect();
    let global_task_names: HashSet<_> = document
        .tasks
        .iter()
        .filter(|task| task.namespace.is_none())
        .map(|task| task.name.clone())
        .collect();
    let supports_command_blocks =
        document
            .directives
            .iter()
            .find_map(|directive| match directive {
                DirectiveAst::Version { major, minor, .. } => Some(*major > 0 || *minor >= 2),
                DirectiveAst::Shell { .. } => None,
                DirectiveAst::Variable { .. } => None,
            })
            == Some(true);
    let supports_engineering = document.directives.iter().any(|directive| {
        matches!(directive, DirectiveAst::Version { major, minor, .. } if *major > 0 || *minor >= 3)
    });
    let supports_result_metadata = document.directives.iter().any(|directive| {
        matches!(directive, DirectiveAst::Version { major, minor, .. } if *major > 0 || *minor >= 4)
    });
    let globals = document
        .directives
        .iter()
        .filter_map(|directive| match directive {
            DirectiveAst::Variable { name, .. } => Some(name.clone()),
            _ => None,
        })
        .collect::<HashSet<_>>();

    for directive in &document.directives {
        if let DirectiveAst::Shell { shell, range } = directive {
            validate_shell(
                &ShellSelection::required(shell.clone()),
                *range,
                &mut diagnostics,
            );
        }
    }

    if !supports_engineering && (!globals.is_empty() || document.uses_braced_namespaces) {
        let range = document
            .directives
            .iter()
            .find_map(|directive| match directive {
                DirectiveAst::Variable { range, .. } => Some(*range),
                _ => None,
            })
            .or_else(|| document.namespaces.first().map(|namespace| namespace.range))
            .unwrap_or_default();
        diagnostics.push(error(
            "semantic.engineering-version",
            "this syntax needs `!version 0.3` or newer".to_string(),
            range,
        ));
    }

    for namespace in &document.namespaces {
        if namespace.is_group && !supports_result_metadata {
            diagnostics.push(error(
                "semantic.group-version",
                "group declarations need `!version 0.4` or newer".to_string(),
                namespace.range,
            ));
        }
        if supports_engineering && !namespace.is_braced {
            diagnostics.push(error(
                "namespace.missing-open-brace",
                format!("group {} must use '{{' and end with '}}'", namespace.name),
                namespace.range,
            ));
        } else if supports_engineering && namespace.close_range.is_none() {
            diagnostics.push(error(
                "namespace.missing-close",
                format!("namespace '{}' must end with '}}'", namespace.name),
                namespace.range,
            ));
        }
        if supports_result_metadata && !namespace.is_group {
            diagnostics.push(error(
                "namespace.group-required",
                format!("use `group {} {{` for a 0.4 group", namespace.name),
                namespace.range,
            ));
        }
        validate_metadata(
            &namespace.metadata,
            namespace.range,
            &globals,
            supports_result_metadata,
            false,
            &mut diagnostics,
        );
        if global_task_names.contains(&namespace.name) {
            diagnostics.push(error(
                "semantic.namespace-conflict",
                format!(
                    "task and namespace cannot both be named '{}'",
                    namespace.name
                ),
                namespace.range,
            ));
        }
    }

    for task in &document.tasks {
        validate_task(
            task,
            &task_names,
            &globals,
            supports_command_blocks,
            supports_engineering,
            supports_result_metadata,
            &mut diagnostics,
        );
    }

    report_duplicate_directives(document, &mut diagnostics);
    report_duplicate_variables(document, &mut diagnostics);
    report_duplicate_tasks(document, &mut diagnostics);
    diagnostics
}

fn validate_task(
    task: &TaskAst,
    task_names: &HashSet<smol_str::SmolStr>,
    globals: &HashSet<smol_str::SmolStr>,
    supports_command_blocks: bool,
    supports_engineering: bool,
    supports_result_metadata: bool,
    diagnostics: &mut Vec<Diagnostic>,
) {
    validate_metadata(
        &task.metadata,
        task.range,
        globals,
        supports_result_metadata,
        true,
        diagnostics,
    );

    let mut params = HashSet::new();
    for (index, param) in task.params.iter().enumerate() {
        if !params.insert(param.name.clone()) {
            diagnostics.push(error(
                "semantic.duplicate-parameter",
                format!(
                    "parameter '{}' is used more than once in task '{}'",
                    param.name,
                    task.qualified_name()
                ),
                task.range,
            ));
        }

        if param.is_slice && index + 1 != task.params.len() {
            diagnostics.push(error(
                "semantic.slice-parameter-position",
                format!(
                    "slice parameter '{}..' must be last in task '{}'",
                    param.name,
                    task.qualified_name()
                ),
                task.range,
            ));
        }

        if param.is_slice && param.default_value.is_some() {
            diagnostics.push(error(
                "semantic.slice-parameter-default",
                format!("slice parameter '{}..' cannot have a default", param.name),
                task.range,
            ));
        }
    }

    let uses_shell_fallback = task
        .shell
        .as_ref()
        .is_some_and(|shell| shell.selection.operator == ShellOperator::Fallback);
    if !supports_engineering
        && (task.guards.len() > 1 || task.uses_multiline_header || uses_shell_fallback)
    {
        diagnostics.push(error(
            "semantic.engineering-version",
            "this syntax needs `!version 0.3` or newer".to_string(),
            task.range,
        ));
    }

    if let Some(shell) = &task.shell {
        validate_shell(&shell.selection, shell.range, diagnostics);
    }

    let mut guards = HashSet::new();
    for guard in &task.guards {
        if !guard.kind.is_supported() {
            diagnostics.push(error(
                "semantic.unknown-guard",
                format!(
                    "guard '@{}' is not supported; use {}",
                    guard.kind,
                    supported_guards()
                ),
                guard.range,
            ));
        }

        let key = format!("{}:{}", guard.kind, guard.argument);
        if !guards.insert(key) {
            diagnostics.push(error(
                "semantic.duplicate-guard",
                format!(
                    "guard '@{}(\"{}\")' is repeated",
                    guard.kind, guard.argument
                ),
                guard.range,
            ));
        }
    }

    for dependency in &task.dependencies {
        if !task_names.contains(&dependency.name) {
            diagnostics.push(error(
                "semantic.undefined-dependency",
                format!(
                    "task '{}' depends on missing task '{}'",
                    task.qualified_name(),
                    dependency.name
                ),
                dependency.range,
            ));
        }
    }

    for step in &task.steps {
        if let crate::TaskStepAst::CommandBlock(block) = step
            && !supports_command_blocks
        {
            diagnostics.push(error(
                "semantic.command-block-version",
                "command blocks need `!version 0.2` or newer".to_string(),
                block.range,
            ));
        }
        let interpolations = match step {
            crate::TaskStepAst::Command(command) => &command.interpolations,
            crate::TaskStepAst::CommandBlock(block) => &block.interpolations,
        };
        for interpolation in interpolations {
            if !params.contains(&interpolation.name) && !globals.contains(&interpolation.name) {
                diagnostics.push(error(
                    "semantic.undefined-variable",
                    format!("variable '{}' is not defined", interpolation.name),
                    interpolation.range,
                ));
            }
        }
    }
}

fn validate_metadata(
    metadata: &crate::TaskMetadataAst,
    range: TextRange,
    globals: &HashSet<smol_str::SmolStr>,
    supports_result_metadata: bool,
    allow_result_messages: bool,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if metadata.has_structured_fields && !supports_result_metadata {
        diagnostics.push(error(
            "semantic.result-metadata-version",
            "task metadata needs `!version 0.4` or newer".to_string(),
            range,
        ));
    }
    if metadata.desc.is_some() && metadata.help.is_none() {
        diagnostics.push(error(
            "semantic.metadata-help-required",
            "`[help]` is required when `[desc]` is used".to_string(),
            range,
        ));
    }
    if metadata.help_count > 1 {
        diagnostics.push(error(
            "semantic.duplicate-help",
            "`[help]` can be used only once".to_string(),
            range,
        ));
    }
    for field in &metadata.unknown_fields {
        diagnostics.push(error(
            "semantic.unknown-metadata-field",
            format!(
                "unknown metadata field `{field}`; expected {}",
                MetadataKind::expected_list()
            ),
            range,
        ));
    }
    if !allow_result_messages && (metadata.pass.is_some() || metadata.fail.is_some()) {
        diagnostics.push(error(
            "semantic.group-result-metadata",
            "`[pass]` and `[fail]` are only valid on tasks".to_string(),
            range,
        ));
    }
    for (field, text) in [
        ("help", metadata.help.as_ref()),
        ("desc", metadata.desc.as_ref()),
        ("pass", metadata.pass.as_ref()),
        ("fail", metadata.fail.as_ref()),
    ] {
        let Some(text) = text else { continue };
        for interpolation in scan_interpolations(text.as_str()) {
            if !globals.contains(&interpolation.name) {
                diagnostics.push(error(
                    "semantic.metadata-variable",
                    format!(
                        "{field} can only use a global variable named '{}'",
                        interpolation.name
                    ),
                    range,
                ));
            }
        }
    }
}

fn validate_shell(shell: &ShellSelection, range: TextRange, diagnostics: &mut Vec<Diagnostic>) {
    if !shell.kind.is_supported() {
        diagnostics.push(error(
            "semantic.unknown-shell",
            format!(
                "shell '{}' is not supported; use {}",
                shell.kind,
                supported_shells()
            ),
            range,
        ));
    } else if shell.operator == ShellOperator::Fallback && shell.kind.fallback().is_none() {
        diagnostics.push(error(
            "semantic.invalid-shell-fallback",
            format!(
                "shell '{}' has no fallback; use `shell={}`",
                shell.kind, shell.kind
            ),
            range,
        ));
    }
}

fn supported_shells() -> String {
    format_choices(
        ShellKind::SUPPORTED
            .iter()
            .map(|shell| format!("'{}'", shell.as_str()))
            .collect(),
    )
}

fn supported_guards() -> String {
    format_choices(
        GuardKind::SUPPORTED
            .iter()
            .map(|guard| format!("'@{}'", guard.as_str()))
            .collect(),
    )
}

fn format_choices(mut choices: Vec<String>) -> String {
    let Some(last) = choices.pop() else {
        return String::new();
    };
    if choices.is_empty() {
        return last;
    }
    format!("{}, or {last}", choices.join(", "))
}

fn error(code: &str, message: String, range: TextRange) -> Diagnostic {
    Diagnostic::new(
        DiagnosticSeverity::Error,
        DiagnosticCode::new(code),
        message,
        DiagnosticPhase::Semantic,
        range,
    )
}

fn report_duplicate_tasks(document: &DocumentAst, diagnostics: &mut Vec<Diagnostic>) {
    let mut seen = std::collections::HashMap::<String, &TaskAst>::new();
    let mut seen_guards = std::collections::HashMap::<(String, String), &TaskAst>::new();

    for task in &document.tasks {
        if !task.guards.is_empty() {
            let guard_key = (task.qualified_name().to_string(), render_guards(task));
            if seen_guards.insert(guard_key, task).is_some() {
                diagnostics.push(error(
                    "semantic.ambiguous-guard",
                    format!(
                        "task '{}' has the same guard more than once",
                        task.qualified_name()
                    ),
                    task.range,
                ));
            }
        }

        let key = task_signature_key(task);
        if seen.insert(key, task).is_some() {
            diagnostics.push(error(
                "semantic.duplicate-task",
                format!("task '{}' is defined more than once", task.qualified_name()),
                task.range,
            ));
        }
    }
}

fn report_duplicate_directives(document: &DocumentAst, diagnostics: &mut Vec<Diagnostic>) {
    let mut seen = std::collections::HashMap::<DirectiveKind, TextRange>::new();

    for directive in &document.directives {
        let (name, range) = match directive {
            DirectiveAst::Version { .. } => continue,
            DirectiveAst::Shell { range, .. } => (DirectiveKind::Shell, *range),
            DirectiveAst::Variable { .. } => continue,
        };

        if let Some(previous_range) = seen.insert(name.clone(), range) {
            diagnostics.push(error(
                "semantic.duplicate-directive",
                format!("`!{name}` is used more than once"),
                previous_range.cover(range),
            ));
        }
    }
}

fn report_duplicate_variables(document: &DocumentAst, diagnostics: &mut Vec<Diagnostic>) {
    let mut seen = std::collections::HashMap::<&str, TextRange>::new();
    for directive in &document.directives {
        let DirectiveAst::Variable { name, range, .. } = directive else {
            continue;
        };
        if let Some(previous) = seen.insert(name.as_str(), *range) {
            diagnostics.push(error(
                "variable.duplicate",
                format!("variable '{name}' is used more than once"),
                previous.cover(*range),
            ));
        }
    }
}

fn task_signature_key(task: &TaskAst) -> String {
    let parameter_names = task
        .params
        .iter()
        .map(
            |parameter| match (parameter.is_slice, &parameter.default_value) {
                (true, Some(default)) => format!("{}..={default}", parameter.name),
                (true, None) => format!("{}..", parameter.name),
                (false, Some(default)) => format!("{}={default}", parameter.name),
                (false, None) => parameter.name.to_string(),
            },
        )
        .collect::<Vec<_>>()
        .join(",");

    let guard = render_guards(task);

    format!("{}|{}|{}", task.qualified_name(), parameter_names, guard)
}

fn render_guards(task: &TaskAst) -> String {
    task.guards
        .iter()
        .map(|guard| format!("{}:{}", guard.kind, guard.argument))
        .collect::<Vec<_>>()
        .join("?")
}