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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// completion:
// static: flag names, command names
// dynamic: argument values, positional item values
//
// for static when running collect any parser that fails
//
// OR: combine completions
// AND: usual logic without shortcircuits
//
// for static completion it's enough to collect items
// for argument completion - only one argument(Comp::Meta) should be active at once
//
// for rendering prefer longer version of names
//
// complete short names to long names if possible

use crate::{
    args::{Arg, State},
    complete_shell::{render_bash, render_fish, render_simple, render_test, render_zsh},
    item::ShortLong,
    parsers::NamedArg,
    Doc, ShellComp,
};
use std::ffi::OsStr;

#[derive(Clone, Debug)]
pub(crate) struct Complete {
    /// completions accumulated so far
    comps: Vec<Comp>,
    pub(crate) output_rev: usize,

    /// don't try to suggest any more positional items after there's a positional item failure
    /// or parsing in progress
    pub(crate) no_pos_ahead: bool,
}

impl Complete {
    pub(crate) fn new(output_rev: usize) -> Self {
        Self {
            comps: Vec::new(),
            output_rev,
            no_pos_ahead: false,
        }
    }
}

impl State {
    /// Add a new completion hint for flag, if needed
    pub(crate) fn push_flag(&mut self, named: &NamedArg) {
        let depth = self.depth();
        if let Some(comp) = self.comp_mut() {
            comp.comps.push(Comp::Flag {
                extra: CompExtra {
                    depth,
                    group: None,
                    help: named.help.as_ref().and_then(Doc::to_completion),
                },
                name: ShortLong::from(named),
            });
        }
    }

    /// Add a new completion hint for an argument, if needed
    pub(crate) fn push_argument(&mut self, named: &NamedArg, metavar: &'static str) {
        let depth = self.depth();
        if let Some(comp) = self.comp_mut() {
            comp.comps.push(Comp::Argument {
                extra: CompExtra {
                    depth,
                    group: None,
                    help: named.help.as_ref().and_then(Doc::to_completion),
                },
                metavar,
                name: ShortLong::from(named),
            });
        }
    }

    /// Add a new completion hint for metadata, if needed
    ///
    /// `is_argument` is set to true when we are trying to parse the value and false if
    /// when meta
    pub(crate) fn push_metavar(
        &mut self,
        meta: &'static str,
        help: &Option<Doc>,
        is_argument: bool,
    ) {
        let depth = self.depth();
        if let Some(comp) = self.comp_mut() {
            let extra = CompExtra {
                depth,
                group: None,
                help: help.as_ref().and_then(Doc::to_completion),
            };

            comp.comps.push(Comp::Metavariable {
                extra,
                meta,
                is_argument,
            });
        }
    }

    /// Add a new completion hint for command, if needed
    pub(crate) fn push_command(
        &mut self,
        name: &'static str,
        short: Option<char>,
        help: &Option<Doc>,
    ) {
        let depth = self.depth();
        if let Some(comp) = self.comp_mut() {
            comp.comps.push(Comp::Command {
                extra: CompExtra {
                    depth,
                    group: None,
                    help: help.as_ref().and_then(Doc::to_completion),
                },
                name,
                short,
            });
        }
    }

    /// Clear collected completions if enabled
    pub(crate) fn clear_comps(&mut self) {
        if let Some(comp) = self.comp_mut() {
            comp.comps.clear();
        }
    }

    /// Insert a literal value with some description for completion
    ///
    /// In practice it's "--"
    pub(crate) fn push_pos_sep(&mut self) {
        let depth = self.depth();
        if let Some(comp) = self.comp_mut() {
            comp.comps.push(Comp::Value {
                extra: CompExtra {
                    depth,
                    group: None,
                    help: Some("Positional only items after this token".to_owned()),
                },
                body: "--".to_owned(),
                is_argument: false,
            });
        }
    }

    /// Insert a bunch of items
    pub(crate) fn push_with_group(&mut self, group: &Option<String>, comps: &mut Vec<Comp>) {
        if let Some(comp) = self.comp_mut() {
            for mut item in comps.drain(..) {
                if let Some(group) = group.as_ref() {
                    item.set_group(group.clone());
                }
                comp.comps.push(item);
            }
        }
    }
}

impl Complete {
    pub(crate) fn push_shell(&mut self, op: ShellComp, depth: usize) {
        self.comps.push(Comp::Shell {
            extra: CompExtra {
                depth,
                group: None,
                help: None,
            },
            script: op,
        });
    }

    pub(crate) fn push_value(
        &mut self,
        body: String,
        help: Option<String>,
        group: Option<String>,
        depth: usize,
        is_argument: bool,
    ) {
        self.comps.push(Comp::Value {
            body,
            is_argument,
            extra: CompExtra { depth, group, help },
        });
    }

    pub(crate) fn push_comp(&mut self, comp: Comp) {
        self.comps.push(comp);
    }

    pub(crate) fn extend_comps(&mut self, comps: Vec<Comp>) {
        self.comps.extend(comps);
    }

    pub(crate) fn drain_comps(&mut self) -> std::vec::Drain<Comp> {
        self.comps.drain(0..)
    }

    pub(crate) fn swap_comps(&mut self, other: &mut Vec<Comp>) {
        std::mem::swap(other, &mut self.comps);
    }
}

#[derive(Clone, Debug)]
pub(crate) struct CompExtra {
    /// Used by complete_gen to separate commands from each other
    pub(crate) depth: usize,

    /// Render this option in a group along with all other items with the same name
    pub(crate) group: Option<String>,

    /// help message attached to a completion item
    pub(crate) help: Option<String>,
}

#[derive(Clone, Debug)]
pub(crate) enum Comp {
    /// short or long flag
    Flag {
        extra: CompExtra,
        name: ShortLong,
    },

    /// argument + metadata
    Argument {
        extra: CompExtra,
        name: ShortLong,
        metavar: &'static str,
    },

    ///
    Command {
        extra: CompExtra,
        name: &'static str,
        short: Option<char>,
    },

    /// comes from completed values, part of "dynamic" completion
    Value {
        extra: CompExtra,
        body: String,
        /// values from arguments (say -p=SPEC and user already typed "-p b"
        /// should suppress all other options except for metavaraiables?
        ///
        is_argument: bool,
    },

    Metavariable {
        extra: CompExtra,
        meta: &'static str,
        is_argument: bool,
    },

    Shell {
        extra: CompExtra,
        script: ShellComp,
    },
}

impl Comp {
    /// to avoid leaking items with higher depth into items with lower depth
    fn depth(&self) -> usize {
        match self {
            Comp::Command { extra, .. }
            | Comp::Value { extra, .. }
            | Comp::Flag { extra, .. }
            | Comp::Shell { extra, .. }
            | Comp::Metavariable { extra, .. }
            | Comp::Argument { extra, .. } => extra.depth,
        }
    }

    /// completer needs to replace meta placeholder with actual values - uses this
    ///
    /// value indicates if it's an argument or a positional meta
    pub(crate) fn is_metavar(&self) -> Option<bool> {
        if let Comp::Metavariable { is_argument, .. } = self {
            Some(*is_argument)
        } else {
            None
        }
    }

    pub(crate) fn set_group(&mut self, group: String) {
        let extra = match self {
            Comp::Flag { extra, .. }
            | Comp::Argument { extra, .. }
            | Comp::Command { extra, .. }
            | Comp::Value { extra, .. }
            | Comp::Shell { extra, .. }
            | Comp::Metavariable { extra, .. } => extra,
        };
        if extra.group.is_none() {
            extra.group = Some(group);
        }
    }
}

#[derive(Debug)]
pub(crate) struct ShowComp<'a> {
    /// value to be actually inserted by the autocomplete system
    pub(crate) subst: String,

    /// pretty rendering which might include metavars, etc
    pub(crate) pretty: String,

    pub(crate) extra: &'a CompExtra,
}

impl std::fmt::Display for ShowComp<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let (Some(help), true) = (&self.extra.help, self.subst.is_empty()) {
            write!(f, "{}: {}", self.pretty, help)
        } else if let Some(help) = &self.extra.help {
            write!(f, "{:24} -- {}", self.pretty, help)
        } else {
            write!(f, "{}", self.pretty)
        }
    }
}

impl Arg {
    fn and_os_string(&self) -> Option<(&Self, &OsStr)> {
        match self {
            Arg::Short(_, _, s) => {
                if s.is_empty() {
                    None
                } else {
                    Some((self, s))
                }
            }
            Arg::Long(_, _, s) | Arg::ArgWord(s) | Arg::Word(s) | Arg::PosWord(s) => {
                Some((self, s))
            }
        }
    }
}

fn pair_to_os_string<'a>(pair: (&'a Arg, &'a OsStr)) -> Option<(&'a Arg, &'a str)> {
    Some((pair.0, pair.1.to_str()?))
}

#[derive(Debug, Copy, Clone)]
enum Prefix<'a> {
    NA,
    Short(char),
    Long(&'a str),
}

impl State {
    /// Generate completion from collected heads
    ///
    /// before calling this method we run parser in "complete" mode and collect live heads inside
    /// `self.comp`, this part goes over collected heads and generates possible completions from
    /// that
    pub(crate) fn check_complete(&self) -> Option<String> {
        let comp = self.comp_ref()?;

        let mut items = self
            .items
            .iter()
            .rev()
            .filter_map(Arg::and_os_string)
            .filter_map(pair_to_os_string);

        // try get a current item to complete - must be non-virtual right most one
        // value must be present here, and can fail only for non-utf8 values
        // can't do much completing with non-utf8 values since bpaf needs to print them to stdout
        let (_, lit) = items.next()?;

        // For cases like "-k=val", "-kval", "--key=val", "--key val"
        // last value is going  to be either Arg::Word or Arg::ArgWord
        // so to perform full completion we look at the preceeding item
        // and use it's value if it was a composite short/long argument
        let preceeding = items.next();
        let (pos_only, full_lit) = match preceeding {
            Some((Arg::Short(_, true, _os) | Arg::Long(_, true, _os), full_lit)) => {
                (false, full_lit)
            }
            Some((Arg::PosWord(_), _)) => (true, lit),
            _ => (false, lit),
        };

        let prefix = match preceeding {
            Some((Arg::Short(s, true, _os), _lit)) => Prefix::Short(*s),
            Some((Arg::Long(l, true, _os), _lit)) => Prefix::Long(l.as_str()),
            _ => Prefix::NA,
        };

        let (items, shell) = comp.complete(lit, pos_only, prefix);

        Some(match comp.output_rev {
            0 => render_test(&items, &shell, full_lit),
            1 => render_simple(&items), // <- AKA elvish
            7 => render_zsh(&items, &shell, full_lit),
            8 => render_bash(&items, &shell, full_lit),
            9 => render_fish(&items, &shell, full_lit, self.path[0].as_str()),
            unk => panic!("Unsupported output revision {}, you need to genenerate your shell completion files for the app", unk)
        }.unwrap())
    }
}

/// Try to expand short string names into long names if possible
fn preferred_name(name: ShortLong) -> String {
    match name {
        ShortLong::Short(s) => format!("-{}", s),
        ShortLong::Long(l) | ShortLong::ShortLong(_, l) => format!("--{}", l),
    }
}

// check if argument can possibly match the argument passed in and returns a preferrable replacement
fn arg_matches(arg: &str, name: ShortLong) -> Option<String> {
    // "" and "-" match any flag
    if arg.is_empty() || arg == "-" {
        return Some(preferred_name(name));
    }

    let mut can_match = false;

    // separately check for short and long names, fancy strip prefix things is here to avoid
    // allocations and cloning
    match name {
        ShortLong::Long(_) => {}
        ShortLong::Short(s) | ShortLong::ShortLong(s, _) => {
            can_match |= arg
                .strip_prefix('-')
                .and_then(|a| a.strip_prefix(s))
                .map_or(false, str::is_empty);
        }
    }

    // and long string too
    match name {
        ShortLong::Short(_) => {}
        ShortLong::Long(l) | ShortLong::ShortLong(_, l) => {
            can_match |= arg.strip_prefix("--").map_or(false, |s| l.starts_with(s));
        }
    }

    if can_match {
        Some(preferred_name(name))
    } else {
        None
    }
}
fn cmd_matches(arg: &str, name: &'static str, short: Option<char>) -> Option<&'static str> {
    // partial long name and exact short name match anything
    if name.starts_with(arg)
        || short.map_or(false, |s| {
            // avoid allocations
            arg.strip_prefix(s).map_or(false, str::is_empty)
        })
    {
        Some(name)
    } else {
        None
    }
}

impl Comp {
    /// this completion should suppress anything else that is not a value
    fn only_value(&self) -> bool {
        match self {
            Comp::Flag { .. } | Comp::Argument { .. } | Comp::Command { .. } => false,
            Comp::Metavariable { is_argument, .. } | Comp::Value { is_argument, .. } => {
                *is_argument
            }
            Comp::Shell { .. } => true,
        }
    }
    fn is_pos(&self) -> bool {
        match self {
            Comp::Flag { .. } | Comp::Argument { .. } | Comp::Command { .. } => false,
            Comp::Value { is_argument, .. } => !is_argument,
            Comp::Metavariable { .. } | Comp::Shell { .. } => true,
        }
    }
}

impl Complete {
    fn complete(
        &self,
        arg: &str,
        pos_only: bool,
        prefix: Prefix,
    ) -> (Vec<ShowComp>, Vec<ShellComp>) {
        let mut items: Vec<ShowComp> = Vec::new();
        let mut shell = Vec::new();
        let max_depth = self.comps.iter().map(Comp::depth).max().unwrap_or(0);
        let mut only_values = false;

        for item in self
            .comps
            .iter()
            .filter(|c| c.depth() == max_depth && (!pos_only || c.is_pos()))
        {
            match (only_values, item.only_value()) {
                (true, true) | (false, false) => {}
                (true, false) => continue,
                (false, true) => {
                    only_values = true;
                    items.clear();
                }
            }

            match item {
                Comp::Command { name, short, extra } => {
                    if let Some(long) = cmd_matches(arg, name, *short) {
                        items.push(ShowComp {
                            subst: long.to_string(),
                            pretty: long.to_string(),
                            extra,
                        });
                    }
                }

                Comp::Flag { name, extra } => {
                    if let Some(long) = arg_matches(arg, *name) {
                        items.push(ShowComp {
                            pretty: long.clone(),
                            subst: long,
                            extra,
                        });
                    }
                }

                Comp::Argument {
                    name,
                    metavar,
                    extra,
                } => {
                    if let Some(long) = arg_matches(arg, *name) {
                        items.push(ShowComp {
                            pretty: format!("{}={}", long, metavar),
                            subst: long,
                            extra,
                        });
                    }
                }

                Comp::Value {
                    body,
                    extra,
                    is_argument: _,
                } => {
                    items.push(ShowComp {
                        pretty: body.clone(),
                        extra,
                        subst: match prefix {
                            Prefix::NA => body.clone(),
                            Prefix::Short(s) => format!("-{}={}", s, body),
                            Prefix::Long(l) => format!("--{}={}", l, body),
                        },
                    });
                }

                Comp::Metavariable {
                    extra,
                    meta,
                    is_argument,
                } => {
                    if !is_argument && !pos_only && arg.starts_with('-') {
                        continue;
                    }
                    items.push(ShowComp {
                        subst: String::new(),
                        pretty: (*meta).to_string(),
                        extra,
                    });
                }

                Comp::Shell { script, .. } => {
                    shell.push(*script);
                }
            }
        }

        (items, shell)
    }
}