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
use argdef::{SingleTarget, CollectionTarget, OptionTarget, ArgDef, ArgDefKind, SubCmd};
use help::Help;
use std::collections::{HashMap, HashSet, VecDeque};
use std::borrow::{Cow, Borrow};
use std::rc::Rc;

/// References to the targets of non-positional arguments.
//#[derive(Debug)]
pub enum TargetRef<'def, 'tar> {
    Flag(&'tar mut bool),
    Count(&'tar mut usize),
    Setting(&'tar mut OptionTarget),
    Interrupt(Box<FnMut(Rc<Help<'def>>)>),
    Collect(&'tar mut CollectionTarget),
}

/// Sorted argument definitions. Updated mutably during the parse.
//#[derive(Debug)]
pub struct ParseState<'def, 'tar> {
    positional: VecDeque<(Cow<'def, str>, &'tar mut SingleTarget)>,
    // (satisfied, target)
    trail: Option<(Cow<'def, str>, bool, &'tar mut CollectionTarget)>,
    subcommands: HashMap<Cow<'def, str>, SubCmd<'def>>,
    options: HashMap<Cow<'def, str>, TargetRef<'def, 'tar>>,
    short_map: HashMap<Cow<'def, str>, Cow<'def, str>>,
}

impl<'def, 'tar> ParseState<'def, 'tar> {
    /// Returns the internal object representing the given option name.
    fn get_interned_name(&self, option: &str) -> Cow<'def, str> {
        self.options.keys().find(|k| k.as_ref() == option).unwrap().clone()
    }
    
    /// Attempts to find a target from the given option.
    fn get_target<'a>(&'a mut self, option: &str, help: Rc<Help<'def>>)
            -> Result<(Cow<'def, str>, &'a mut TargetRef<'def, 'tar>), ParseError<'def>> {
        let mut key = &option[2..];
        if ! option.starts_with("--") {
            if let Some(mapped_key) = self.short_map.get(&option[1..]) {
                key = mapped_key.as_ref();
            } else {
                return ParseError::parse(format!("Unknown option: '{}'", option), help);
            }
        }
        if ! self.options.contains_key(key) {
            return ParseError::parse(format!("Unknown option '{}'", option), help);
        }
        // INVARIANT: key is contained
        let name = self.get_interned_name(key);
        let target = self.options.get_mut(key).unwrap();
        Ok((name, target))
    }
    
    
    fn read_option<'arg, I>(&mut self, option: &str, args: &mut I, 
        given_values: &mut HashSet<Cow<'def, str>>, help: Rc<Help<'def>>) 
        -> Result<Option<Cow<'def, str>>, ParseError<'def>>
      where I: Iterator<Item=&'arg str>
    {
        use self::TargetRef::*;
        match self.get_target(option, help.clone())? {
            (_, &mut Flag(ref mut target)) => {
                **target = true;
            }
            (_, &mut Count(ref mut target)) => {
                **target += 1;
            }
            (ref name, &mut Setting(ref mut target)) => {
                if given_values.contains(name) {
                    return ParseError::parse(format!("Option '{}' given twice!", name), help);
                }
                let arg = if let Some(arg) = args.next() {
                    arg
                } else {
                    return ParseError::parse(format!("Missing argument for option '{}'", option), help);
                };
                match target.parse(arg) {
                    Ok(_) => {}
                    Err(msg) => return ParseError::parse(msg, help),
                };
                given_values.insert(name.clone());
            }
            (_, &mut Collect(ref mut collection_target)) => {
                let arg = if let Some(arg) = args.next() {
                    arg
                } else {
                    return ParseError::parse(format!("Missing argument for option '{}'", option), help);
                };
                match collection_target.parse_and_add(arg) {
                    Ok(_) => {}
                    Err(msg) => return ParseError::parse(msg, help),
                };
            }
            (ref name, &mut Interrupt(ref mut callback)) => {
                callback(help);
                return Ok(Some(name.clone()));
            }
        }
        Ok(None)
    }
}

fn validate_short<'def, N: AsRef<str>>(name: &N) -> Result<(), ParseError<'def>> {
    let name = name.as_ref();
    if name.starts_with("-") {
        ParseError::defs(format!("Invalid short identifier '{}'. Short ids may not start with '-'.", name))
    } else {
        Ok(())
    }
}

fn add_option<'def, 'tar>(
    name: Cow<'def, str>, 
    short: Option<Cow<'def, str>>,
    target: TargetRef<'def, 'tar>,
    options: &mut HashMap<Cow<'def, str>, TargetRef<'def, 'tar>>,
    short_map: &mut HashMap<Cow<'def, str>, Cow<'def, str>>,
) -> Result<(), ParseError<'def>> 
{
    if let Some(short) = short {
        validate_short(&short)?;
        if short_map.contains_key(&short) {
            return ParseError::defs(format!("Short name '{}' defined twice.", short));
        }
        short_map.insert(short, name.clone());
    }
    if options.contains_key(&name) {
        return ParseError::defs(format!("Option '{}' defined twice.", name));
    }
    options.insert(name, target);
    Ok(())
}

/// Sorts the given definitions and checks that all invariants are upheld.
pub fn parse_definitions<'def, 'tar>(defs: Vec<ArgDef<'def, 'tar>>) 
        -> Result<ParseState<'def, 'tar>, ParseError<'def>> {
    let mut positional = VecDeque::new();
    let mut trail = None;
    let mut options = HashMap::new(); // long-to-arg
    let mut short_map = HashMap::new(); // short-to-long
    let mut subcommands = HashMap::new();
    let mut has_positional = false;
    let mut has_subcommand = false;
    for def in defs {
        match def.kind {
            ArgDefKind::Positional { target } => {
                if has_subcommand {
                    return ParseError::defs(format!("Positional (+trail) and subcommand definitions cannot be used together."));
                }
                has_positional = true;
                positional.push_back((def.name, target));
            }
            ArgDefKind::Trail { optional, target } => {
                if has_subcommand {
                    return ParseError::defs(format!("Positional (+trail) and subcommand definitions cannot be used together."));
                }
                has_positional = true;
                if trail.is_some() {
                    return ParseError::defs(format!("Two trails defined."));
                }
                trail = Some((def.name, optional, target));
            }
            ArgDefKind::Subcommand { handler } => {
                if has_positional {
                    return ParseError::defs(format!("Positional (+trail) and subcommand definitions cannot be used together."));
                }
                has_subcommand = true;
                if subcommands.contains_key(&def.name) {
                    return ParseError::defs(format!("Sucommand '{}' defined twice", def.name))
                }
                subcommands.insert(def.name, handler);
            }
            ArgDefKind::Flag { short, target } => {
                add_option(def.name, short, TargetRef::Flag(target), &mut options, &mut short_map)?;
            }
            ArgDefKind::Count { short, target } => {
                add_option(def.name, short, TargetRef::Count(target), &mut options, &mut short_map)?;
            }
            ArgDefKind::Collect { short, target, .. } => {
                add_option(def.name, short, TargetRef::Collect(target), &mut options, &mut short_map)?;
            }
            ArgDefKind::Setting { short, target, .. } => {
                add_option(def.name, short, TargetRef::Setting(target), &mut options, &mut short_map)?;
            }
            ArgDefKind::Interrupt { short, callback } => {
                add_option(def.name, short, TargetRef::Interrupt(callback), &mut options, &mut short_map)?;
            }
        }
    }
    Ok(ParseState { positional, trail, subcommands, options, short_map })
}

/// An error found when parsing arguments.
#[derive(Debug)]
pub enum ParseError<'def> {
    /// The given argument definitions aren't valid.
    InvalidDefinitions(String),
    
    /// The parse could not finish succesfully.
    ParseFailed(String, Rc<Help<'def>>),
    
    /// A subcommand failed to parse, and has been handled.
    SubParseFailed,
    
    /// An interrupt-flag with the given name was encountered.
    /// 
    /// The variables pointed to by the definitions will not all have been
    /// assigned their expected values.
    Interrupted(Cow<'def, str>)
}

impl<'def> ParseError<'def> {
    fn defs<T, S: Into<String>>(reason: S) -> Result<T, ParseError<'def>> {
        Err(ParseError::InvalidDefinitions(reason.into()))
    }
    
    fn parse<T, S: Into<String>>(reason: S, help: Rc<Help<'def>>) -> Result<T, ParseError<'def>> {
        Err(ParseError::ParseFailed(reason.into(), help))
    }
    
    fn interrupt<T>(name: Cow<'def, str>) -> Result<T, ParseError<'def>> {
       Err( ParseError::Interrupted(name))
    }
}

/// Parses the given arguments and updates the defined variables with them.
/// This version does not print usage in the case of parse errors, nor does 
/// it 'un-propagate' parsing errors.
pub fn parse_plain<'def, 'tar, T, P: Into<String>>(program: P, args: &[T], definitions: Vec<ArgDef<'def, 'tar>>) 
    -> Result<Option<i32>, ParseError<'def>>
  where T: Borrow<str> 
{ 
    let program = program.into();
    let help = Rc::new(Help::new(program.clone(), &definitions));
    let mut defs = parse_definitions(definitions)?;
    
    //println!("Defs: {:?}", defs);
    let mut args = args.iter().map(|e| e.borrow());
    
    // value-type definitions that have been given and should not be overridden
    let mut given_values = HashSet::new();
    
    while let Some(arg) = args.next() {
        // Option / interrupt
        if arg.starts_with("-") {
            if let Some(interrupt) = defs.read_option(arg, &mut args, &mut given_values, help.clone())? {
                return ParseError::interrupt(interrupt);
            }
        
        // Positional
        } else if ! defs.positional.is_empty() {
            let (_name, target) = defs.positional.pop_front().unwrap();
            match target.parse(arg) {
                Ok(()) => {},
                Err(msg) => return ParseError::parse(msg, help),
            } // MAYBE: chain err
        
        // Subcommand
        } else if ! defs.subcommands.is_empty() {
            if let Some(handler) = defs.subcommands.get_mut(arg) {
                let rest = args.collect::<Vec<_>>();
                // Allow 'empty' super-program.
                let subprogram = if program != "" {
                    format!("{} {}", program, arg)
                } else {
                    arg.to_string()
                };
                return handler(subprogram, &rest);
            } else {
                return ParseError::parse(format!("Unknown subcommand: '{}'", arg), help);
            }
        
        // Trail
        } else {
            if let Some((_, ref mut satisfied, ref mut target)) = defs.trail {
                match target.parse_and_add(arg) {
                    Ok(()) => {},
                    Err(msg) => return ParseError::parse(msg, help),
                }; // TODO: chain err
                *satisfied = true;
            } else {
                return ParseError::parse(format!("Unexpected argument '{}'", arg), help);
            }            
        }
    }
    
    if let Some((name, _)) = defs.positional.pop_front() {
        return ParseError::parse(format!("Missing positional argument '{}'", name), help);
    }
    
    if let Some((name, satisfied, _)) = defs.trail {
        if ! satisfied {
            return ParseError::parse(format!("Expected at least one trailing argument for '{}'", name), help);
        }
    }
    
    if ! defs.subcommands.is_empty() {
        return ParseError::parse(format!("No subcommand specified"), help);
    }
    
    Ok(None)
}

/// Parses the given arguments and updates the defined variables with them.
/// 
/// Errors are handled like this:
/// - Invalid argument definitions (logic error): Panic.
/// - Parse failed: Print usage and prevent the error from propagating.
/// - Interrupt or sub parse failed: Just passed along.
pub fn parse<'def, 'tar, T, P: Into<String>>(program: P, args: &[T], definitions: Vec<ArgDef<'def, 'tar>>) 
    -> Result<Option<i32>, ParseError<'def>>
  where T: Borrow<str> 
{ 
    match parse_plain(program, args, definitions) {
        Err(ParseError::InvalidDefinitions(msg)) => {
            panic!("Invalid definitions: {}", msg);
        }
        Err(ParseError::ParseFailed(msg, help)) => {
            println!("Parse failed: {}", msg);
            help.print_usage();
            Err(ParseError::SubParseFailed)
        }
        other => other,
    }
}