1 //! Defines `Fixture` -- a convenient way to describe the initial state of
2 //! rust-analyzer database from a single string.
4 use rustc_hash::FxHashMap;
5 use stdx::{lines_with_ends, split_once, trim_indent};
7 #[derive(Debug, Eq, PartialEq)]
11 pub explicit_root: bool,
12 pub krate: Option<String>,
13 pub deps: Vec<String>,
14 pub cfg_atoms: Vec<String>,
15 pub cfg_key_values: Vec<(String, String)>,
16 pub edition: Option<String>,
17 pub env: FxHashMap<String, String>,
21 /// Parses text which looks like this:
29 pub fn parse(ra_fixture: &str) -> Vec<Fixture> {
30 let fixture = trim_indent(ra_fixture);
32 let mut res: Vec<Fixture> = Vec::new();
34 let default = if ra_fixture.contains("//-") { None } else { Some("//- /main.rs") };
36 for (ix, line) in default.into_iter().chain(lines_with_ends(&fixture)).enumerate() {
37 if line.contains("//-") {
39 line.starts_with("//-"),
40 "Metadata line {} has invalid indentation. \
41 All metadata lines need to have the same indentation.\n\
42 The offending line: {:?}",
48 if line.starts_with("//-") {
49 let meta = Fixture::parse_meta_line(line);
51 } else if let Some(entry) = res.last_mut() {
52 entry.text.push_str(line);
59 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
60 fn parse_meta_line(meta: &str) -> Fixture {
61 assert!(meta.starts_with("//-"));
62 let meta = meta["//-".len()..].trim();
63 let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
65 let path = components[0].to_string();
66 assert!(path.starts_with('/'));
68 let mut explicit_root = false;
70 let mut deps = Vec::new();
71 let mut edition = None;
72 let mut cfg_atoms = Vec::new();
73 let mut cfg_key_values = Vec::new();
74 let mut env = FxHashMap::default();
75 for component in components[1..].iter() {
76 let (key, value) = split_once(component, ':').unwrap();
78 "root" => explicit_root = true,
79 "crate" => krate = Some(value.to_string()),
80 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
81 "edition" => edition = Some(value.to_string()),
83 for entry in value.split(',') {
84 match split_once(entry, '=') {
85 Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
86 None => cfg_atoms.push(entry.to_string()),
91 for key in value.split(',') {
92 if let Some((k, v)) = split_once(key, '=') {
93 env.insert(k.into(), v.into());
97 _ => panic!("bad component: {:?}", component),
104 explicit_root: explicit_root,
117 fn parse_fixture_checks_further_indented_metadata() {
131 fn parse_fixture_gets_full_meta() {
132 let parsed = Fixture::parse(
134 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
138 assert_eq!(1, parsed.len());
140 let meta = &parsed[0];
141 assert_eq!("mod m;\n", meta.text);
143 assert_eq!("foo", meta.krate.as_ref().unwrap());
144 assert_eq!("/lib.rs", meta.path);
145 assert_eq!(2, meta.env.len());