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
use crate::error::{Error, Result, UserAction};
use crate::prompt::{
  PromptRequester, PromptResponder, ReportKind, RequestKind,
};
use rustyline::completion::{Candidate, Completer};
use rustyline::config::Configurer;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
use rustyline::{Context, Editor, Helper};
use std::borrow::BorrowMut;
use std::marker::PhantomData;

/// Trait for RustyLine `Helper`s which support tab completion of variant
/// names.
pub trait SpanielHelper: Helper {
  fn set_variants(&mut self, variants: &'static [&'static str]);
}

impl SpanielHelper for () {
  fn set_variants(&mut self, _variants: &'static [&'static str]) {}
}

/// RustyLine `Helper` which supports tab completion of variant names.
pub struct SimpleHelper {
  variants: &'static [&'static str],
}

impl SimpleHelper {
  pub fn new() -> Self {
    SimpleHelper { variants: &[] }
  }
}

impl Default for SimpleHelper {
  fn default() -> Self {
    Self::new()
  }
}

impl SpanielHelper for SimpleHelper {
  fn set_variants(&mut self, variants: &'static [&'static str]) {
    self.variants = variants;
  }
}

/// Tab completion candidate with a static lifetime.
pub struct StaticCandidate(&'static str);

impl Candidate for StaticCandidate {
  fn display(&self) -> &str {
    self.0
  }

  fn replacement(&self) -> &str {
    self.0
  }
}

impl Completer for SimpleHelper {
  type Candidate = StaticCandidate;

  fn complete(
    &self,
    line: &str,
    pos: usize,
    _ctx: &Context<'_>,
  ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
    let mut cands = Vec::new();
    let partial = &line[..pos];
    for variant in self.variants {
      if variant.starts_with(partial) {
        cands.push(StaticCandidate(variant));
      }
    }
    Ok((0, cands))
  }
}

impl Validator for SimpleHelper {}
impl Highlighter for SimpleHelper {}
impl Hinter for SimpleHelper {
  type Hint = String;
}
impl Helper for SimpleHelper {}

/// Prompt based on RustyLine
pub struct RustyLinePrompt<T: BorrowMut<Editor<H>>, H: SpanielHelper> {
  editor: T,
  helper: PhantomData<H>,
  level: usize,
  was_autohistory: bool,
}

impl RustyLinePrompt<Editor<SimpleHelper>, SimpleHelper> {
  /// Constructs a new `RustyLinePrompt` which owns a stock editor.
  pub fn new() -> Self {
    let mut editor = Editor::new();
    editor.set_helper(Some(SimpleHelper::new()));
    Self::with_editor(editor)
  }
}

impl Default for RustyLinePrompt<Editor<SimpleHelper>, SimpleHelper> {
  fn default() -> Self {
    Self::new()
  }
}

impl<T: BorrowMut<Editor<H>>, H: SpanielHelper> RustyLinePrompt<T, H> {
  /// Constructs a new `RustyLinePrompt` with the editor `T`.
  pub fn with_editor(mut editor: T) -> Self {
    let ed_ref = editor.borrow_mut();
    let was_autohistory = ed_ref.config_mut().auto_add_history();
    ed_ref.set_auto_add_history(true);
    RustyLinePrompt {
      editor,
      helper: PhantomData,
      level: 0,
      was_autohistory,
    }
  }

  fn spaces(&self) -> usize {
    2 * self.level
  }
}

impl<T: BorrowMut<Editor<H>>, H: SpanielHelper> Drop for RustyLinePrompt<T, H> {
  fn drop(&mut self) {
    self
      .editor
      .borrow_mut()
      .set_auto_add_history(self.was_autohistory);
  }
}

impl<T: BorrowMut<Editor<H>>, H: SpanielHelper> PromptResponder
  for RustyLinePrompt<T, H>
{
  fn begin_scope(&mut self, name: &str, _size: Option<usize>) -> Result<()> {
    println!("{:indent$}{} {{", "", name, indent = self.spaces());
    self.level += 1;
    Ok(())
  }

  fn end_scope(&mut self) -> Result<()> {
    self.level -= 1;
    println!("{:indent$}}}", "", indent = self.spaces());
    Ok(())
  }

  fn respond(
    &mut self,
    _kind: RequestKind,
    prompt: &str,
    response: &str,
  ) -> Result<()> {
    println!(
      "{:indent$}{}: {}",
      "",
      prompt,
      response,
      indent = self.spaces()
    );
    Ok(())
  }
}

impl<T: BorrowMut<Editor<H>>, H: SpanielHelper> PromptRequester
  for RustyLinePrompt<T, H>
{
  fn is_interactive(&self) -> bool {
    true
  }

  fn request(
    &mut self,
    _kind: RequestKind,
    prompt: &str,
    variants: &'static [&'static str],
  ) -> Result<String> {
    let fmt_prompt =
      format!("{:indent$}{}: ", "", prompt, indent = self.spaces());
    let editor = self.editor.borrow_mut();
    if let Some(h) = editor.helper_mut() {
      h.set_variants(variants)
    }
    let res = editor.readline(&fmt_prompt);
    if let Some(h) = editor.helper_mut() {
      h.set_variants(&[])
    }
    match res {
      Ok(line) => Ok(line),
      Err(rustyline::error::ReadlineError::Interrupted) => {
        Err(Error::UserAction(UserAction::Cancel))
      }
      Err(e) => Err(Error::IOError(e.to_string())),
    }
  }

  fn report(&mut self, _kind: ReportKind, msg: &str) -> Result<()> {
    println!("{:indent$}{}", "", msg, indent = self.spaces());
    Ok(())
  }
}