1 //! Defines `Fixture` -- a convenient way to describe the initial state of
2 //! rust-analyzer database from a single string.
4 //! Fixtures are strings containing rust source code with optional metadata.
5 //! A fixture without metadata is parsed into a single source file.
6 //! Use this to test functionality local to one file.
12 //! println!("Hello World")
17 //! Metadata can be added to a fixture after a `//-` comment.
18 //! The basic form is specifying filenames,
19 //! which is also how to define multiple files in a single test fixture
21 //! Example using two files in the same crate:
35 //! Example using two crates with one file each, with one crate depending on the other:
38 //! //- /main.rs crate:a deps:b
42 //! //- /lib.rs crate:b
44 //! println!("Hello World")
49 //! Metadata allows specifying all settings and variables
50 //! that are available in a real rust project:
51 //! - crate names via `crate:cratename`
52 //! - dependencies via `deps:dep1,dep2`
53 //! - configuration settings via `cfg:dbg=false,opt_level=2`
54 //! - environment variables via `env:PATH=/bin,RUST_LOG=debug`
56 //! Example using all available metadata:
59 //! //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
60 //! fn insert_source_code_here() {}
64 use rustc_hash::FxHashMap;
65 use stdx::trim_indent;
67 #[derive(Debug, Eq, PartialEq)]
71 pub krate: Option<String>,
72 pub deps: Vec<String>,
73 pub cfg_atoms: Vec<String>,
74 pub cfg_key_values: Vec<(String, String)>,
75 pub edition: Option<String>,
76 pub env: FxHashMap<String, String>,
77 pub introduce_new_source_root: bool,
81 activated_flags: Vec<String>,
82 valid_flags: Vec<String>,
86 /// Parses text which looks like this:
95 /// Fixture can also start with a minicore declaration:
98 /// //- minicore: sized
101 /// That will include a subset of `libcore` into the fixture, see
102 /// `minicore.rs` for what's available.
103 pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<Fixture>) {
104 let fixture = trim_indent(ra_fixture);
105 let mut fixture = fixture.as_str();
106 let mut mini_core = None;
107 let mut res: Vec<Fixture> = Vec::new();
109 if fixture.starts_with("//- minicore:") {
110 let first_line = fixture.split_inclusive('\n').next().unwrap();
111 mini_core = Some(MiniCore::parse(first_line));
112 fixture = &fixture[first_line.len()..];
115 let default = if fixture.contains("//-") { None } else { Some("//- /main.rs") };
117 for (ix, line) in default.into_iter().chain(fixture.split_inclusive('\n')).enumerate() {
118 if line.contains("//-") {
120 line.starts_with("//-"),
121 "Metadata line {} has invalid indentation. \
122 All metadata lines need to have the same indentation.\n\
123 The offending line: {:?}",
129 if line.starts_with("//-") {
130 let meta = Fixture::parse_meta_line(line);
133 if line.starts_with("// ")
134 && line.contains(":")
135 && !line.contains("::")
136 && line.chars().all(|it| !it.is_uppercase())
138 panic!("looks like invalid metadata line: {:?}", line)
141 if let Some(entry) = res.last_mut() {
142 entry.text.push_str(line);
150 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
151 fn parse_meta_line(meta: &str) -> Fixture {
152 assert!(meta.starts_with("//-"));
153 let meta = meta["//-".len()..].trim();
154 let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
156 let path = components[0].to_string();
157 assert!(path.starts_with('/'), "fixture path does not start with `/`: {:?}", path);
159 let mut krate = None;
160 let mut deps = Vec::new();
161 let mut edition = None;
162 let mut cfg_atoms = Vec::new();
163 let mut cfg_key_values = Vec::new();
164 let mut env = FxHashMap::default();
165 let mut introduce_new_source_root = false;
166 for component in components[1..].iter() {
167 let (key, value) = component
169 .unwrap_or_else(|| panic!("invalid meta line: {:?}", meta));
171 "crate" => krate = Some(value.to_string()),
172 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
173 "edition" => edition = Some(value.to_string()),
175 for entry in value.split(',') {
176 match entry.split_once('=') {
177 Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
178 None => cfg_atoms.push(entry.to_string()),
183 for key in value.split(',') {
184 if let Some((k, v)) = key.split_once('=') {
185 env.insert(k.into(), v.into());
189 "new_source_root" => introduce_new_source_root = true,
190 _ => panic!("bad component: {:?}", component),
203 introduce_new_source_root,
209 fn has_flag(&self, flag: &str) -> bool {
210 self.activated_flags.iter().any(|it| it == flag)
214 fn assert_valid_flag(&self, flag: &str) {
215 if !self.valid_flags.iter().any(|it| it == flag) {
216 panic!("invalid flag: {:?}, valid flags: {:?}", flag, self.valid_flags);
220 fn parse(line: &str) -> MiniCore {
221 let mut res = MiniCore { activated_flags: Vec::new(), valid_flags: Vec::new() };
223 let line = line.strip_prefix("//- minicore:").unwrap().trim();
224 for entry in line.split(", ") {
225 if res.has_flag(entry) {
226 panic!("duplicate minicore flag: {:?}", entry)
228 res.activated_flags.push(entry.to_string())
234 /// Strips parts of minicore.rs which are flagged by inactive flags.
236 /// This is probably over-engineered to support flags dependencies.
237 pub fn source_code(mut self) -> String {
238 let mut buf = String::new();
239 let raw_mini_core = include_str!("./minicore.rs");
240 let mut lines = raw_mini_core.split_inclusive('\n');
242 let mut parsing_flags = false;
243 let mut implications = Vec::new();
245 // Parse `//!` preamble and extract flags and dependencies.
246 for line in lines.by_ref() {
247 let line = match line.strip_prefix("//!") {
250 assert!(line.trim().is_empty());
256 let (flag, deps) = line.split_once(':').unwrap();
257 let flag = flag.trim();
258 self.valid_flags.push(flag.to_string());
259 for dep in deps.split(", ") {
260 let dep = dep.trim();
262 self.assert_valid_flag(dep);
263 implications.push((flag, dep));
268 if line.contains("Available flags:") {
269 parsing_flags = true;
273 for flag in &self.activated_flags {
274 self.assert_valid_flag(flag);
277 // Fixed point loop to compute transitive closure of flags.
279 let mut changed = false;
280 for &(u, v) in implications.iter() {
281 if self.has_flag(u) && !self.has_flag(v) {
282 self.activated_flags.push(v.to_string());
291 let mut active_regions = Vec::new();
292 let mut seen_regions = Vec::new();
294 let trimmed = line.trim();
295 if let Some(region) = trimmed.strip_prefix("// region:") {
296 active_regions.push(region);
299 if let Some(region) = trimmed.strip_prefix("// endregion:") {
300 let prev = active_regions.pop().unwrap();
301 assert_eq!(prev, region);
305 let mut line_region = false;
306 if let Some(idx) = trimmed.find("// :") {
308 active_regions.push(&trimmed[idx + "// :".len()..]);
312 for ®ion in &active_regions {
314 !region.starts_with(' '),
315 "region marker starts with a space: {:?}",
318 self.assert_valid_flag(region);
319 seen_regions.push(region);
320 keep &= self.has_flag(region);
327 active_regions.pop().unwrap();
331 for flag in &self.valid_flags {
332 if !seen_regions.iter().any(|it| it == flag) {
333 panic!("unused minicore flag: {:?}", flag);
343 fn parse_fixture_checks_further_indented_metadata() {
357 fn parse_fixture_gets_full_meta() {
358 let (mini_core, parsed) = Fixture::parse(
360 //- minicore: coerce_unsized
361 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
365 assert_eq!(mini_core.unwrap().activated_flags, vec!["coerce_unsized".to_string()]);
366 assert_eq!(1, parsed.len());
368 let meta = &parsed[0];
369 assert_eq!("mod m;\n", meta.text);
371 assert_eq!("foo", meta.krate.as_ref().unwrap());
372 assert_eq!("/lib.rs", meta.path);
373 assert_eq!(2, meta.env.len());