1 //! Fixtures are strings containing rust source code with optional metadata.
2 //! A fixture without metadata is parsed into a single source file.
3 //! Use this to test functionality local to one file.
9 //! println!("Hello World")
14 //! Metadata can be added to a fixture after a `//-` comment.
15 //! The basic form is specifying filenames,
16 //! which is also how to define multiple files in a single test fixture
18 //! Example using two files in the same crate:
32 //! Example using two crates with one file each, with one crate depending on the other:
35 //! //- /main.rs crate:a deps:b
39 //! //- /lib.rs crate:b
41 //! println!("Hello World")
46 //! Metadata allows specifying all settings and variables
47 //! that are available in a real rust project:
48 //! - crate names via `crate:cratename`
49 //! - dependencies via `deps:dep1,dep2`
50 //! - configuration settings via `cfg:dbg=false,opt_level=2`
51 //! - environment variables via `env:PATH=/bin,RUST_LOG=debug`
53 //! Example using all available metadata:
56 //! //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
57 //! fn insert_source_code_here() {}
60 use std::{mem, str::FromStr, sync::Arc};
63 use rustc_hash::FxHashMap;
65 extract_range_or_offset, Fixture, RangeOrOffset, CURSOR_MARKER, ESCAPED_CURSOR_MARKER,
67 use vfs::{file_set::FileSet, VfsPath};
70 input::CrateName, Change, CrateGraph, CrateId, Edition, Env, FileId, FilePosition, FileRange,
71 SourceDatabaseExt, SourceRoot, SourceRootId,
74 pub const WORKSPACE: SourceRootId = SourceRootId(0);
76 pub trait WithFixture: Default + SourceDatabaseExt + 'static {
77 fn with_single_file(text: &str) -> (Self, FileId) {
78 let fixture = ChangeFixture::parse(text);
79 let mut db = Self::default();
80 fixture.change.apply(&mut db);
81 assert_eq!(fixture.files.len(), 1);
82 (db, fixture.files[0])
85 fn with_files(ra_fixture: &str) -> Self {
86 let fixture = ChangeFixture::parse(ra_fixture);
87 let mut db = Self::default();
88 fixture.change.apply(&mut db);
89 assert!(fixture.file_position.is_none());
93 fn with_position(ra_fixture: &str) -> (Self, FilePosition) {
94 let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
95 let offset = match range_or_offset {
96 RangeOrOffset::Range(_) => panic!(),
97 RangeOrOffset::Offset(it) => it,
99 (db, FilePosition { file_id, offset })
102 fn with_range(ra_fixture: &str) -> (Self, FileRange) {
103 let (db, file_id, range_or_offset) = Self::with_range_or_offset(ra_fixture);
104 let range = match range_or_offset {
105 RangeOrOffset::Range(it) => it,
106 RangeOrOffset::Offset(_) => panic!(),
108 (db, FileRange { file_id, range })
111 fn with_range_or_offset(ra_fixture: &str) -> (Self, FileId, RangeOrOffset) {
112 let fixture = ChangeFixture::parse(ra_fixture);
113 let mut db = Self::default();
114 fixture.change.apply(&mut db);
115 let (file_id, range_or_offset) = fixture.file_position.unwrap();
116 (db, file_id, range_or_offset)
119 fn test_crate(&self) -> CrateId {
120 let crate_graph = self.crate_graph();
121 let mut it = crate_graph.iter();
122 let res = it.next().unwrap();
123 assert!(it.next().is_none());
128 impl<DB: SourceDatabaseExt + Default + 'static> WithFixture for DB {}
130 pub struct ChangeFixture {
131 pub file_position: Option<(FileId, RangeOrOffset)>,
132 pub files: Vec<FileId>,
137 pub fn parse(ra_fixture: &str) -> ChangeFixture {
138 let fixture = Fixture::parse(ra_fixture);
139 let mut change = Change::new();
141 let mut files = Vec::new();
142 let mut crate_graph = CrateGraph::default();
143 let mut crates = FxHashMap::default();
144 let mut crate_deps = Vec::new();
145 let mut default_crate_root: Option<FileId> = None;
146 let mut default_cfg = CfgOptions::default();
148 let mut file_set = FileSet::default();
149 let source_root_prefix = "/".to_string();
150 let mut file_id = FileId(0);
151 let mut roots = Vec::new();
153 let mut file_position = None;
155 for entry in fixture {
156 let text = if entry.text.contains(CURSOR_MARKER) {
157 if entry.text.contains(ESCAPED_CURSOR_MARKER) {
158 entry.text.replace(ESCAPED_CURSOR_MARKER, CURSOR_MARKER)
160 let (range_or_offset, text) = extract_range_or_offset(&entry.text);
161 assert!(file_position.is_none());
162 file_position = Some((file_id, range_or_offset));
169 let meta = FileMeta::from(entry);
170 assert!(meta.path.starts_with(&source_root_prefix));
172 if meta.introduce_new_source_root {
173 roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
176 if let Some(krate) = meta.krate {
177 let crate_name = CrateName::normalize_dashes(&krate);
178 let crate_id = crate_graph.add_crate_root(
181 Some(crate_name.clone().into()),
186 let prev = crates.insert(crate_name.clone(), crate_id);
187 assert!(prev.is_none());
188 for dep in meta.deps {
189 let dep = CrateName::normalize_dashes(&dep);
190 crate_deps.push((crate_name.clone(), dep))
192 } else if meta.path == "/main.rs" || meta.path == "/lib.rs" {
193 assert!(default_crate_root.is_none());
194 default_crate_root = Some(file_id);
195 default_cfg = meta.cfg;
198 change.change_file(file_id, Some(Arc::new(text)));
199 let path = VfsPath::new_virtual_path(meta.path);
200 file_set.insert(file_id, path);
205 if crates.is_empty() {
206 let crate_root = default_crate_root.unwrap();
207 crate_graph.add_crate_root(
209 Edition::Edition2018,
210 Some(CrateName::new("test").unwrap().into()),
216 for (from, to) in crate_deps {
217 let from_id = crates[&from];
218 let to_id = crates[&to];
219 crate_graph.add_dep(from_id, CrateName::new(&to).unwrap(), to_id).unwrap();
223 roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
224 change.set_roots(roots);
225 change.set_crate_graph(crate_graph);
227 ChangeFixture { file_position, files, change }
233 krate: Option<String>,
238 introduce_new_source_root: bool,
241 impl From<Fixture> for FileMeta {
242 fn from(f: Fixture) -> FileMeta {
243 let mut cfg = CfgOptions::default();
244 f.cfg_atoms.iter().for_each(|it| cfg.insert_atom(it.into()));
245 f.cfg_key_values.iter().for_each(|(k, v)| cfg.insert_key_value(k.into(), v.into()));
255 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
256 env: f.env.into_iter().collect(),
257 introduce_new_source_root: f.introduce_new_source_root,