Skip to content
Myr

parse.rs

This file

Path

crates/core/flags/parse.rs

476 lines · 17.4 KiB · Rust

Last changed by

style: apply rustfmtAndrew Gallantbefore adoptionbb8172f

History of this file

Take it

The walk stopped after 200 commits: lines older than 5f5da48 point at it.

globset: support nested alternatesLuke Sandbergbefore adoption5f5da48

lines 1–9why, one step back
1/*!
2Parses command line arguments into a structured and typed representation.3*/45use std::{borrow::Cow, collections::BTreeSet, ffi::OsString};67use anyhow::Context;89use crate::flags::{

style: apply rustfmtAndrew Gallantbefore adoptionbb8172f

line 10why, one step back
10 Flag, FlagValue,

globset: support nested alternatesLuke Sandbergbefore adoption5f5da48

lines 11–476why, one step back
11 defs::FLAGS,
12 hiargs::HiArgs,13 lowargs::{LoggingMode, LowArgs, SpecialMode},14};1516/// The result of parsing CLI arguments.17///18/// This is basically a `anyhow::Result<T>`, but with one extra variant that is19/// inhabited whenever ripgrep should execute a "special" mode. That is, when a20/// user provides the `-h/--help` or `-V/--version` flags.21///22/// This special variant exists to allow CLI parsing to short circuit as23/// quickly as is reasonable. For example, it lets CLI parsing avoid reading24/// ripgrep's configuration and converting low level arguments into a higher25/// level representation.26#[derive(Debug)]27pub(crate) enum ParseResult<T> {28 Special(SpecialMode),29 Ok(T),30 Err(anyhow::Error),31}3233impl<T> ParseResult<T> {34 /// If this result is `Ok`, then apply `then` to it. Otherwise, return this35 /// result unchanged.36 fn and_then<U>(37 self,38 mut then: impl FnMut(T) -> ParseResult<U>,39 ) -> ParseResult<U> {40 match self {41 ParseResult::Special(mode) => ParseResult::Special(mode),42 ParseResult::Ok(t) => then(t),43 ParseResult::Err(err) => ParseResult::Err(err),44 }45 }46}4748/// Parse CLI arguments and convert then to their high level representation.49pub(crate) fn parse() -> ParseResult<HiArgs> {50 parse_low().and_then(|low| match HiArgs::from_low_args(low) {51 Ok(hi) => ParseResult::Ok(hi),52 Err(err) => ParseResult::Err(err),53 })54}5556/// Parse CLI arguments only into their low level representation.57///58/// This takes configuration into account. That is, it will try to read59/// `RIPGREP_CONFIG_PATH` and prepend any arguments found there to the60/// arguments passed to this process.61///62/// This will also set one-time global state flags, such as the log level and63/// whether messages should be printed.64fn parse_low() -> ParseResult<LowArgs> {65 if let Err(err) = crate::logger::Logger::init() {66 let err = anyhow::anyhow!("failed to initialize logger: {err}");67 return ParseResult::Err(err);68 }6970 let parser = Parser::new();71 let mut low = LowArgs::default();72 if let Err(err) = parser.parse(std::env::args_os().skip(1), &mut low) {73 return ParseResult::Err(err);74 }75 // Even though we haven't parsed the config file yet (assuming it exists),76 // we can still use the arguments given on the CLI to setup ripgrep's77 // logging preferences. Even if the config file changes them in some way,78 // it's really the best we can do. This way, for example, folks can pass79 // `--trace` and see any messages logged during config file parsing.80 set_log_levels(&low);81 // Before we try to take configuration into account, we can bail early82 // if a special mode was enabled. This is basically only for version and83 // help output which shouldn't be impacted by extra configuration.84 if let Some(special) = low.special.take() {85 return ParseResult::Special(special);86 }87 // If the end user says no config, then respect it.88 if low.no_config {89 log::debug!("not reading config files because --no-config is present");90 return ParseResult::Ok(low);91 }92 // Look for arguments from a config file. If we got nothing (whether the93 // file is empty or RIPGREP_CONFIG_PATH wasn't set), then we don't need94 // to re-parse.95 let config_args = crate::flags::config::args();96 if config_args.is_empty() {97 log::debug!("no extra arguments found from configuration file");98 return ParseResult::Ok(low);99 }100 // The final arguments are just the arguments from the CLI appending to101 // the end of the config arguments.102 let mut final_args = config_args;103 final_args.extend(std::env::args_os().skip(1));104105 // Now do the CLI parsing dance again.106 let mut low = LowArgs::default();107 if let Err(err) = parser.parse(final_args.into_iter(), &mut low) {108 return ParseResult::Err(err);109 }110 // Reset the message and logging levels, since they could have changed.111 set_log_levels(&low);112 ParseResult::Ok(low)113}114115/// Sets global state flags that control logging based on low-level arguments.116fn set_log_levels(low: &LowArgs) {117 crate::messages::set_messages(!low.no_messages);118 crate::messages::set_ignore_messages(!low.no_ignore_messages);119 match low.logging {120 Some(LoggingMode::Trace) => {121 log::set_max_level(log::LevelFilter::Trace)122 }123 Some(LoggingMode::Debug) => {124 log::set_max_level(log::LevelFilter::Debug)125 }126 None => log::set_max_level(log::LevelFilter::Warn),127 }128}129130/// Parse the sequence of CLI arguments given a low level typed set of131/// arguments.132///133/// This is exposed for testing that the correct low-level arguments are parsed134/// from a CLI. It just runs the parser once over the CLI arguments. It doesn't135/// setup logging or read from a config file.136///137/// This assumes the iterator given does *not* begin with the binary name.138#[cfg(test)]139pub(crate) fn parse_low_raw(140 rawargs: impl IntoIterator<Item = impl Into<OsString>>,141) -> anyhow::Result<LowArgs> {142 let mut args = LowArgs::default();143 Parser::new().parse(rawargs, &mut args)?;144 Ok(args)145}146147/// Return the metadata for the flag of the given name.148pub(super) fn lookup(name: &str) -> Option<&'static dyn Flag> {149 // N.B. Creating a new parser might look expensive, but it only builds150 // the lookup trie exactly once. That is, we get a `&'static Parser` from151 // `Parser::new()`.152 match Parser::new().find_long(name) {153 FlagLookup::Match(&FlagInfo { flag, .. }) => Some(flag),154 _ => None,155 }156}157158/// A parser for turning a sequence of command line arguments into a more159/// strictly typed set of arguments.160#[derive(Debug)]161struct Parser {162 /// A single map that contains all possible flag names. This includes163 /// short and long names, aliases and negations. This maps those names to164 /// indices into `info`.165 map: FlagMap,166 /// A map from IDs returned by the `map` to the corresponding flag167 /// information.168 info: Vec<FlagInfo>,169}170171impl Parser {172 /// Create a new parser.173 ///174 /// This always creates the same parser and only does it once. Callers may175 /// call this repeatedly, and the parser will only be built once.176 fn new() -> &'static Parser {177 use std::sync::OnceLock;178179 // Since a parser's state is immutable and completely determined by180 // FLAGS, and since FLAGS is a constant, we can initialize it exactly181 // once.182 static P: OnceLock<Parser> = OnceLock::new();183 P.get_or_init(|| {184 let mut infos = vec![];185 for &flag in FLAGS.iter() {186 infos.push(FlagInfo {187 flag,188 name: Ok(flag.name_long()),189 kind: FlagInfoKind::Standard,190 });191 for alias in flag.aliases() {192 infos.push(FlagInfo {193 flag,194 name: Ok(alias),195 kind: FlagInfoKind::Alias,196 });197 }198 if let Some(byte) = flag.name_short() {199 infos.push(FlagInfo {200 flag,201 name: Err(byte),202 kind: FlagInfoKind::Standard,203 });204 }205 if let Some(name) = flag.name_negated() {206 infos.push(FlagInfo {207 flag,208 name: Ok(name),209 kind: FlagInfoKind::Negated,210 });211 }212 }213 let map = FlagMap::new(&infos);214 Parser { map, info: infos }215 })216 }217218 /// Parse the given CLI arguments into a low level representation.219 ///220 /// The iterator given should *not* start with the binary name.221 fn parse<I, O>(&self, rawargs: I, args: &mut LowArgs) -> anyhow::Result<()>222 where223 I: IntoIterator<Item = O>,224 O: Into<OsString>,225 {226 let mut p = lexopt::Parser::from_args(rawargs);227 while let Some(arg) = p.next().context("invalid CLI arguments")? {228 let lookup = match arg {229 lexopt::Arg::Value(value) => {230 args.positional.push(value);231 continue;232 }233 lexopt::Arg::Short(ch) if ch == 'h' => {234 // Special case -h/--help since behavior is different235 // based on whether short or long flag is given.236 args.special = Some(SpecialMode::HelpShort);237 continue;238 }239 lexopt::Arg::Short(ch) if ch == 'V' => {240 // Special case -V/--version since behavior is different241 // based on whether short or long flag is given.242 args.special = Some(SpecialMode::VersionShort);243 continue;244 }245 lexopt::Arg::Short(ch) => self.find_short(ch),246 lexopt::Arg::Long(name) if name == "help" => {247 // Special case -h/--help since behavior is different248 // based on whether short or long flag is given.249 args.special = Some(SpecialMode::HelpLong);250 continue;251 }252 lexopt::Arg::Long(name) if name == "version" => {253 // Special case -V/--version since behavior is different254 // based on whether short or long flag is given.255 args.special = Some(SpecialMode::VersionLong);256 continue;257 }258 lexopt::Arg::Long(name) => self.find_long(name),259 };260 let mat = match lookup {261 FlagLookup::Match(mat) => mat,262 FlagLookup::UnrecognizedShort(name) => {263 anyhow::bail!("unrecognized flag -{name}")264 }265 FlagLookup::UnrecognizedLong(name) => {266 let mut msg = format!("unrecognized flag --{name}");267 if let Some(suggest_msg) = suggest(&name) {268 msg = format!("{msg}\n\n{suggest_msg}");269 }270 anyhow::bail!("{msg}")271 }272 };273 let value = if matches!(mat.kind, FlagInfoKind::Negated) {274 // Negated flags are always switches, even if the non-negated275 // flag is not. For example, --context-separator accepts a276 // value, but --no-context-separator does not.277 FlagValue::Switch(false)278 } else if mat.flag.is_switch() {279 FlagValue::Switch(true)280 } else {281 FlagValue::Value(p.value().with_context(|| {282 format!("missing value for flag {mat}")283 })?)284 };285 mat.flag286 .update(value, args)287 .with_context(|| format!("error parsing flag {mat}"))?;288 }289 Ok(())290 }291292 /// Look for a flag by its short name.293 fn find_short(&self, ch: char) -> FlagLookup<'_> {294 if !ch.is_ascii() {295 return FlagLookup::UnrecognizedShort(ch);296 }297 let byte = u8::try_from(ch).unwrap();298 let Some(index) = self.map.find(&[byte]) else {299 return FlagLookup::UnrecognizedShort(ch);300 };301 FlagLookup::Match(&self.info[index])302 }303304 /// Look for a flag by its long name.305 ///306 /// This also works for aliases and negated names.307 fn find_long(&self, name: &str) -> FlagLookup<'_> {308 let Some(index) = self.map.find(name.as_bytes()) else {309 return FlagLookup::UnrecognizedLong(name.to_string());310 };311 FlagLookup::Match(&self.info[index])312 }313}314315/// The result of looking up a flag name.316#[derive(Debug)]317enum FlagLookup<'a> {318 /// Lookup found a match and the metadata for the flag is attached.319 Match(&'a FlagInfo),320 /// The given short name is unrecognized.321 UnrecognizedShort(char),322 /// The given long name is unrecognized.323 UnrecognizedLong(String),324}325326/// The info about a flag associated with a flag's ID in the flag map.327#[derive(Debug)]328struct FlagInfo {329 /// The flag object and its associated metadata.330 flag: &'static dyn Flag,331 /// The actual name that is stored in the Aho-Corasick automaton. When this332 /// is a byte, it corresponds to a short single character ASCII flag. The333 /// actual pattern that's in the Aho-Corasick automaton is just the single334 /// byte.335 name: Result<&'static str, u8>,336 /// The type of flag that is stored for the corresponding Aho-Corasick337 /// pattern.338 kind: FlagInfoKind,339}340341/// The kind of flag that is being matched.342#[derive(Debug)]343enum FlagInfoKind {344 /// A standard flag, e.g., --passthru.345 Standard,346 /// A negation of a standard flag, e.g., --no-multiline.347 Negated,348 /// An alias for a standard flag, e.g., --passthrough.349 Alias,350}351352impl std::fmt::Display for FlagInfo {353 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {354 match self.name {355 Ok(long) => write!(f, "--{long}"),356 Err(short) => write!(f, "-{short}", short = char::from(short)),357 }358 }359}360361/// A map from flag names (short, long, negated and aliases) to their ID.362///363/// Once an ID is known, it can be used to look up a flag's metadata in the364/// parser's internal state.365#[derive(Debug)]366struct FlagMap {367 map: std::collections::HashMap<Vec<u8>, usize>,368}369370impl FlagMap {371 /// Create a new map of flags for the given flag information.372 ///373 /// The index of each flag info corresponds to its ID.374 fn new(infos: &[FlagInfo]) -> FlagMap {375 let mut map = std::collections::HashMap::with_capacity(infos.len());376 for (i, info) in infos.iter().enumerate() {377 match info.name {378 Ok(name) => {379 assert_eq!(None, map.insert(name.as_bytes().to_vec(), i));380 }381 Err(byte) => {382 assert_eq!(None, map.insert(vec![byte], i));383 }384 }385 }386 FlagMap { map }387 }388389 /// Look for a match of `name` in the given Aho-Corasick automaton.390 ///391 /// This only returns a match if the one found has a length equivalent to392 /// the length of the name given.393 fn find(&self, name: &[u8]) -> Option<usize> {394 self.map.get(name).copied()395 }396}397398/// Possibly return a message suggesting flags similar in the name to the one399/// given.400///401/// The one given should be a flag given by the user (without the leading402/// dashes) that was unrecognized. This attempts to find existing flags that403/// are similar to the one given.404fn suggest(unrecognized: &str) -> Option<String> {405 let similars = find_similar_names(unrecognized);406 if similars.is_empty() {407 return None;408 }409 let list = similars410 .into_iter()411 .map(|name| format!("--{name}"))412 .collect::<Vec<String>>()413 .join(", ");414 Some(format!("similar flags that are available: {list}"))415}416417/// Return a sequence of names similar to the unrecognized name given.418fn find_similar_names(unrecognized: &str) -> Vec<&'static str> {419 // The jaccard similarity threshold at which we consider two flag names420 // similar enough that it's worth suggesting it to the end user.421 //422 // This value was determined by some ad hoc experimentation. It might need423 // further tweaking.424 const THRESHOLD: f64 = 0.4;425426 let mut similar = vec![];427 let bow_given = ngrams(unrecognized);428 for &flag in FLAGS.iter() {429 let name = flag.name_long();430 let bow = ngrams(name);431 if jaccard_index(&bow_given, &bow) >= THRESHOLD {432 similar.push(name);433 }434 if let Some(name) = flag.name_negated() {435 let bow = ngrams(name);436 if jaccard_index(&bow_given, &bow) >= THRESHOLD {437 similar.push(name);438 }439 }440 for name in flag.aliases() {441 let bow = ngrams(name);442 if jaccard_index(&bow_given, &bow) >= THRESHOLD {443 similar.push(name);444 }445 }446 }447 similar448}449450/// A "bag of words" is a set of ngrams.451type BagOfWords<'a> = BTreeSet<Cow<'a, [u8]>>;452453/// Returns the jaccard index (a measure of similarity) between sets of ngrams.454fn jaccard_index(ngrams1: &BagOfWords<'_>, ngrams2: &BagOfWords<'_>) -> f64 {455 let union = u32::try_from(ngrams1.union(ngrams2).count())456 .expect("fewer than u32::MAX flags");457 let intersection = u32::try_from(ngrams1.intersection(ngrams2).count())458 .expect("fewer than u32::MAX flags");459 f64::from(intersection) / f64::from(union)460}461462/// Returns all 3-grams in the slice given.463///464/// If the slice doesn't contain a 3-gram, then one is artificially created by465/// padding it out with a character that will never appear in a flag name.466fn ngrams(flag_name: &str) -> BagOfWords<'_> {467 // We only allow ASCII flag names, so we can just use bytes.468 let slice = flag_name.as_bytes();469 let seq: Vec<Cow<[u8]>> = match slice.len() {470 0 => vec![Cow::Owned(b"!!!".to_vec())],471 1 => vec![Cow::Owned(vec![slice[0], b'!', b'!'])],472 2 => vec![Cow::Owned(vec![slice[0], slice[1], b'!'])],473 _ => slice.windows(3).map(Cow::Borrowed).collect(),474 };475 BTreeSet::from_iter(seq)476}