Skip to content

Commit defc7ad

Browse files
bors[bot]matklad
andauthored
Merge #2197
2197: Remove typed macro parsing API r=matklad a=matklad Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
2 parents 561bb97 + 70f2a21 commit defc7ad

File tree

7 files changed

+92
-78
lines changed

7 files changed

+92
-78
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/ra_hir_expand/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ log = "0.4.5"
1010
ra_arena = { path = "../ra_arena" }
1111
ra_db = { path = "../ra_db" }
1212
ra_syntax = { path = "../ra_syntax" }
13+
ra_parser = { path = "../ra_parser" }
1314
ra_prof = { path = "../ra_prof" }
1415
tt = { path = "../ra_tt", package = "ra_tt" }
1516
mbe = { path = "../ra_mbe", package = "ra_mbe" }

crates/ra_hir_expand/src/db.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::sync::Arc;
44

55
use mbe::MacroRules;
66
use ra_db::{salsa, SourceDatabase};
7+
use ra_parser::FragmentKind;
78
use ra_prof::profile;
89
use ra_syntax::{AstNode, Parse, SyntaxNode};
910

@@ -108,12 +109,10 @@ pub(crate) fn parse_macro(
108109
})
109110
.ok()?;
110111

111-
match macro_file.macro_file_kind {
112-
MacroFileKind::Items => {
113-
mbe::token_tree_to_items(&tt).ok().map(|(p, map)| (p.to_syntax(), Arc::new(map)))
114-
}
115-
MacroFileKind::Expr => {
116-
mbe::token_tree_to_expr(&tt).ok().map(|(p, map)| (p.to_syntax(), Arc::new(map)))
117-
}
118-
}
112+
let fragment_kind = match macro_file.macro_file_kind {
113+
MacroFileKind::Items => FragmentKind::Items,
114+
MacroFileKind::Expr => FragmentKind::Expr,
115+
};
116+
let (parse, rev_token_map) = mbe::token_tree_to_syntax_node(&tt, fragment_kind).ok()?;
117+
Some((parse, Arc::new(rev_token_map)))
119118
}

crates/ra_hir_expand/src/lib.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -151,19 +151,21 @@ pub struct ExpansionInfo {
151151

152152
impl ExpansionInfo {
153153
pub fn find_range(&self, from: TextRange) -> Option<(HirFileId, TextRange)> {
154-
fn look_in_rev_map(exp_map: &mbe::RevTokenMap, from: TextRange) -> Option<tt::TokenId> {
155-
exp_map.ranges.iter().find(|&it| it.0.is_subrange(&from)).map(|it| it.1)
156-
}
157-
158154
let token_id = look_in_rev_map(&self.exp_map, from)?;
159-
let (token_map, file_offset, token_id) = if token_id.0 >= self.shift {
155+
156+
let (token_map, (file_id, start_offset), token_id) = if token_id.0 >= self.shift {
160157
(&self.macro_arg.1, self.arg_start, tt::TokenId(token_id.0 - self.shift).into())
161158
} else {
162159
(&self.macro_def.1, self.def_start, token_id)
163160
};
164161

165162
let range = token_map.relative_range_of(token_id)?;
166-
Some((file_offset.0, TextRange::offset_len(range.start() + file_offset.1, range.len())))
163+
164+
return Some((file_id, range + start_offset));
165+
166+
fn look_in_rev_map(exp_map: &mbe::RevTokenMap, from: TextRange) -> Option<tt::TokenId> {
167+
exp_map.ranges.iter().find(|&it| it.0.is_subrange(&from)).map(|it| it.1)
168+
}
167169
}
168170
}
169171

crates/ra_mbe/src/lib.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ pub enum ExpandError {
3131
}
3232

3333
pub use crate::syntax_bridge::{
34-
ast_to_token_tree, syntax_node_to_token_tree, token_tree_to_expr, token_tree_to_items,
35-
token_tree_to_macro_stmts, token_tree_to_pat, token_tree_to_ty, RevTokenMap, TokenMap,
34+
ast_to_token_tree, syntax_node_to_token_tree, token_tree_to_syntax_node, RevTokenMap, TokenMap,
3635
};
3736

3837
/// This struct contains AST for a single `macro_rules` definition. What might

crates/ra_mbe/src/syntax_bridge.rs

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
//! FIXME: write short doc here
22
3-
use ra_parser::{
4-
FragmentKind::{self, *},
5-
ParseError, TreeSink,
6-
};
3+
use ra_parser::{FragmentKind, ParseError, TreeSink};
74
use ra_syntax::{
85
ast, AstNode, AstToken, NodeOrToken, Parse, SmolStr, SyntaxKind, SyntaxKind::*, SyntaxNode,
96
SyntaxTreeBuilder, TextRange, TextUnit, T,
@@ -55,7 +52,7 @@ pub fn syntax_node_to_token_tree(node: &SyntaxNode) -> Option<(tt::Subtree, Toke
5552
// * ImplItems(SmallVec<[ast::ImplItem; 1]>)
5653
// * ForeignItems(SmallVec<[ast::ForeignItem; 1]>
5754

58-
fn fragment_to_syntax_node(
55+
pub fn token_tree_to_syntax_node(
5956
tt: &tt::Subtree,
6057
fragment_kind: FragmentKind,
6158
) -> Result<(Parse<SyntaxNode>, RevTokenMap), ExpandError> {
@@ -79,31 +76,6 @@ fn fragment_to_syntax_node(
7976
Ok((parse, range_map))
8077
}
8178

82-
macro_rules! impl_token_tree_conversions {
83-
($($(#[$attr:meta])* $name:ident => ($kind:ident, $t:ty) ),*) => {
84-
$(
85-
$(#[$attr])*
86-
pub fn $name(tt: &tt::Subtree) -> Result<(Parse<$t>, RevTokenMap), ExpandError> {
87-
let (parse, map) = fragment_to_syntax_node(tt, $kind)?;
88-
parse.cast().ok_or_else(|| crate::ExpandError::ConversionError).map(|p| (p, map))
89-
}
90-
)*
91-
}
92-
}
93-
94-
impl_token_tree_conversions! {
95-
/// Parses the token tree (result of macro expansion) to an expression
96-
token_tree_to_expr => (Expr, ast::Expr),
97-
/// Parses the token tree (result of macro expansion) to a Pattern
98-
token_tree_to_pat => (Pattern, ast::Pat),
99-
/// Parses the token tree (result of macro expansion) to a Type
100-
token_tree_to_ty => (Type, ast::TypeRef),
101-
/// Parses the token tree (result of macro expansion) as a sequence of stmts
102-
token_tree_to_macro_stmts => (Statements, ast::MacroStmts),
103-
/// Parses the token tree (result of macro expansion) as a sequence of items
104-
token_tree_to_items => (Items, ast::MacroItems)
105-
}
106-
10779
impl TokenMap {
10880
pub fn relative_range_of(&self, tt: tt::TokenId) -> Option<TextRange> {
10981
let idx = tt.0 as usize;
@@ -446,6 +418,6 @@ mod tests {
446418
"#,
447419
);
448420
let expansion = expand(&rules, "stmts!();");
449-
assert!(token_tree_to_expr(&expansion).is_err());
421+
assert!(token_tree_to_syntax_node(&expansion, FragmentKind::Expr).is_err());
450422
}
451423
}

crates/ra_mbe/src/tests.rs

Lines changed: 71 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use ra_parser::FragmentKind;
12
use ra_syntax::{ast, AstNode, NodeOrToken, WalkEvent};
23
use test_utils::assert_eq_text;
34

@@ -126,9 +127,9 @@ fn test_expr_order() {
126127
"#,
127128
);
128129
let expanded = expand(&rules, "foo! { 1 + 1}");
129-
let tree = token_tree_to_items(&expanded).unwrap().0.tree();
130+
let tree = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap().0.syntax_node();
130131

131-
let dump = format!("{:#?}", tree.syntax());
132+
let dump = format!("{:#?}", tree);
132133
assert_eq_text!(
133134
dump.trim(),
134135
r#"MACRO_ITEMS@[0; 15)
@@ -383,9 +384,9 @@ fn test_expand_to_item_list() {
383384
",
384385
);
385386
let expansion = expand(&rules, "structs!(Foo, Bar);");
386-
let tree = token_tree_to_items(&expansion).unwrap().0.tree();
387+
let tree = token_tree_to_syntax_node(&expansion, FragmentKind::Items).unwrap().0.syntax_node();
387388
assert_eq!(
388-
format!("{:#?}", tree.syntax()).trim(),
389+
format!("{:#?}", tree).trim(),
389390
r#"
390391
MACRO_ITEMS@[0; 40)
391392
STRUCT_DEF@[0; 20)
@@ -501,10 +502,11 @@ fn test_tt_to_stmts() {
501502
);
502503

503504
let expanded = expand(&rules, "foo!{}");
504-
let stmts = token_tree_to_macro_stmts(&expanded).unwrap().0.tree();
505+
let stmts =
506+
token_tree_to_syntax_node(&expanded, FragmentKind::Statements).unwrap().0.syntax_node();
505507

506508
assert_eq!(
507-
format!("{:#?}", stmts.syntax()).trim(),
509+
format!("{:#?}", stmts).trim(),
508510
r#"MACRO_STMTS@[0; 15)
509511
LET_STMT@[0; 7)
510512
LET_KW@[0; 3) "let"
@@ -754,7 +756,10 @@ fn test_all_items() {
754756
}
755757
"#,
756758
);
757-
assert_expansion(MacroKind::Items, &rules, r#"
759+
assert_expansion(
760+
MacroKind::Items,
761+
&rules,
762+
r#"
758763
foo! {
759764
extern crate a;
760765
mod b;
@@ -770,7 +775,9 @@ fn test_all_items() {
770775
extern {}
771776
type T = u8;
772777
}
773-
"#, r#"extern crate a ; mod b ; mod c {} use d ; const E : i32 = 0 ; static F : i32 = 0 ; impl G {} struct H ; enum I {Foo} trait J {} fn h () {} extern {} type T = u8 ;"#);
778+
"#,
779+
r#"extern crate a ; mod b ; mod c {} use d ; const E : i32 = 0 ; static F : i32 = 0 ; impl G {} struct H ; enum I {Foo} trait J {} fn h () {} extern {} type T = u8 ;"#,
780+
);
774781
}
775782

776783
#[test]
@@ -946,10 +953,10 @@ fn test_vec() {
946953
);
947954

948955
let expansion = expand(&rules, r#"vec![1u32,2];"#);
949-
let tree = token_tree_to_expr(&expansion).unwrap().0.tree();
956+
let tree = token_tree_to_syntax_node(&expansion, FragmentKind::Expr).unwrap().0.syntax_node();
950957

951958
assert_eq!(
952-
format!("{:#?}", tree.syntax()).trim(),
959+
format!("{:#?}", tree).trim(),
953960
r#"BLOCK_EXPR@[0; 45)
954961
BLOCK@[0; 45)
955962
L_CURLY@[0; 1) "{"
@@ -1088,8 +1095,12 @@ macro_rules! generate_pattern_iterators {
10881095
"#,
10891096
);
10901097

1091-
assert_expansion(MacroKind::Items, &rules, r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1092-
"fn foo () {}");
1098+
assert_expansion(
1099+
MacroKind::Items,
1100+
&rules,
1101+
r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1102+
"fn foo () {}",
1103+
);
10931104
}
10941105

10951106
#[test]
@@ -1171,8 +1182,12 @@ fn test_impl_nonzero_fmt() {
11711182
"#,
11721183
);
11731184

1174-
assert_expansion(MacroKind::Items, &rules, r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1175-
"fn foo () {}");
1185+
assert_expansion(
1186+
MacroKind::Items,
1187+
&rules,
1188+
r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1189+
"fn foo () {}",
1190+
);
11761191
}
11771192

11781193
#[test]
@@ -1189,8 +1204,12 @@ fn test_cfg_if_items() {
11891204
"#,
11901205
);
11911206

1192-
assert_expansion(MacroKind::Items, &rules, r#"__cfg_if_items ! { ( rustdoc , ) ; ( ( ) ( # [ cfg ( any ( target_os = "redox" , unix ) ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as unix ; # [ cfg ( windows ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as windows ; # [ cfg ( any ( target_os = "linux" , target_os = "l4re" ) ) ] pub mod linux ; ) ) , }"#,
1193-
"__cfg_if_items ! {(rustdoc ,) ;}");
1207+
assert_expansion(
1208+
MacroKind::Items,
1209+
&rules,
1210+
r#"__cfg_if_items ! { ( rustdoc , ) ; ( ( ) ( # [ cfg ( any ( target_os = "redox" , unix ) ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as unix ; # [ cfg ( windows ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as windows ; # [ cfg ( any ( target_os = "linux" , target_os = "l4re" ) ) ] pub mod linux ; ) ) , }"#,
1211+
"__cfg_if_items ! {(rustdoc ,) ;}",
1212+
);
11941213
}
11951214

11961215
#[test]
@@ -1233,10 +1252,13 @@ cfg_if ! {
12331252
"#,
12341253
"__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}");
12351254

1236-
assert_expansion(MacroKind::Items, &rules, r#"
1255+
assert_expansion(
1256+
MacroKind::Items,
1257+
&rules,
1258+
r#"
12371259
cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
12381260
"#,
1239-
""
1261+
"",
12401262
);
12411263
}
12421264

@@ -1291,10 +1313,13 @@ macro_rules! RIDL {
12911313
}"#,
12921314
);
12931315

1294-
let expanded = expand(&rules, r#"
1316+
let expanded = expand(
1317+
&rules,
1318+
r#"
12951319
RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
12961320
fn GetDataSize(&mut self) -> UINT
1297-
}}"#);
1321+
}}"#,
1322+
);
12981323
assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
12991324
}
13001325

@@ -1340,7 +1365,8 @@ quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
13401365

13411366
#[test]
13421367
fn test_empty_repeat_vars_in_empty_repeat_vars() {
1343-
let rules = create_rules(r#"
1368+
let rules = create_rules(
1369+
r#"
13441370
macro_rules! delegate_impl {
13451371
([$self_type:ident, $self_wrap:ty, $self_map:ident]
13461372
pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
@@ -1385,9 +1411,15 @@ macro_rules! delegate_impl {
13851411
}
13861412
}
13871413
}
1388-
"#);
1414+
"#,
1415+
);
13891416

1390-
assert_expansion(MacroKind::Items, &rules, r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#, "impl <> Data for & \'a mut G where G : Data {}");
1417+
assert_expansion(
1418+
MacroKind::Items,
1419+
&rules,
1420+
r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1421+
"impl <> Data for & \'a mut G where G : Data {}",
1422+
);
13911423
}
13921424

13931425
pub(crate) fn create_rules(macro_definition: &str) -> MacroRules {
@@ -1436,22 +1468,30 @@ pub(crate) fn assert_expansion(
14361468
};
14371469
let (expanded_tree, expected_tree) = match kind {
14381470
MacroKind::Items => {
1439-
let expanded_tree = token_tree_to_items(&expanded).unwrap().0.tree();
1440-
let expected_tree = token_tree_to_items(&expected).unwrap().0.tree();
1471+
let expanded_tree =
1472+
token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap().0.syntax_node();
1473+
let expected_tree =
1474+
token_tree_to_syntax_node(&expected, FragmentKind::Items).unwrap().0.syntax_node();
14411475

14421476
(
1443-
debug_dump_ignore_spaces(expanded_tree.syntax()).trim().to_string(),
1444-
debug_dump_ignore_spaces(expected_tree.syntax()).trim().to_string(),
1477+
debug_dump_ignore_spaces(&expanded_tree).trim().to_string(),
1478+
debug_dump_ignore_spaces(&expected_tree).trim().to_string(),
14451479
)
14461480
}
14471481

14481482
MacroKind::Stmts => {
1449-
let expanded_tree = token_tree_to_macro_stmts(&expanded).unwrap().0.tree();
1450-
let expected_tree = token_tree_to_macro_stmts(&expected).unwrap().0.tree();
1483+
let expanded_tree = token_tree_to_syntax_node(&expanded, FragmentKind::Statements)
1484+
.unwrap()
1485+
.0
1486+
.syntax_node();
1487+
let expected_tree = token_tree_to_syntax_node(&expected, FragmentKind::Statements)
1488+
.unwrap()
1489+
.0
1490+
.syntax_node();
14511491

14521492
(
1453-
debug_dump_ignore_spaces(expanded_tree.syntax()).trim().to_string(),
1454-
debug_dump_ignore_spaces(expected_tree.syntax()).trim().to_string(),
1493+
debug_dump_ignore_spaces(&expanded_tree).trim().to_string(),
1494+
debug_dump_ignore_spaces(&expected_tree).trim().to_string(),
14551495
)
14561496
}
14571497
};

0 commit comments

Comments
 (0)