aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_expand/src
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2020-03-11 10:51:07 +0000
committerGitHub <[email protected]>2020-03-11 10:51:07 +0000
commitc48dcf74118b6e0df747f036a9b66701037f3fc7 (patch)
treebc047c31d43d2e16428c56bf7cdf305f4a30fa66 /crates/ra_hir_expand/src
parent7b323b45a15809a20052f13d5a8f073aaa274a86 (diff)
parent6ea7c319154f9ec10721f4041afc9d07d6b2476b (diff)
Merge #3549
3549: Implement env! macro r=matklad a=edwin0cheng This PR implements `env!` macro by adding following things: 1. Added `additional_outdirs` settings in vscode. (naming to be bikeshed) 2. Added `ExternSourceId` which is a wrapping for SourceRootId but only used in extern sources. It is because `OUT_DIR` is not belonged to any crate and we have to access it behind an `AstDatabase`. 3. This PR does not implement the `OUT_DIR` parsing from `cargo check`. I don't have general design about this, @kiljacken could we reuse some cargo watch code for that ? ~~Block on [#3536]~~ PS: After this PR , we (kind of) completed the `include!(concat!(env!('OUT_DIR'), "foo.rs")` macro call combo. [Exodia Obliterate!](https://www.youtube.com/watch?v=RfqNH3FoGi0) Co-authored-by: Edwin Cheng <[email protected]>
Diffstat (limited to 'crates/ra_hir_expand/src')
-rw-r--r--crates/ra_hir_expand/src/builtin_macro.rs182
-rw-r--r--crates/ra_hir_expand/src/test_db.rs9
2 files changed, 130 insertions, 61 deletions
diff --git a/crates/ra_hir_expand/src/builtin_macro.rs b/crates/ra_hir_expand/src/builtin_macro.rs
index 3f60b1cca..a90007f26 100644
--- a/crates/ra_hir_expand/src/builtin_macro.rs
+++ b/crates/ra_hir_expand/src/builtin_macro.rs
@@ -90,15 +90,15 @@ register_builtin! {
90 (line, Line) => line_expand, 90 (line, Line) => line_expand,
91 (stringify, Stringify) => stringify_expand, 91 (stringify, Stringify) => stringify_expand,
92 (format_args, FormatArgs) => format_args_expand, 92 (format_args, FormatArgs) => format_args_expand,
93 (env, Env) => env_expand,
94 (option_env, OptionEnv) => option_env_expand,
95 // format_args_nl only differs in that it adds a newline in the end, 93 // format_args_nl only differs in that it adds a newline in the end,
96 // so we use the same stub expansion for now 94 // so we use the same stub expansion for now
97 (format_args_nl, FormatArgsNl) => format_args_expand, 95 (format_args_nl, FormatArgsNl) => format_args_expand,
98 96
99 EAGER: 97 EAGER:
100 (concat, Concat) => concat_expand, 98 (concat, Concat) => concat_expand,
101 (include, Include) => include_expand 99 (include, Include) => include_expand,
100 (env, Env) => env_expand,
101 (option_env, OptionEnv) => option_env_expand
102} 102}
103 103
104fn line_expand( 104fn line_expand(
@@ -137,31 +137,6 @@ fn stringify_expand(
137 Ok(expanded) 137 Ok(expanded)
138} 138}
139 139
140fn env_expand(
141 _db: &dyn AstDatabase,
142 _id: LazyMacroId,
143 _tt: &tt::Subtree,
144) -> Result<tt::Subtree, mbe::ExpandError> {
145 // dummy implementation for type-checking purposes
146 // we cannot use an empty string here, because for
147 // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
148 // `include!("foo.rs"), which maybe infinite loop
149 let expanded = quote! { "__RA_UNIMPLEMENTATED__" };
150
151 Ok(expanded)
152}
153
154fn option_env_expand(
155 _db: &dyn AstDatabase,
156 _id: LazyMacroId,
157 _tt: &tt::Subtree,
158) -> Result<tt::Subtree, mbe::ExpandError> {
159 // dummy implementation for type-checking purposes
160 let expanded = quote! { std::option::Option::None::<&str> };
161
162 Ok(expanded)
163}
164
165fn column_expand( 140fn column_expand(
166 _db: &dyn AstDatabase, 141 _db: &dyn AstDatabase,
167 _id: LazyMacroId, 142 _id: LazyMacroId,
@@ -278,30 +253,37 @@ fn concat_expand(
278 253
279fn relative_file(db: &dyn AstDatabase, call_id: MacroCallId, path: &str) -> Option<FileId> { 254fn relative_file(db: &dyn AstDatabase, call_id: MacroCallId, path: &str) -> Option<FileId> {
280 let call_site = call_id.as_file().original_file(db); 255 let call_site = call_id.as_file().original_file(db);
281 let path = RelativePath::new(&path);
282 256
283 let res = db.resolve_relative_path(call_site, &path)?; 257 // Handle trivial case
284 // Prevent include itself 258 if let Some(res) = db.resolve_relative_path(call_site, &RelativePath::new(&path)) {
285 if res == call_site { 259 // Prevent include itself
286 return None; 260 return if res == call_site { None } else { Some(res) };
287 } 261 }
288 Some(res) 262
263 // Extern paths ?
264 let krate = db.relevant_crates(call_site).get(0)?.clone();
265 let (extern_source_id, relative_file) =
266 db.crate_graph()[krate].extern_source.extern_path(path)?;
267
268 db.resolve_extern_path(extern_source_id, &relative_file)
289} 269}
290 270
291fn include_expand( 271fn parse_string(tt: &tt::Subtree) -> Result<String, mbe::ExpandError> {
292 db: &dyn AstDatabase, 272 tt.token_trees
293 arg_id: EagerMacroId,
294 tt: &tt::Subtree,
295) -> Result<(tt::Subtree, FragmentKind), mbe::ExpandError> {
296 let path = tt
297 .token_trees
298 .get(0) 273 .get(0)
299 .and_then(|tt| match tt { 274 .and_then(|tt| match tt {
300 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(&it), 275 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(&it),
301 _ => None, 276 _ => None,
302 }) 277 })
303 .ok_or_else(|| mbe::ExpandError::ConversionError)?; 278 .ok_or_else(|| mbe::ExpandError::ConversionError)
279}
304 280
281fn include_expand(
282 db: &dyn AstDatabase,
283 arg_id: EagerMacroId,
284 tt: &tt::Subtree,
285) -> Result<(tt::Subtree, FragmentKind), mbe::ExpandError> {
286 let path = parse_string(tt)?;
305 let file_id = 287 let file_id =
306 relative_file(db, arg_id.into(), &path).ok_or_else(|| mbe::ExpandError::ConversionError)?; 288 relative_file(db, arg_id.into(), &path).ok_or_else(|| mbe::ExpandError::ConversionError)?;
307 289
@@ -314,12 +296,58 @@ fn include_expand(
314 Ok((res, FragmentKind::Items)) 296 Ok((res, FragmentKind::Items))
315} 297}
316 298
299fn get_env_inner(db: &dyn AstDatabase, arg_id: EagerMacroId, key: &str) -> Option<String> {
300 let call_id: MacroCallId = arg_id.into();
301 let original_file = call_id.as_file().original_file(db);
302
303 let krate = db.relevant_crates(original_file).get(0)?.clone();
304 db.crate_graph()[krate].env.get(key)
305}
306
307fn env_expand(
308 db: &dyn AstDatabase,
309 arg_id: EagerMacroId,
310 tt: &tt::Subtree,
311) -> Result<(tt::Subtree, FragmentKind), mbe::ExpandError> {
312 let key = parse_string(tt)?;
313
314 // FIXME:
315 // If the environment variable is not defined int rustc, then a compilation error will be emitted.
316 // We might do the same if we fully support all other stuffs.
317 // But for now on, we should return some dummy string for better type infer purpose.
318 // However, we cannot use an empty string here, because for
319 // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
320 // `include!("foo.rs"), which might go to infinite loop
321 let s = get_env_inner(db, arg_id, &key).unwrap_or("__RA_UNIMPLEMENTATED__".to_string());
322 let expanded = quote! { #s };
323
324 Ok((expanded, FragmentKind::Expr))
325}
326
327fn option_env_expand(
328 db: &dyn AstDatabase,
329 arg_id: EagerMacroId,
330 tt: &tt::Subtree,
331) -> Result<(tt::Subtree, FragmentKind), mbe::ExpandError> {
332 let key = parse_string(tt)?;
333 let expanded = match get_env_inner(db, arg_id, &key) {
334 None => quote! { std::option::Option::None::<&str> },
335 Some(s) => quote! { std::option::Some(#s) },
336 };
337
338 Ok((expanded, FragmentKind::Expr))
339}
340
317#[cfg(test)] 341#[cfg(test)]
318mod tests { 342mod tests {
319 use super::*; 343 use super::*;
320 use crate::{name::AsName, test_db::TestDB, AstNode, MacroCallId, MacroCallKind, MacroCallLoc}; 344 use crate::{
345 name::AsName, test_db::TestDB, AstNode, EagerCallLoc, MacroCallId, MacroCallKind,
346 MacroCallLoc,
347 };
321 use ra_db::{fixture::WithFixture, SourceDatabase}; 348 use ra_db::{fixture::WithFixture, SourceDatabase};
322 use ra_syntax::ast::NameOwner; 349 use ra_syntax::ast::NameOwner;
350 use std::sync::Arc;
323 351
324 fn expand_builtin_macro(ra_fixture: &str) -> String { 352 fn expand_builtin_macro(ra_fixture: &str) -> String {
325 let (db, file_id) = TestDB::with_single_file(&ra_fixture); 353 let (db, file_id) = TestDB::with_single_file(&ra_fixture);
@@ -330,27 +358,61 @@ mod tests {
330 let ast_id_map = db.ast_id_map(file_id.into()); 358 let ast_id_map = db.ast_id_map(file_id.into());
331 359
332 let expander = find_by_name(&macro_calls[0].name().unwrap().as_name()).unwrap(); 360 let expander = find_by_name(&macro_calls[0].name().unwrap().as_name()).unwrap();
333 let expander = expander.left().unwrap();
334 361
335 // the first one should be a macro_rules 362 let file_id = match expander {
336 let def = MacroDefId { 363 Either::Left(expander) => {
337 krate: Some(CrateId(0)), 364 // the first one should be a macro_rules
338 ast_id: Some(AstId::new(file_id.into(), ast_id_map.ast_id(&macro_calls[0]))), 365 let def = MacroDefId {
339 kind: MacroDefKind::BuiltIn(expander), 366 krate: Some(CrateId(0)),
340 }; 367 ast_id: Some(AstId::new(file_id.into(), ast_id_map.ast_id(&macro_calls[0]))),
368 kind: MacroDefKind::BuiltIn(expander),
369 };
341 370
342 let loc = MacroCallLoc { 371 let loc = MacroCallLoc {
343 def, 372 def,
344 kind: MacroCallKind::FnLike(AstId::new( 373 kind: MacroCallKind::FnLike(AstId::new(
345 file_id.into(), 374 file_id.into(),
346 ast_id_map.ast_id(&macro_calls[1]), 375 ast_id_map.ast_id(&macro_calls[1]),
347 )), 376 )),
348 }; 377 };
378
379 let id: MacroCallId = db.intern_macro(loc).into();
380 id.as_file()
381 }
382 Either::Right(expander) => {
383 // the first one should be a macro_rules
384 let def = MacroDefId {
385 krate: Some(CrateId(0)),
386 ast_id: Some(AstId::new(file_id.into(), ast_id_map.ast_id(&macro_calls[0]))),
387 kind: MacroDefKind::BuiltInEager(expander),
388 };
349 389
350 let id: MacroCallId = db.intern_macro(loc).into(); 390 let args = macro_calls[1].token_tree().unwrap();
351 let parsed = db.parse_or_expand(id.as_file()).unwrap(); 391 let parsed_args = mbe::ast_to_token_tree(&args).unwrap().0;
392
393 let arg_id = db.intern_eager_expansion({
394 EagerCallLoc {
395 def,
396 fragment: FragmentKind::Expr,
397 subtree: Arc::new(parsed_args.clone()),
398 file_id: file_id.into(),
399 }
400 });
401
402 let (subtree, fragment) = expander.expand(&db, arg_id, &parsed_args).unwrap();
403 let eager = EagerCallLoc {
404 def,
405 fragment,
406 subtree: Arc::new(subtree),
407 file_id: file_id.into(),
408 };
409
410 let id: MacroCallId = db.intern_eager_expansion(eager.into()).into();
411 id.as_file()
412 }
413 };
352 414
353 parsed.text().to_string() 415 db.parse_or_expand(file_id).unwrap().to_string()
354 } 416 }
355 417
356 #[test] 418 #[test]
diff --git a/crates/ra_hir_expand/src/test_db.rs b/crates/ra_hir_expand/src/test_db.rs
index 918736e2a..c1fb762de 100644
--- a/crates/ra_hir_expand/src/test_db.rs
+++ b/crates/ra_hir_expand/src/test_db.rs
@@ -5,7 +5,7 @@ use std::{
5 sync::{Arc, Mutex}, 5 sync::{Arc, Mutex},
6}; 6};
7 7
8use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath}; 8use ra_db::{salsa, CrateId, ExternSourceId, FileId, FileLoader, FileLoaderDelegate, RelativePath};
9 9
10#[salsa::database( 10#[salsa::database(
11 ra_db::SourceDatabaseExtStorage, 11 ra_db::SourceDatabaseExtStorage,
@@ -51,4 +51,11 @@ impl FileLoader for TestDB {
51 fn relevant_crates(&self, file_id: FileId) -> Arc<Vec<CrateId>> { 51 fn relevant_crates(&self, file_id: FileId) -> Arc<Vec<CrateId>> {
52 FileLoaderDelegate(self).relevant_crates(file_id) 52 FileLoaderDelegate(self).relevant_crates(file_id)
53 } 53 }
54 fn resolve_extern_path(
55 &self,
56 anchor: ExternSourceId,
57 relative_path: &RelativePath,
58 ) -> Option<FileId> {
59 FileLoaderDelegate(self).resolve_extern_path(anchor, relative_path)
60 }
54} 61}