aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock8
-rw-r--r--crates/ra_assists/src/add_derive.rs2
-rw-r--r--crates/ra_assists/src/add_explicit_type.rs2
-rw-r--r--crates/ra_assists/src/add_impl.rs6
-rw-r--r--crates/ra_assists/src/add_missing_impl_members.rs46
-rw-r--r--crates/ra_assists/src/assist_ctx.rs14
-rw-r--r--crates/ra_assists/src/ast_editor.rs123
-rw-r--r--crates/ra_assists/src/auto_import.rs143
-rw-r--r--crates/ra_assists/src/change_visibility.rs4
-rw-r--r--crates/ra_assists/src/fill_match_arms.rs4
-rw-r--r--crates/ra_assists/src/flip_binexpr.rs4
-rw-r--r--crates/ra_assists/src/flip_comma.rs4
-rw-r--r--crates/ra_assists/src/inline_local_variable.rs10
-rw-r--r--crates/ra_assists/src/introduce_variable.rs24
-rw-r--r--crates/ra_assists/src/move_guard.rs10
-rw-r--r--crates/ra_assists/src/remove_dbg.rs6
-rw-r--r--crates/ra_assists/src/replace_if_let_with_match.rs13
-rw-r--r--crates/ra_cli/src/main.rs6
-rw-r--r--crates/ra_fmt/src/lib.rs14
-rw-r--r--crates/ra_hir/src/adt.rs15
-rw-r--r--crates/ra_hir/src/code_model.rs19
-rw-r--r--crates/ra_hir/src/code_model/docs.rs24
-rw-r--r--crates/ra_hir/src/code_model/src.rs44
-rw-r--r--crates/ra_hir/src/db.rs6
-rw-r--r--crates/ra_hir/src/diagnostics.rs12
-rw-r--r--crates/ra_hir/src/expr.rs46
-rw-r--r--crates/ra_hir/src/expr/scope.rs6
-rw-r--r--crates/ra_hir/src/expr/validation.rs2
-rw-r--r--crates/ra_hir/src/generics.rs22
-rw-r--r--crates/ra_hir/src/ids.rs14
-rw-r--r--crates/ra_hir/src/impl_block.rs24
-rw-r--r--crates/ra_hir/src/lang_item.rs8
-rw-r--r--crates/ra_hir/src/name.rs2
-rw-r--r--crates/ra_hir/src/nameres/raw.rs52
-rw-r--r--crates/ra_hir/src/path.rs26
-rw-r--r--crates/ra_hir/src/source_binder.rs54
-rw-r--r--crates/ra_hir/src/source_id.rs18
-rw-r--r--crates/ra_hir/src/traits.rs6
-rw-r--r--crates/ra_hir/src/ty/tests.rs10
-rw-r--r--crates/ra_hir/src/type_ref.rs4
-rw-r--r--crates/ra_ide_api/src/call_info.rs28
-rw-r--r--crates/ra_ide_api/src/completion/complete_dot.rs9
-rw-r--r--crates/ra_ide_api/src/completion/complete_fn_param.rs7
-rw-r--r--crates/ra_ide_api/src/completion/complete_keyword.rs16
-rw-r--r--crates/ra_ide_api/src/completion/complete_postfix.rs7
-rw-r--r--crates/ra_ide_api/src/completion/complete_scope.rs4
-rw-r--r--crates/ra_ide_api/src/completion/complete_struct_literal.rs4
-rw-r--r--crates/ra_ide_api/src/completion/completion_context.rs26
-rw-r--r--crates/ra_ide_api/src/diagnostics.rs16
-rw-r--r--crates/ra_ide_api/src/display/function_signature.rs2
-rw-r--r--crates/ra_ide_api/src/display/navigation_target.rs56
-rw-r--r--crates/ra_ide_api/src/display/structure.rs50
-rw-r--r--crates/ra_ide_api/src/extend_selection.rs28
-rw-r--r--crates/ra_ide_api/src/folding_ranges.rs48
-rw-r--r--crates/ra_ide_api/src/goto_definition.rs106
-rw-r--r--crates/ra_ide_api/src/goto_type_definition.rs10
-rw-r--r--crates/ra_ide_api/src/hover.rs51
-rw-r--r--crates/ra_ide_api/src/impls.rs10
-rw-r--r--crates/ra_ide_api/src/join_lines.rs23
-rw-r--r--crates/ra_ide_api/src/lib.rs12
-rw-r--r--crates/ra_ide_api/src/matching_brace.rs2
-rw-r--r--crates/ra_ide_api/src/name_ref_kind.rs10
-rw-r--r--crates/ra_ide_api/src/references.rs35
-rw-r--r--crates/ra_ide_api/src/runnables.rs10
-rw-r--r--crates/ra_ide_api/src/status.rs2
-rw-r--r--crates/ra_ide_api/src/symbol_index.rs10
-rw-r--r--crates/ra_ide_api/src/syntax_highlighting.rs25
-rw-r--r--crates/ra_ide_api/src/syntax_tree.rs6
-rw-r--r--crates/ra_ide_api/src/typing.rs19
-rw-r--r--crates/ra_mbe/src/mbe_expander.rs6
-rw-r--r--crates/ra_mbe/src/mbe_parser.rs3
-rw-r--r--crates/ra_mbe/src/syntax_bridge.rs11
-rw-r--r--crates/ra_mbe/src/tests.rs43
-rw-r--r--crates/ra_syntax/Cargo.toml2
-rw-r--r--crates/ra_syntax/src/algo.rs10
-rw-r--r--crates/ra_syntax/src/algo/visit.rs12
-rw-r--r--crates/ra_syntax/src/ast.rs36
-rw-r--r--crates/ra_syntax/src/ast/expr_extensions.rs30
-rw-r--r--crates/ra_syntax/src/ast/extensions.rs64
-rw-r--r--crates/ra_syntax/src/ast/generated.rs2720
-rw-r--r--crates/ra_syntax/src/ast/generated.rs.tera51
-rw-r--r--crates/ra_syntax/src/ast/tokens.rs26
-rw-r--r--crates/ra_syntax/src/ast/traits.rs50
-rw-r--r--crates/ra_syntax/src/fuzz.rs14
-rw-r--r--crates/ra_syntax/src/lib.rs122
-rw-r--r--crates/ra_syntax/src/parsing/reparsing.rs20
-rw-r--r--crates/ra_syntax/src/ptr.rs11
-rw-r--r--crates/ra_syntax/src/syntax_node.rs331
-rw-r--r--crates/ra_syntax/src/syntax_text.rs25
-rw-r--r--crates/ra_syntax/src/validation.rs4
-rw-r--r--crates/ra_syntax/src/validation/block.rs2
-rw-r--r--crates/ra_syntax/src/validation/field_expr.rs2
92 files changed, 1984 insertions, 3100 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 03f5be16b..141cc6088 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1313,7 +1313,7 @@ dependencies = [
1313 "itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", 1313 "itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
1314 "ra_parser 0.1.0", 1314 "ra_parser 0.1.0",
1315 "ra_text_edit 0.1.0", 1315 "ra_text_edit 0.1.0",
1316 "rowan 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", 1316 "rowan 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
1317 "smol_str 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", 1317 "smol_str 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
1318 "test_utils 0.1.0", 1318 "test_utils 0.1.0",
1319 "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 1319 "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -1584,11 +1584,11 @@ dependencies = [
1584 1584
1585[[package]] 1585[[package]]
1586name = "rowan" 1586name = "rowan"
1587version = "0.5.5" 1587version = "0.5.6"
1588source = "registry+https://github.com/rust-lang/crates.io-index" 1588source = "registry+https://github.com/rust-lang/crates.io-index"
1589dependencies = [ 1589dependencies = [
1590 "colosseum 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 1590 "colosseum 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
1591 "parking_lot 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", 1591 "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
1592 "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", 1592 "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
1593 "smol_str 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", 1593 "smol_str 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
1594 "text_unit 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", 1594 "text_unit 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -2275,7 +2275,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
2275"checksum relative-path 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0e7790c7f1cc73d831d28dc5a7deb316a006e7848e6a7f467cdb10a0a9e0fb1c" 2275"checksum relative-path 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0e7790c7f1cc73d831d28dc5a7deb316a006e7848e6a7f467cdb10a0a9e0fb1c"
2276"checksum remove_dir_all 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" 2276"checksum remove_dir_all 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e"
2277"checksum ron 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "17f52a24414403f81528b67488cf8edc4eda977d3af1646bb6b106a600ead78f" 2277"checksum ron 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "17f52a24414403f81528b67488cf8edc4eda977d3af1646bb6b106a600ead78f"
2278"checksum rowan 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)" = "500ba7550373d42593a5228085bad391517378fa31ad2a84defe100dd8259fef" 2278"checksum rowan 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0c433ffe99ac9b96fa9882805d05eee5d750c9202fb42d0546c556e5d70d54be"
2279"checksum rustc-demangle 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "a7f4dccf6f4891ebcc0c39f9b6eb1a83b9bf5d747cb439ec6fba4f3b977038af" 2279"checksum rustc-demangle 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "a7f4dccf6f4891ebcc0c39f9b6eb1a83b9bf5d747cb439ec6fba4f3b977038af"
2280"checksum rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7540fc8b0c49f096ee9c961cda096467dce8084bec6bdca2fc83895fd9b28cb8" 2280"checksum rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7540fc8b0c49f096ee9c961cda096467dce8084bec6bdca2fc83895fd9b28cb8"
2281"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" 2281"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
diff --git a/crates/ra_assists/src/add_derive.rs b/crates/ra_assists/src/add_derive.rs
index bf7d55d6d..f19196f53 100644
--- a/crates/ra_assists/src/add_derive.rs
+++ b/crates/ra_assists/src/add_derive.rs
@@ -9,7 +9,7 @@ use crate::{Assist, AssistCtx, AssistId};
9 9
10pub(crate) fn add_derive(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 10pub(crate) fn add_derive(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
11 let nominal = ctx.node_at_offset::<ast::NominalDef>()?; 11 let nominal = ctx.node_at_offset::<ast::NominalDef>()?;
12 let node_start = derive_insertion_offset(nominal)?; 12 let node_start = derive_insertion_offset(&nominal)?;
13 ctx.add_action(AssistId("add_derive"), "add `#[derive]`", |edit| { 13 ctx.add_action(AssistId("add_derive"), "add `#[derive]`", |edit| {
14 let derive_attr = nominal 14 let derive_attr = nominal
15 .attrs() 15 .attrs()
diff --git a/crates/ra_assists/src/add_explicit_type.rs b/crates/ra_assists/src/add_explicit_type.rs
index bb47a32f0..a69cfc8e3 100644
--- a/crates/ra_assists/src/add_explicit_type.rs
+++ b/crates/ra_assists/src/add_explicit_type.rs
@@ -27,7 +27,7 @@ pub(crate) fn add_explicit_type(mut ctx: AssistCtx<impl HirDatabase>) -> Option<
27 // Infer type 27 // Infer type
28 let db = ctx.db; 28 let db = ctx.db;
29 let analyzer = hir::SourceAnalyzer::new(db, ctx.frange.file_id, stmt.syntax(), None); 29 let analyzer = hir::SourceAnalyzer::new(db, ctx.frange.file_id, stmt.syntax(), None);
30 let ty = analyzer.type_of(db, expr)?; 30 let ty = analyzer.type_of(db, &expr)?;
31 // Assist not applicable if the type is unknown 31 // Assist not applicable if the type is unknown
32 if is_unknown(&ty) { 32 if is_unknown(&ty) {
33 return None; 33 return None;
diff --git a/crates/ra_assists/src/add_impl.rs b/crates/ra_assists/src/add_impl.rs
index b81922c1d..cebc19539 100644
--- a/crates/ra_assists/src/add_impl.rs
+++ b/crates/ra_assists/src/add_impl.rs
@@ -16,7 +16,7 @@ pub(crate) fn add_impl(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
16 let start_offset = nominal.syntax().range().end(); 16 let start_offset = nominal.syntax().range().end();
17 let mut buf = String::new(); 17 let mut buf = String::new();
18 buf.push_str("\n\nimpl"); 18 buf.push_str("\n\nimpl");
19 if let Some(type_params) = type_params { 19 if let Some(type_params) = &type_params {
20 type_params.syntax().text().push_to(&mut buf); 20 type_params.syntax().text().push_to(&mut buf);
21 } 21 }
22 buf.push_str(" "); 22 buf.push_str(" ");
@@ -25,9 +25,9 @@ pub(crate) fn add_impl(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
25 let lifetime_params = type_params 25 let lifetime_params = type_params
26 .lifetime_params() 26 .lifetime_params()
27 .filter_map(|it| it.lifetime_token()) 27 .filter_map(|it| it.lifetime_token())
28 .map(|it| it.text()); 28 .map(|it| it.text().clone());
29 let type_params = 29 let type_params =
30 type_params.type_params().filter_map(|it| it.name()).map(|it| it.text()); 30 type_params.type_params().filter_map(|it| it.name()).map(|it| it.text().clone());
31 join(lifetime_params.chain(type_params)).surround_with("<", ">").to_buf(&mut buf); 31 join(lifetime_params.chain(type_params)).surround_with("<", ">").to_buf(&mut buf);
32 } 32 }
33 buf.push_str(" {\n"); 33 buf.push_str(" {\n");
diff --git a/crates/ra_assists/src/add_missing_impl_members.rs b/crates/ra_assists/src/add_missing_impl_members.rs
index 6ffdad0b1..b992a4dc8 100644
--- a/crates/ra_assists/src/add_missing_impl_members.rs
+++ b/crates/ra_assists/src/add_missing_impl_members.rs
@@ -5,8 +5,8 @@ use crate::{
5 5
6use hir::{db::HirDatabase, HasSource}; 6use hir::{db::HirDatabase, HasSource};
7use ra_db::FilePosition; 7use ra_db::FilePosition;
8use ra_syntax::ast::{self, AstNode, ImplItem, ImplItemKind, NameOwner}; 8use ra_syntax::ast::{self, AstNode, ImplItemKind, NameOwner};
9use ra_syntax::{SmolStr, TreeArc}; 9use ra_syntax::SmolStr;
10 10
11#[derive(PartialEq)] 11#[derive(PartialEq)]
12enum AddMissingImplMembersMode { 12enum AddMissingImplMembersMode {
@@ -46,16 +46,16 @@ fn add_missing_impl_members_inner(
46 let position = FilePosition { file_id, offset: impl_node.syntax().range().start() }; 46 let position = FilePosition { file_id, offset: impl_node.syntax().range().start() };
47 let analyzer = hir::SourceAnalyzer::new(ctx.db, position.file_id, impl_node.syntax(), None); 47 let analyzer = hir::SourceAnalyzer::new(ctx.db, position.file_id, impl_node.syntax(), None);
48 48
49 resolve_target_trait_def(ctx.db, &analyzer, impl_node)? 49 resolve_target_trait_def(ctx.db, &analyzer, &impl_node)?
50 }; 50 };
51 51
52 let def_name = |kind| -> Option<&SmolStr> { 52 let def_name = |kind| -> Option<SmolStr> {
53 match kind { 53 match kind {
54 ImplItemKind::FnDef(def) => def.name(), 54 ast::ImplItemKind::FnDef(def) => def.name(),
55 ImplItemKind::TypeAliasDef(def) => def.name(), 55 ast::ImplItemKind::TypeAliasDef(def) => def.name(),
56 ImplItemKind::ConstDef(def) => def.name(), 56 ast::ImplItemKind::ConstDef(def) => def.name(),
57 } 57 }
58 .map(ast::Name::text) 58 .map(|it| it.text().clone())
59 }; 59 };
60 60
61 let trait_items = trait_def.item_list()?.impl_items(); 61 let trait_items = trait_def.item_list()?.impl_items();
@@ -78,18 +78,13 @@ fn add_missing_impl_members_inner(
78 78
79 ctx.add_action(AssistId(assist_id), label, |edit| { 79 ctx.add_action(AssistId(assist_id), label, |edit| {
80 let n_existing_items = impl_item_list.impl_items().count(); 80 let n_existing_items = impl_item_list.impl_items().count();
81 let items: Vec<_> = missing_items 81 let items = missing_items.into_iter().map(|it| match it.kind() {
82 .into_iter() 82 ImplItemKind::FnDef(def) => strip_docstring(add_body(def).into()),
83 .map(|it| match it.kind() { 83 _ => strip_docstring(it),
84 ImplItemKind::FnDef(def) => { 84 });
85 strip_docstring(ImplItem::cast(add_body(def).syntax()).unwrap())
86 }
87 _ => strip_docstring(it),
88 })
89 .collect();
90 let mut ast_editor = AstEditor::new(impl_item_list); 85 let mut ast_editor = AstEditor::new(impl_item_list);
91 86
92 ast_editor.append_items(items.iter().map(|it| &**it)); 87 ast_editor.append_items(items);
93 88
94 let first_new_item = ast_editor.ast().impl_items().nth(n_existing_items).unwrap(); 89 let first_new_item = ast_editor.ast().impl_items().nth(n_existing_items).unwrap();
95 let cursor_position = first_new_item.syntax().range().start(); 90 let cursor_position = first_new_item.syntax().range().start();
@@ -101,14 +96,14 @@ fn add_missing_impl_members_inner(
101 ctx.build() 96 ctx.build()
102} 97}
103 98
104fn strip_docstring(item: &ast::ImplItem) -> TreeArc<ast::ImplItem> { 99fn strip_docstring(item: ast::ImplItem) -> ast::ImplItem {
105 let mut ast_editor = AstEditor::new(item); 100 let mut ast_editor = AstEditor::new(item);
106 ast_editor.strip_attrs_and_docs(); 101 ast_editor.strip_attrs_and_docs();
107 ast_editor.ast().to_owned() 102 ast_editor.ast().to_owned()
108} 103}
109 104
110fn add_body(fn_def: &ast::FnDef) -> TreeArc<ast::FnDef> { 105fn add_body(fn_def: ast::FnDef) -> ast::FnDef {
111 let mut ast_editor = AstEditor::new(fn_def); 106 let mut ast_editor = AstEditor::new(fn_def.clone());
112 if fn_def.body().is_none() { 107 if fn_def.body().is_none() {
113 ast_editor.set_body(&AstBuilder::<ast::Block>::single_expr( 108 ast_editor.set_body(&AstBuilder::<ast::Block>::single_expr(
114 &AstBuilder::<ast::Expr>::unimplemented(), 109 &AstBuilder::<ast::Expr>::unimplemented(),
@@ -123,9 +118,12 @@ fn resolve_target_trait_def(
123 db: &impl HirDatabase, 118 db: &impl HirDatabase,
124 analyzer: &hir::SourceAnalyzer, 119 analyzer: &hir::SourceAnalyzer,
125 impl_block: &ast::ImplBlock, 120 impl_block: &ast::ImplBlock,
126) -> Option<TreeArc<ast::TraitDef>> { 121) -> Option<ast::TraitDef> {
127 let ast_path = 122 let ast_path = impl_block
128 impl_block.target_trait().map(AstNode::syntax).and_then(ast::PathType::cast)?.path()?; 123 .target_trait()
124 .map(|it| it.syntax().clone())
125 .and_then(ast::PathType::cast)?
126 .path()?;
129 127
130 match analyzer.resolve_path(db, &ast_path) { 128 match analyzer.resolve_path(db, &ast_path) {
131 Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => Some(def.source(db).ast), 129 Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => Some(def.source(db).ast),
diff --git a/crates/ra_assists/src/assist_ctx.rs b/crates/ra_assists/src/assist_ctx.rs
index 34b207154..e52085f85 100644
--- a/crates/ra_assists/src/assist_ctx.rs
+++ b/crates/ra_assists/src/assist_ctx.rs
@@ -49,7 +49,7 @@ pub(crate) enum Assist {
49pub(crate) struct AssistCtx<'a, DB> { 49pub(crate) struct AssistCtx<'a, DB> {
50 pub(crate) db: &'a DB, 50 pub(crate) db: &'a DB,
51 pub(crate) frange: FileRange, 51 pub(crate) frange: FileRange,
52 source_file: &'a SourceFile, 52 source_file: SourceFile,
53 should_compute_edit: bool, 53 should_compute_edit: bool,
54 assist: Assist, 54 assist: Assist,
55} 55}
@@ -59,7 +59,7 @@ impl<'a, DB> Clone for AssistCtx<'a, DB> {
59 AssistCtx { 59 AssistCtx {
60 db: self.db, 60 db: self.db,
61 frange: self.frange, 61 frange: self.frange,
62 source_file: self.source_file, 62 source_file: self.source_file.clone(),
63 should_compute_edit: self.should_compute_edit, 63 should_compute_edit: self.should_compute_edit,
64 assist: self.assist.clone(), 64 assist: self.assist.clone(),
65 } 65 }
@@ -104,18 +104,18 @@ impl<'a, DB: HirDatabase> AssistCtx<'a, DB> {
104 Some(self.assist) 104 Some(self.assist)
105 } 105 }
106 106
107 pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken<'a>> { 107 pub(crate) fn token_at_offset(&self) -> TokenAtOffset<SyntaxToken> {
108 find_token_at_offset(self.source_file.syntax(), self.frange.range.start()) 108 find_token_at_offset(self.source_file.syntax(), self.frange.range.start())
109 } 109 }
110 110
111 pub(crate) fn node_at_offset<N: AstNode>(&self) -> Option<&'a N> { 111 pub(crate) fn node_at_offset<N: AstNode>(&self) -> Option<N> {
112 find_node_at_offset(self.source_file.syntax(), self.frange.range.start()) 112 find_node_at_offset(self.source_file.syntax(), self.frange.range.start())
113 } 113 }
114 pub(crate) fn covering_element(&self) -> SyntaxElement<'a> { 114 pub(crate) fn covering_element(&self) -> SyntaxElement {
115 find_covering_element(self.source_file.syntax(), self.frange.range) 115 find_covering_element(self.source_file.syntax(), self.frange.range)
116 } 116 }
117 117
118 pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement<'a> { 118 pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {
119 find_covering_element(self.source_file.syntax(), range) 119 find_covering_element(self.source_file.syntax(), range)
120 } 120 }
121} 121}
@@ -139,7 +139,7 @@ impl AssistBuilder {
139 ) { 139 ) {
140 let mut replace_with = replace_with.into(); 140 let mut replace_with = replace_with.into();
141 if let Some(indent) = leading_indent(node) { 141 if let Some(indent) = leading_indent(node) {
142 replace_with = reindent(&replace_with, indent) 142 replace_with = reindent(&replace_with, &indent)
143 } 143 }
144 self.replace(node.range(), replace_with) 144 self.replace(node.range(), replace_with)
145 } 145 }
diff --git a/crates/ra_assists/src/ast_editor.rs b/crates/ra_assists/src/ast_editor.rs
index 7b743c9f0..5fbcadfee 100644
--- a/crates/ra_assists/src/ast_editor.rs
+++ b/crates/ra_assists/src/ast_editor.rs
@@ -4,18 +4,18 @@ use arrayvec::ArrayVec;
4use hir::Name; 4use hir::Name;
5use ra_fmt::leading_indent; 5use ra_fmt::leading_indent;
6use ra_syntax::{ 6use ra_syntax::{
7 ast, AstNode, Direction, InsertPosition, SourceFile, SyntaxElement, SyntaxKind::*, TreeArc, T, 7 ast, AstNode, Direction, InsertPosition, SourceFile, SyntaxElement, SyntaxKind::*, T,
8}; 8};
9use ra_text_edit::TextEditBuilder; 9use ra_text_edit::TextEditBuilder;
10 10
11pub struct AstEditor<N: AstNode> { 11pub struct AstEditor<N: AstNode> {
12 original_ast: TreeArc<N>, 12 original_ast: N,
13 ast: TreeArc<N>, 13 ast: N,
14} 14}
15 15
16impl<N: AstNode> AstEditor<N> { 16impl<N: AstNode> AstEditor<N> {
17 pub fn new(node: &N) -> AstEditor<N> { 17 pub fn new(node: N) -> AstEditor<N> {
18 AstEditor { original_ast: node.to_owned(), ast: node.to_owned() } 18 AstEditor { original_ast: node.clone(), ast: node }
19 } 19 }
20 20
21 pub fn into_text_edit(self, builder: &mut TextEditBuilder) { 21 pub fn into_text_edit(self, builder: &mut TextEditBuilder) {
@@ -26,27 +26,27 @@ impl<N: AstNode> AstEditor<N> {
26 } 26 }
27 27
28 pub fn ast(&self) -> &N { 28 pub fn ast(&self) -> &N {
29 &*self.ast 29 &self.ast
30 } 30 }
31 31
32 #[must_use] 32 #[must_use]
33 fn insert_children<'a>( 33 fn insert_children(
34 &self, 34 &self,
35 position: InsertPosition<SyntaxElement<'_>>, 35 position: InsertPosition<SyntaxElement>,
36 to_insert: impl Iterator<Item = SyntaxElement<'a>>, 36 to_insert: impl Iterator<Item = SyntaxElement>,
37 ) -> TreeArc<N> { 37 ) -> N {
38 let new_syntax = self.ast().syntax().insert_children(position, to_insert); 38 let new_syntax = self.ast().syntax().insert_children(position, to_insert);
39 N::cast(&new_syntax).unwrap().to_owned() 39 N::cast(new_syntax).unwrap()
40 } 40 }
41 41
42 #[must_use] 42 #[must_use]
43 fn replace_children<'a>( 43 fn replace_children(
44 &self, 44 &self,
45 to_delete: RangeInclusive<SyntaxElement<'_>>, 45 to_delete: RangeInclusive<SyntaxElement>,
46 to_insert: impl Iterator<Item = SyntaxElement<'a>>, 46 to_insert: impl Iterator<Item = SyntaxElement>,
47 ) -> TreeArc<N> { 47 ) -> N {
48 let new_syntax = self.ast().syntax().replace_children(to_delete, to_insert); 48 let new_syntax = self.ast().syntax().replace_children(to_delete, to_insert);
49 N::cast(&new_syntax).unwrap().to_owned() 49 N::cast(new_syntax).unwrap()
50 } 50 }
51 51
52 fn do_make_multiline(&mut self) { 52 fn do_make_multiline(&mut self) {
@@ -66,16 +66,18 @@ impl<N: AstNode> AstEditor<N> {
66 if ws.text().contains('\n') { 66 if ws.text().contains('\n') {
67 return; 67 return;
68 } 68 }
69 Some(ws) 69 Some(ws.clone())
70 } 70 }
71 }; 71 };
72 72
73 let indent = leading_indent(self.ast().syntax()).unwrap_or(""); 73 let indent = leading_indent(self.ast().syntax()).unwrap_or("".into());
74 let ws = tokens::WsBuilder::new(&format!("\n{}", indent)); 74 let ws = tokens::WsBuilder::new(&format!("\n{}", indent));
75 let to_insert = iter::once(ws.ws().into()); 75 let to_insert = iter::once(ws.ws().into());
76 self.ast = match existing_ws { 76 self.ast = match existing_ws {
77 None => self.insert_children(InsertPosition::After(l_curly), to_insert), 77 None => self.insert_children(InsertPosition::After(l_curly), to_insert),
78 Some(ws) => self.replace_children(RangeInclusive::new(ws.into(), ws.into()), to_insert), 78 Some(ws) => {
79 self.replace_children(RangeInclusive::new(ws.clone().into(), ws.into()), to_insert)
80 }
79 }; 81 };
80 } 82 }
81} 83}
@@ -95,7 +97,7 @@ impl AstEditor<ast::NamedFieldList> {
95 let space = if is_multiline { 97 let space = if is_multiline {
96 ws = tokens::WsBuilder::new(&format!( 98 ws = tokens::WsBuilder::new(&format!(
97 "\n{} ", 99 "\n{} ",
98 leading_indent(self.ast().syntax()).unwrap_or("") 100 leading_indent(self.ast().syntax()).unwrap_or("".into())
99 )); 101 ));
100 ws.ws() 102 ws.ws()
101 } else { 103 } else {
@@ -104,7 +106,7 @@ impl AstEditor<ast::NamedFieldList> {
104 106
105 let mut to_insert: ArrayVec<[SyntaxElement; 4]> = ArrayVec::new(); 107 let mut to_insert: ArrayVec<[SyntaxElement; 4]> = ArrayVec::new();
106 to_insert.push(space.into()); 108 to_insert.push(space.into());
107 to_insert.push(field.syntax().into()); 109 to_insert.push(field.syntax().clone().into());
108 to_insert.push(tokens::comma().into()); 110 to_insert.push(tokens::comma().into());
109 111
110 macro_rules! after_l_curly { 112 macro_rules! after_l_curly {
@@ -127,7 +129,7 @@ impl AstEditor<ast::NamedFieldList> {
127 InsertPosition::After(comma) 129 InsertPosition::After(comma)
128 } else { 130 } else {
129 to_insert.insert(0, tokens::comma().into()); 131 to_insert.insert(0, tokens::comma().into());
130 InsertPosition::After($anchor.syntax().into()) 132 InsertPosition::After($anchor.syntax().clone().into())
131 } 133 }
132 }; 134 };
133 }; 135 };
@@ -144,7 +146,9 @@ impl AstEditor<ast::NamedFieldList> {
144 None => after_l_curly!(), 146 None => after_l_curly!(),
145 } 147 }
146 } 148 }
147 InsertPosition::Before(anchor) => InsertPosition::Before(anchor.syntax().into()), 149 InsertPosition::Before(anchor) => {
150 InsertPosition::Before(anchor.syntax().clone().into())
151 }
148 InsertPosition::After(anchor) => after_field!(anchor), 152 InsertPosition::After(anchor) => after_field!(anchor),
149 }; 153 };
150 154
@@ -157,7 +161,7 @@ impl AstEditor<ast::NamedFieldList> {
157} 161}
158 162
159impl AstEditor<ast::ItemList> { 163impl AstEditor<ast::ItemList> {
160 pub fn append_items<'a>(&mut self, items: impl Iterator<Item = &'a ast::ImplItem>) { 164 pub fn append_items(&mut self, items: impl Iterator<Item = ast::ImplItem>) {
161 let n_existing_items = self.ast().impl_items().count(); 165 let n_existing_items = self.ast().impl_items().count();
162 if n_existing_items == 0 { 166 if n_existing_items == 0 {
163 self.do_make_multiline(); 167 self.do_make_multiline();
@@ -165,22 +169,23 @@ impl AstEditor<ast::ItemList> {
165 items.for_each(|it| self.append_item(it)); 169 items.for_each(|it| self.append_item(it));
166 } 170 }
167 171
168 pub fn append_item(&mut self, item: &ast::ImplItem) { 172 pub fn append_item(&mut self, item: ast::ImplItem) {
169 let (indent, position) = match self.ast().impl_items().last() { 173 let (indent, position) = match self.ast().impl_items().last() {
170 Some(it) => ( 174 Some(it) => (
171 leading_indent(it.syntax()).unwrap_or("").to_string(), 175 leading_indent(it.syntax()).unwrap_or_default().to_string(),
172 InsertPosition::After(it.syntax().into()), 176 InsertPosition::After(it.syntax().clone().into()),
173 ), 177 ),
174 None => match self.l_curly() { 178 None => match self.l_curly() {
175 Some(it) => ( 179 Some(it) => (
176 " ".to_string() + leading_indent(self.ast().syntax()).unwrap_or(""), 180 " ".to_string() + &leading_indent(self.ast().syntax()).unwrap_or_default(),
177 InsertPosition::After(it), 181 InsertPosition::After(it),
178 ), 182 ),
179 None => return, 183 None => return,
180 }, 184 },
181 }; 185 };
182 let ws = tokens::WsBuilder::new(&format!("\n{}", indent)); 186 let ws = tokens::WsBuilder::new(&format!("\n{}", indent));
183 let to_insert: ArrayVec<[SyntaxElement; 2]> = [ws.ws().into(), item.syntax().into()].into(); 187 let to_insert: ArrayVec<[SyntaxElement; 2]> =
188 [ws.ws().into(), item.syntax().clone().into()].into();
184 self.ast = self.insert_children(position, to_insert.into_iter()); 189 self.ast = self.insert_children(position, to_insert.into_iter());
185 } 190 }
186 191
@@ -197,9 +202,9 @@ impl AstEditor<ast::ImplItem> {
197 .children_with_tokens() 202 .children_with_tokens()
198 .find(|it| it.kind() == ATTR || it.kind() == COMMENT) 203 .find(|it| it.kind() == ATTR || it.kind() == COMMENT)
199 { 204 {
200 let end = match start.next_sibling_or_token() { 205 let end = match &start.next_sibling_or_token() {
201 Some(el) if el.kind() == WHITESPACE => el, 206 Some(el) if el.kind() == WHITESPACE => el.clone(),
202 Some(_) | None => start, 207 Some(_) | None => start.clone(),
203 }; 208 };
204 self.ast = self.replace_children(RangeInclusive::new(start, end), iter::empty()); 209 self.ast = self.replace_children(RangeInclusive::new(start, end), iter::empty());
205 } 210 }
@@ -210,18 +215,18 @@ impl AstEditor<ast::FnDef> {
210 pub fn set_body(&mut self, body: &ast::Block) { 215 pub fn set_body(&mut self, body: &ast::Block) {
211 let mut to_insert: ArrayVec<[SyntaxElement; 2]> = ArrayVec::new(); 216 let mut to_insert: ArrayVec<[SyntaxElement; 2]> = ArrayVec::new();
212 let old_body_or_semi: SyntaxElement = if let Some(old_body) = self.ast().body() { 217 let old_body_or_semi: SyntaxElement = if let Some(old_body) = self.ast().body() {
213 old_body.syntax().into() 218 old_body.syntax().clone().into()
214 } else if let Some(semi) = self.ast().semicolon_token() { 219 } else if let Some(semi) = self.ast().semicolon_token() {
215 to_insert.push(tokens::single_space().into()); 220 to_insert.push(tokens::single_space().into());
216 semi.into() 221 semi.into()
217 } else { 222 } else {
218 to_insert.push(tokens::single_space().into()); 223 to_insert.push(tokens::single_space().into());
219 to_insert.push(body.syntax().into()); 224 to_insert.push(body.syntax().clone().into());
220 self.ast = self.insert_children(InsertPosition::Last, to_insert.into_iter()); 225 self.ast = self.insert_children(InsertPosition::Last, to_insert.into_iter());
221 return; 226 return;
222 }; 227 };
223 to_insert.push(body.syntax().into()); 228 to_insert.push(body.syntax().clone().into());
224 let replace_range = RangeInclusive::new(old_body_or_semi, old_body_or_semi); 229 let replace_range = RangeInclusive::new(old_body_or_semi.clone(), old_body_or_semi);
225 self.ast = self.replace_children(replace_range, to_insert.into_iter()) 230 self.ast = self.replace_children(replace_range, to_insert.into_iter())
226 } 231 }
227} 232}
@@ -231,15 +236,15 @@ pub struct AstBuilder<N: AstNode> {
231} 236}
232 237
233impl AstBuilder<ast::NamedField> { 238impl AstBuilder<ast::NamedField> {
234 pub fn from_name(name: &Name) -> TreeArc<ast::NamedField> { 239 pub fn from_name(name: &Name) -> ast::NamedField {
235 ast_node_from_file_text(&format!("fn f() {{ S {{ {}: (), }} }}", name)) 240 ast_node_from_file_text(&format!("fn f() {{ S {{ {}: (), }} }}", name))
236 } 241 }
237 242
238 fn from_text(text: &str) -> TreeArc<ast::NamedField> { 243 fn from_text(text: &str) -> ast::NamedField {
239 ast_node_from_file_text(&format!("fn f() {{ S {{ {}, }} }}", text)) 244 ast_node_from_file_text(&format!("fn f() {{ S {{ {}, }} }}", text))
240 } 245 }
241 246
242 pub fn from_pieces(name: &ast::NameRef, expr: Option<&ast::Expr>) -> TreeArc<ast::NamedField> { 247 pub fn from_pieces(name: &ast::NameRef, expr: Option<&ast::Expr>) -> ast::NamedField {
243 match expr { 248 match expr {
244 Some(expr) => Self::from_text(&format!("{}: {}", name.syntax(), expr.syntax())), 249 Some(expr) => Self::from_text(&format!("{}: {}", name.syntax(), expr.syntax())),
245 None => Self::from_text(&name.syntax().to_string()), 250 None => Self::from_text(&name.syntax().to_string()),
@@ -248,36 +253,36 @@ impl AstBuilder<ast::NamedField> {
248} 253}
249 254
250impl AstBuilder<ast::Block> { 255impl AstBuilder<ast::Block> {
251 fn from_text(text: &str) -> TreeArc<ast::Block> { 256 fn from_text(text: &str) -> ast::Block {
252 ast_node_from_file_text(&format!("fn f() {}", text)) 257 ast_node_from_file_text(&format!("fn f() {}", text))
253 } 258 }
254 259
255 pub fn single_expr(e: &ast::Expr) -> TreeArc<ast::Block> { 260 pub fn single_expr(e: &ast::Expr) -> ast::Block {
256 Self::from_text(&format!("{{ {} }}", e.syntax())) 261 Self::from_text(&format!("{{ {} }}", e.syntax()))
257 } 262 }
258} 263}
259 264
260impl AstBuilder<ast::Expr> { 265impl AstBuilder<ast::Expr> {
261 fn from_text(text: &str) -> TreeArc<ast::Expr> { 266 fn from_text(text: &str) -> ast::Expr {
262 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text)) 267 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text))
263 } 268 }
264 269
265 pub fn unit() -> TreeArc<ast::Expr> { 270 pub fn unit() -> ast::Expr {
266 Self::from_text("()") 271 Self::from_text("()")
267 } 272 }
268 273
269 pub fn unimplemented() -> TreeArc<ast::Expr> { 274 pub fn unimplemented() -> ast::Expr {
270 Self::from_text("unimplemented!()") 275 Self::from_text("unimplemented!()")
271 } 276 }
272} 277}
273 278
274impl AstBuilder<ast::NameRef> { 279impl AstBuilder<ast::NameRef> {
275 pub fn new(text: &str) -> TreeArc<ast::NameRef> { 280 pub fn new(text: &str) -> ast::NameRef {
276 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text)) 281 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text))
277 } 282 }
278} 283}
279 284
280fn ast_node_from_file_text<N: AstNode>(text: &str) -> TreeArc<N> { 285fn ast_node_from_file_text<N: AstNode>(text: &str) -> N {
281 let parse = SourceFile::parse(text); 286 let parse = SourceFile::parse(text);
282 let res = parse.tree().syntax().descendants().find_map(N::cast).unwrap().to_owned(); 287 let res = parse.tree().syntax().descendants().find_map(N::cast).unwrap().to_owned();
283 res 288 res
@@ -285,47 +290,49 @@ fn ast_node_from_file_text<N: AstNode>(text: &str) -> TreeArc<N> {
285 290
286mod tokens { 291mod tokens {
287 use once_cell::sync::Lazy; 292 use once_cell::sync::Lazy;
288 use ra_syntax::{AstNode, SourceFile, SyntaxKind::*, SyntaxToken, TreeArc, T}; 293 use ra_syntax::{AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken, T};
289 294
290 static SOURCE_FILE: Lazy<TreeArc<SourceFile>> = 295 static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| SourceFile::parse(",\n; ;"));
291 Lazy::new(|| SourceFile::parse(",\n; ;").tree().to_owned());
292 296
293 pub(crate) fn comma() -> SyntaxToken<'static> { 297 pub(crate) fn comma() -> SyntaxToken {
294 SOURCE_FILE 298 SOURCE_FILE
299 .tree()
295 .syntax() 300 .syntax()
296 .descendants_with_tokens() 301 .descendants_with_tokens()
297 .filter_map(|it| it.as_token()) 302 .filter_map(|it| it.as_token().cloned())
298 .find(|it| it.kind() == T![,]) 303 .find(|it| it.kind() == T![,])
299 .unwrap() 304 .unwrap()
300 } 305 }
301 306
302 pub(crate) fn single_space() -> SyntaxToken<'static> { 307 pub(crate) fn single_space() -> SyntaxToken {
303 SOURCE_FILE 308 SOURCE_FILE
309 .tree()
304 .syntax() 310 .syntax()
305 .descendants_with_tokens() 311 .descendants_with_tokens()
306 .filter_map(|it| it.as_token()) 312 .filter_map(|it| it.as_token().cloned())
307 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == " ") 313 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == " ")
308 .unwrap() 314 .unwrap()
309 } 315 }
310 316
311 #[allow(unused)] 317 #[allow(unused)]
312 pub(crate) fn single_newline() -> SyntaxToken<'static> { 318 pub(crate) fn single_newline() -> SyntaxToken {
313 SOURCE_FILE 319 SOURCE_FILE
320 .tree()
314 .syntax() 321 .syntax()
315 .descendants_with_tokens() 322 .descendants_with_tokens()
316 .filter_map(|it| it.as_token()) 323 .filter_map(|it| it.as_token().cloned())
317 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == "\n") 324 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == "\n")
318 .unwrap() 325 .unwrap()
319 } 326 }
320 327
321 pub(crate) struct WsBuilder(TreeArc<SourceFile>); 328 pub(crate) struct WsBuilder(SourceFile);
322 329
323 impl WsBuilder { 330 impl WsBuilder {
324 pub(crate) fn new(text: &str) -> WsBuilder { 331 pub(crate) fn new(text: &str) -> WsBuilder {
325 WsBuilder(SourceFile::parse(text).ok().unwrap()) 332 WsBuilder(SourceFile::parse(text).ok().unwrap())
326 } 333 }
327 pub(crate) fn ws(&self) -> SyntaxToken<'_> { 334 pub(crate) fn ws(&self) -> SyntaxToken {
328 self.0.syntax().first_child_or_token().unwrap().as_token().unwrap() 335 self.0.syntax().first_child_or_token().unwrap().as_token().cloned().unwrap()
329 } 336 }
330 } 337 }
331 338
diff --git a/crates/ra_assists/src/auto_import.rs b/crates/ra_assists/src/auto_import.rs
index f8f37e852..0eb4bdb62 100644
--- a/crates/ra_assists/src/auto_import.rs
+++ b/crates/ra_assists/src/auto_import.rs
@@ -12,25 +12,25 @@ use ra_syntax::{
12 SyntaxNode, TextRange, T, 12 SyntaxNode, TextRange, T,
13}; 13};
14 14
15fn collect_path_segments_raw<'a>( 15fn collect_path_segments_raw(
16 segments: &mut Vec<&'a ast::PathSegment>, 16 segments: &mut Vec<ast::PathSegment>,
17 mut path: &'a ast::Path, 17 mut path: ast::Path,
18) -> Option<usize> { 18) -> Option<usize> {
19 let oldlen = segments.len(); 19 let oldlen = segments.len();
20 loop { 20 loop {
21 let mut children = path.syntax().children_with_tokens(); 21 let mut children = path.syntax().children_with_tokens();
22 let (first, second, third) = ( 22 let (first, second, third) = (
23 children.next().map(|n| (n, n.kind())), 23 children.next().map(|n| (n.clone(), n.kind())),
24 children.next().map(|n| (n, n.kind())), 24 children.next().map(|n| (n.clone(), n.kind())),
25 children.next().map(|n| (n, n.kind())), 25 children.next().map(|n| (n.clone(), n.kind())),
26 ); 26 );
27 match (first, second, third) { 27 match (first, second, third) {
28 (Some((subpath, PATH)), Some((_, T![::])), Some((segment, PATH_SEGMENT))) => { 28 (Some((subpath, PATH)), Some((_, T![::])), Some((segment, PATH_SEGMENT))) => {
29 path = ast::Path::cast(subpath.as_node()?)?; 29 path = ast::Path::cast(subpath.as_node()?.clone())?;
30 segments.push(ast::PathSegment::cast(segment.as_node()?)?); 30 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
31 } 31 }
32 (Some((segment, PATH_SEGMENT)), _, _) => { 32 (Some((segment, PATH_SEGMENT)), _, _) => {
33 segments.push(ast::PathSegment::cast(segment.as_node()?)?); 33 segments.push(ast::PathSegment::cast(segment.as_node()?.clone())?);
34 break; 34 break;
35 } 35 }
36 (_, _, _) => return None, 36 (_, _, _) => return None,
@@ -60,7 +60,7 @@ fn fmt_segments_raw(segments: &[SmolStr], buf: &mut String) {
60} 60}
61 61
62// Returns the numeber of common segments. 62// Returns the numeber of common segments.
63fn compare_path_segments(left: &[SmolStr], right: &[&ast::PathSegment]) -> usize { 63fn compare_path_segments(left: &[SmolStr], right: &[ast::PathSegment]) -> usize {
64 left.iter().zip(right).filter(|(l, r)| compare_path_segment(l, r)).count() 64 left.iter().zip(right).filter(|(l, r)| compare_path_segment(l, r)).count()
65} 65}
66 66
@@ -81,12 +81,12 @@ fn compare_path_segment_with_name(a: &SmolStr, b: &ast::Name) -> bool {
81 a == b.text() 81 a == b.text()
82} 82}
83 83
84#[derive(Copy, Clone)] 84#[derive(Clone)]
85enum ImportAction<'a> { 85enum ImportAction {
86 Nothing, 86 Nothing,
87 // Add a brand new use statement. 87 // Add a brand new use statement.
88 AddNewUse { 88 AddNewUse {
89 anchor: Option<&'a SyntaxNode>, // anchor node 89 anchor: Option<SyntaxNode>, // anchor node
90 add_after_anchor: bool, 90 add_after_anchor: bool,
91 }, 91 },
92 92
@@ -94,9 +94,9 @@ enum ImportAction<'a> {
94 AddNestedImport { 94 AddNestedImport {
95 // how may segments matched with the target path 95 // how may segments matched with the target path
96 common_segments: usize, 96 common_segments: usize,
97 path_to_split: &'a ast::Path, 97 path_to_split: ast::Path,
98 // the first segment of path_to_split we want to add into the new nested list 98 // the first segment of path_to_split we want to add into the new nested list
99 first_segment_to_split: Option<&'a ast::PathSegment>, 99 first_segment_to_split: Option<ast::PathSegment>,
100 // Wether to add 'self' in addition to the target path 100 // Wether to add 'self' in addition to the target path
101 add_self: bool, 101 add_self: bool,
102 }, 102 },
@@ -104,20 +104,20 @@ enum ImportAction<'a> {
104 AddInTreeList { 104 AddInTreeList {
105 common_segments: usize, 105 common_segments: usize,
106 // The UseTreeList where to add the target path 106 // The UseTreeList where to add the target path
107 tree_list: &'a ast::UseTreeList, 107 tree_list: ast::UseTreeList,
108 add_self: bool, 108 add_self: bool,
109 }, 109 },
110} 110}
111 111
112impl<'a> ImportAction<'a> { 112impl ImportAction {
113 fn add_new_use(anchor: Option<&'a SyntaxNode>, add_after_anchor: bool) -> Self { 113 fn add_new_use(anchor: Option<SyntaxNode>, add_after_anchor: bool) -> Self {
114 ImportAction::AddNewUse { anchor, add_after_anchor } 114 ImportAction::AddNewUse { anchor, add_after_anchor }
115 } 115 }
116 116
117 fn add_nested_import( 117 fn add_nested_import(
118 common_segments: usize, 118 common_segments: usize,
119 path_to_split: &'a ast::Path, 119 path_to_split: ast::Path,
120 first_segment_to_split: Option<&'a ast::PathSegment>, 120 first_segment_to_split: Option<ast::PathSegment>,
121 add_self: bool, 121 add_self: bool,
122 ) -> Self { 122 ) -> Self {
123 ImportAction::AddNestedImport { 123 ImportAction::AddNestedImport {
@@ -130,14 +130,14 @@ impl<'a> ImportAction<'a> {
130 130
131 fn add_in_tree_list( 131 fn add_in_tree_list(
132 common_segments: usize, 132 common_segments: usize,
133 tree_list: &'a ast::UseTreeList, 133 tree_list: ast::UseTreeList,
134 add_self: bool, 134 add_self: bool,
135 ) -> Self { 135 ) -> Self {
136 ImportAction::AddInTreeList { common_segments, tree_list, add_self } 136 ImportAction::AddInTreeList { common_segments, tree_list, add_self }
137 } 137 }
138 138
139 fn better<'b>(left: &'b ImportAction<'a>, right: &'b ImportAction<'a>) -> &'b ImportAction<'a> { 139 fn better(left: ImportAction, right: ImportAction) -> ImportAction {
140 if left.is_better(right) { 140 if left.is_better(&right) {
141 left 141 left
142 } else { 142 } else {
143 right 143 right
@@ -166,12 +166,12 @@ impl<'a> ImportAction<'a> {
166 166
167// Find out the best ImportAction to import target path against current_use_tree. 167// Find out the best ImportAction to import target path against current_use_tree.
168// If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList. 168// If current_use_tree has a nested import the function gets called recursively on every UseTree inside a UseTreeList.
169fn walk_use_tree_for_best_action<'a>( 169fn walk_use_tree_for_best_action(
170 current_path_segments: &mut Vec<&'a ast::PathSegment>, // buffer containing path segments 170 current_path_segments: &mut Vec<ast::PathSegment>, // buffer containing path segments
171 current_parent_use_tree_list: Option<&'a ast::UseTreeList>, // will be Some value if we are in a nested import 171 current_parent_use_tree_list: Option<ast::UseTreeList>, // will be Some value if we are in a nested import
172 current_use_tree: &'a ast::UseTree, // the use tree we are currently examinating 172 current_use_tree: ast::UseTree, // the use tree we are currently examinating
173 target: &[SmolStr], // the path we want to import 173 target: &[SmolStr], // the path we want to import
174) -> ImportAction<'a> { 174) -> ImportAction {
175 // We save the number of segments in the buffer so we can restore the correct segments 175 // We save the number of segments in the buffer so we can restore the correct segments
176 // before returning. Recursive call will add segments so we need to delete them. 176 // before returning. Recursive call will add segments so we need to delete them.
177 let prev_len = current_path_segments.len(); 177 let prev_len = current_path_segments.len();
@@ -188,32 +188,36 @@ fn walk_use_tree_for_best_action<'a>(
188 .syntax() 188 .syntax()
189 .ancestors() 189 .ancestors()
190 .find_map(ast::UseItem::cast) 190 .find_map(ast::UseItem::cast)
191 .map(AstNode::syntax), 191 .map(|it| it.syntax().clone()),
192 true, 192 true,
193 ); 193 );
194 } 194 }
195 }; 195 };
196 196
197 // This can happen only if current_use_tree is a direct child of a UseItem 197 // This can happen only if current_use_tree is a direct child of a UseItem
198 if let Some(name) = alias.and_then(ast::NameOwner::name) { 198 if let Some(name) = alias.and_then(|it| it.name()) {
199 if compare_path_segment_with_name(&target[0], name) { 199 if compare_path_segment_with_name(&target[0], &name) {
200 return ImportAction::Nothing; 200 return ImportAction::Nothing;
201 } 201 }
202 } 202 }
203 203
204 collect_path_segments_raw(current_path_segments, path); 204 collect_path_segments_raw(current_path_segments, path.clone());
205 205
206 // We compare only the new segments added in the line just above. 206 // We compare only the new segments added in the line just above.
207 // The first prev_len segments were already compared in 'parent' recursive calls. 207 // The first prev_len segments were already compared in 'parent' recursive calls.
208 let left = target.split_at(prev_len).1; 208 let left = target.split_at(prev_len).1;
209 let right = current_path_segments.split_at(prev_len).1; 209 let right = current_path_segments.split_at(prev_len).1;
210 let common = compare_path_segments(left, right); 210 let common = compare_path_segments(left, &right);
211 let mut action = match common { 211 let mut action = match common {
212 0 => ImportAction::add_new_use( 212 0 => ImportAction::add_new_use(
213 // e.g: target is std::fmt and we can have 213 // e.g: target is std::fmt and we can have
214 // use foo::bar 214 // use foo::bar
215 // We add a brand new use statement 215 // We add a brand new use statement
216 current_use_tree.syntax().ancestors().find_map(ast::UseItem::cast).map(AstNode::syntax), 216 current_use_tree
217 .syntax()
218 .ancestors()
219 .find_map(ast::UseItem::cast)
220 .map(|it| it.syntax().clone()),
217 true, 221 true,
218 ), 222 ),
219 common if common == left.len() && left.len() == right.len() => { 223 common if common == left.len() && left.len() == right.len() => {
@@ -223,9 +227,9 @@ fn walk_use_tree_for_best_action<'a>(
223 if let Some(list) = tree_list { 227 if let Some(list) = tree_list {
224 // In case 2 we need to add self to the nested list 228 // In case 2 we need to add self to the nested list
225 // unless it's already there 229 // unless it's already there
226 let has_self = list.use_trees().map(ast::UseTree::path).any(|p| { 230 let has_self = list.use_trees().map(|it| it.path()).any(|p| {
227 p.and_then(ast::Path::segment) 231 p.and_then(|it| it.segment())
228 .and_then(ast::PathSegment::kind) 232 .and_then(|it| it.kind())
229 .filter(|k| *k == ast::PathSegmentKind::SelfKw) 233 .filter(|k| *k == ast::PathSegmentKind::SelfKw)
230 .is_some() 234 .is_some()
231 }); 235 });
@@ -248,7 +252,7 @@ fn walk_use_tree_for_best_action<'a>(
248 ImportAction::add_nested_import( 252 ImportAction::add_nested_import(
249 prev_len + common, 253 prev_len + common,
250 path, 254 path,
251 Some(segments_to_split[0]), 255 Some(segments_to_split[0].clone()),
252 false, 256 false,
253 ) 257 )
254 } 258 }
@@ -263,14 +267,18 @@ fn walk_use_tree_for_best_action<'a>(
263 .syntax() 267 .syntax()
264 .ancestors() 268 .ancestors()
265 .find_map(ast::UseItem::cast) 269 .find_map(ast::UseItem::cast)
266 .map(AstNode::syntax), 270 .map(|it| it.syntax().clone()),
267 true, 271 true,
268 ); 272 );
269 if let Some(list) = tree_list { 273 if let Some(list) = tree_list {
270 // Case 2, check recursively if the path is already imported in the nested list 274 // Case 2, check recursively if the path is already imported in the nested list
271 for u in list.use_trees() { 275 for u in list.use_trees() {
272 let child_action = 276 let child_action = walk_use_tree_for_best_action(
273 walk_use_tree_for_best_action(current_path_segments, Some(list), u, target); 277 current_path_segments,
278 Some(list.clone()),
279 u,
280 target,
281 );
274 if child_action.is_better(&better_action) { 282 if child_action.is_better(&better_action) {
275 better_action = child_action; 283 better_action = child_action;
276 if let ImportAction::Nothing = better_action { 284 if let ImportAction::Nothing = better_action {
@@ -291,7 +299,7 @@ fn walk_use_tree_for_best_action<'a>(
291 ImportAction::add_nested_import( 299 ImportAction::add_nested_import(
292 prev_len + common, 300 prev_len + common,
293 path, 301 path,
294 Some(segments_to_split[0]), 302 Some(segments_to_split[0].clone()),
295 true, 303 true,
296 ) 304 )
297 } 305 }
@@ -302,7 +310,7 @@ fn walk_use_tree_for_best_action<'a>(
302 ImportAction::add_nested_import( 310 ImportAction::add_nested_import(
303 prev_len + common, 311 prev_len + common,
304 path, 312 path,
305 Some(segments_to_split[0]), 313 Some(segments_to_split[0].clone()),
306 false, 314 false,
307 ) 315 )
308 } 316 }
@@ -311,7 +319,7 @@ fn walk_use_tree_for_best_action<'a>(
311 319
312 // If we are inside a UseTreeList adding a use statement become adding to the existing 320 // If we are inside a UseTreeList adding a use statement become adding to the existing
313 // tree list. 321 // tree list.
314 action = match (current_parent_use_tree_list, action) { 322 action = match (current_parent_use_tree_list, action.clone()) {
315 (Some(use_tree_list), ImportAction::AddNewUse { .. }) => { 323 (Some(use_tree_list), ImportAction::AddNewUse { .. }) => {
316 ImportAction::add_in_tree_list(prev_len, use_tree_list, false) 324 ImportAction::add_in_tree_list(prev_len, use_tree_list, false)
317 } 325 }
@@ -323,19 +331,20 @@ fn walk_use_tree_for_best_action<'a>(
323 action 331 action
324} 332}
325 333
326fn best_action_for_target<'b, 'a: 'b>( 334fn best_action_for_target(
327 container: &'a SyntaxNode, 335 container: SyntaxNode,
328 anchor: &'a SyntaxNode, 336 anchor: SyntaxNode,
329 target: &'b [SmolStr], 337 target: &[SmolStr],
330) -> ImportAction<'a> { 338) -> ImportAction {
331 let mut storage = Vec::with_capacity(16); // this should be the only allocation 339 let mut storage = Vec::with_capacity(16); // this should be the only allocation
332 let best_action = container 340 let best_action = container
333 .children() 341 .children()
334 .filter_map(ast::UseItem::cast) 342 .filter_map(ast::UseItem::cast)
335 .filter_map(ast::UseItem::use_tree) 343 .filter_map(|it| it.use_tree())
336 .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target)) 344 .map(|u| walk_use_tree_for_best_action(&mut storage, None, u, target))
337 .fold(None, |best, a| { 345 .fold(None, |best, a| match best {
338 best.and_then(|best| Some(*ImportAction::better(&best, &a))).or_else(|| Some(a)) 346 Some(best) => Some(ImportAction::better(best, a)),
347 None => Some(a),
339 }); 348 });
340 349
341 match best_action { 350 match best_action {
@@ -386,7 +395,7 @@ fn make_assist(action: &ImportAction, target: &[SmolStr], edit: &mut TextEditBui
386} 395}
387 396
388fn make_assist_add_new_use( 397fn make_assist_add_new_use(
389 anchor: &Option<&SyntaxNode>, 398 anchor: &Option<SyntaxNode>,
390 after: bool, 399 after: bool,
391 target: &[SmolStr], 400 target: &[SmolStr],
392 edit: &mut TextEditBuilder, 401 edit: &mut TextEditBuilder,
@@ -396,7 +405,7 @@ fn make_assist_add_new_use(
396 let mut buf = String::new(); 405 let mut buf = String::new();
397 if after { 406 if after {
398 buf.push_str("\n"); 407 buf.push_str("\n");
399 if let Some(spaces) = indent { 408 if let Some(spaces) = &indent {
400 buf.push_str(spaces); 409 buf.push_str(spaces);
401 } 410 }
402 } 411 }
@@ -405,8 +414,8 @@ fn make_assist_add_new_use(
405 buf.push_str(";"); 414 buf.push_str(";");
406 if !after { 415 if !after {
407 buf.push_str("\n\n"); 416 buf.push_str("\n\n");
408 if let Some(spaces) = indent { 417 if let Some(spaces) = &indent {
409 buf.push_str(spaces); 418 buf.push_str(&spaces);
410 } 419 }
411 } 420 }
412 let position = if after { anchor.range().end() } else { anchor.range().start() }; 421 let position = if after { anchor.range().end() } else { anchor.range().start() };
@@ -444,7 +453,7 @@ fn make_assist_add_in_tree_list(
444 453
445fn make_assist_add_nested_import( 454fn make_assist_add_nested_import(
446 path: &ast::Path, 455 path: &ast::Path,
447 first_segment_to_split: &Option<&ast::PathSegment>, 456 first_segment_to_split: &Option<ast::PathSegment>,
448 target: &[SmolStr], 457 target: &[SmolStr],
449 add_self: bool, 458 add_self: bool,
450 edit: &mut TextEditBuilder, 459 edit: &mut TextEditBuilder,
@@ -482,7 +491,7 @@ fn apply_auto_import(
482 target: &[SmolStr], 491 target: &[SmolStr],
483 edit: &mut TextEditBuilder, 492 edit: &mut TextEditBuilder,
484) { 493) {
485 let action = best_action_for_target(container, path.syntax(), target); 494 let action = best_action_for_target(container.clone(), path.syntax().clone(), target);
486 make_assist(&action, target, edit); 495 make_assist(&action, target, edit);
487 if let Some(last) = path.segment() { 496 if let Some(last) = path.segment() {
488 // Here we are assuming the assist will provide a correct use statement 497 // Here we are assuming the assist will provide a correct use statement
@@ -522,26 +531,26 @@ pub fn auto_import_text_edit(
522 edit: &mut TextEditBuilder, 531 edit: &mut TextEditBuilder,
523) { 532) {
524 let container = position.ancestors().find_map(|n| { 533 let container = position.ancestors().find_map(|n| {
525 if let Some(module) = ast::Module::cast(n) { 534 if let Some(module) = ast::Module::cast(n.clone()) {
526 return module.item_list().map(ast::AstNode::syntax); 535 return module.item_list().map(|it| it.syntax().clone());
527 } 536 }
528 ast::SourceFile::cast(n).map(ast::AstNode::syntax) 537 ast::SourceFile::cast(n).map(|it| it.syntax().clone())
529 }); 538 });
530 539
531 if let Some(container) = container { 540 if let Some(container) = container {
532 let action = best_action_for_target(container, anchor, target); 541 let action = best_action_for_target(container, anchor.clone(), target);
533 make_assist(&action, target, edit); 542 make_assist(&action, target, edit);
534 } 543 }
535} 544}
536 545
537pub(crate) fn auto_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 546pub(crate) fn auto_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
538 let path: &ast::Path = ctx.node_at_offset()?; 547 let path: ast::Path = ctx.node_at_offset()?;
539 // We don't want to mess with use statements 548 // We don't want to mess with use statements
540 if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() { 549 if path.syntax().ancestors().find_map(ast::UseItem::cast).is_some() {
541 return None; 550 return None;
542 } 551 }
543 552
544 let hir_path = hir::Path::from_ast(path)?; 553 let hir_path = hir::Path::from_ast(path.clone())?;
545 let segments = collect_hir_path_segments(&hir_path); 554 let segments = collect_hir_path_segments(&hir_path);
546 if segments.len() < 2 { 555 if segments.len() < 2 {
547 return None; 556 return None;
@@ -554,7 +563,7 @@ pub(crate) fn auto_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist
554 format!("import {} in mod {}", fmt_segments(&segments), name.text()), 563 format!("import {} in mod {}", fmt_segments(&segments), name.text()),
555 |edit| { 564 |edit| {
556 let mut text_edit = TextEditBuilder::default(); 565 let mut text_edit = TextEditBuilder::default();
557 apply_auto_import(item_list.syntax(), path, &segments, &mut text_edit); 566 apply_auto_import(item_list.syntax(), &path, &segments, &mut text_edit);
558 edit.set_edit_builder(text_edit); 567 edit.set_edit_builder(text_edit);
559 }, 568 },
560 ); 569 );
@@ -566,7 +575,7 @@ pub(crate) fn auto_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist
566 format!("import {} in the current file", fmt_segments(&segments)), 575 format!("import {} in the current file", fmt_segments(&segments)),
567 |edit| { 576 |edit| {
568 let mut text_edit = TextEditBuilder::default(); 577 let mut text_edit = TextEditBuilder::default();
569 apply_auto_import(current_file.syntax(), path, &segments, &mut text_edit); 578 apply_auto_import(current_file.syntax(), &path, &segments, &mut text_edit);
570 edit.set_edit_builder(text_edit); 579 edit.set_edit_builder(text_edit);
571 }, 580 },
572 ); 581 );
diff --git a/crates/ra_assists/src/change_visibility.rs b/crates/ra_assists/src/change_visibility.rs
index 6cabba3e3..ab10d2aa4 100644
--- a/crates/ra_assists/src/change_visibility.rs
+++ b/crates/ra_assists/src/change_visibility.rs
@@ -35,7 +35,7 @@ fn add_vis(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
35 if parent.children().any(|child| child.kind() == VISIBILITY) { 35 if parent.children().any(|child| child.kind() == VISIBILITY) {
36 return None; 36 return None;
37 } 37 }
38 (vis_offset(parent), keyword.range()) 38 (vis_offset(&parent), keyword.range())
39 } else { 39 } else {
40 let ident = ctx.token_at_offset().find(|leaf| leaf.kind() == IDENT)?; 40 let ident = ctx.token_at_offset().find(|leaf| leaf.kind() == IDENT)?;
41 let field = ident.parent().ancestors().find_map(ast::NamedFieldDef::cast)?; 41 let field = ident.parent().ancestors().find_map(ast::NamedFieldDef::cast)?;
@@ -65,7 +65,7 @@ fn vis_offset(node: &SyntaxNode) -> TextUnit {
65 .unwrap_or_else(|| node.range().start()) 65 .unwrap_or_else(|| node.range().start())
66} 66}
67 67
68fn change_vis(mut ctx: AssistCtx<impl HirDatabase>, vis: &ast::Visibility) -> Option<Assist> { 68fn change_vis(mut ctx: AssistCtx<impl HirDatabase>, vis: ast::Visibility) -> Option<Assist> {
69 if vis.syntax().text() == "pub" { 69 if vis.syntax().text() == "pub" {
70 ctx.add_action(AssistId("change_visibility"), "change to pub(crate)", |edit| { 70 ctx.add_action(AssistId("change_visibility"), "change to pub(crate)", |edit| {
71 edit.target(vis.syntax().range()); 71 edit.target(vis.syntax().range());
diff --git a/crates/ra_assists/src/fill_match_arms.rs b/crates/ra_assists/src/fill_match_arms.rs
index deef166b5..b96806ac6 100644
--- a/crates/ra_assists/src/fill_match_arms.rs
+++ b/crates/ra_assists/src/fill_match_arms.rs
@@ -27,7 +27,7 @@ pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
27 let mut arm_iter = arm_list.arms(); 27 let mut arm_iter = arm_list.arms();
28 let first = arm_iter.next(); 28 let first = arm_iter.next();
29 29
30 match first { 30 match &first {
31 // If there arm list is empty or there is only one trivial arm, then proceed. 31 // If there arm list is empty or there is only one trivial arm, then proceed.
32 Some(arm) if is_trivial_arm(arm) => { 32 Some(arm) if is_trivial_arm(arm) => {
33 if arm_iter.next() != None { 33 if arm_iter.next() != None {
@@ -44,7 +44,7 @@ pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
44 44
45 let expr = match_expr.expr()?; 45 let expr = match_expr.expr()?;
46 let analyzer = hir::SourceAnalyzer::new(ctx.db, ctx.frange.file_id, expr.syntax(), None); 46 let analyzer = hir::SourceAnalyzer::new(ctx.db, ctx.frange.file_id, expr.syntax(), None);
47 let match_expr_ty = analyzer.type_of(ctx.db, expr)?; 47 let match_expr_ty = analyzer.type_of(ctx.db, &expr)?;
48 let enum_def = analyzer.autoderef(ctx.db, match_expr_ty).find_map(|ty| match ty.as_adt() { 48 let enum_def = analyzer.autoderef(ctx.db, match_expr_ty).find_map(|ty| match ty.as_adt() {
49 Some((AdtDef::Enum(e), _)) => Some(e), 49 Some((AdtDef::Enum(e), _)) => Some(e),
50 _ => None, 50 _ => None,
diff --git a/crates/ra_assists/src/flip_binexpr.rs b/crates/ra_assists/src/flip_binexpr.rs
index 5e41f9346..2e591ad3b 100644
--- a/crates/ra_assists/src/flip_binexpr.rs
+++ b/crates/ra_assists/src/flip_binexpr.rs
@@ -6,8 +6,8 @@ use crate::{Assist, AssistCtx, AssistId};
6/// Flip binary expression assist. 6/// Flip binary expression assist.
7pub(crate) fn flip_binexpr(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 7pub(crate) fn flip_binexpr(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
8 let expr = ctx.node_at_offset::<BinExpr>()?; 8 let expr = ctx.node_at_offset::<BinExpr>()?;
9 let lhs = expr.lhs()?.syntax(); 9 let lhs = expr.lhs()?.syntax().clone();
10 let rhs = expr.rhs()?.syntax(); 10 let rhs = expr.rhs()?.syntax().clone();
11 let op_range = expr.op_token()?.range(); 11 let op_range = expr.op_token()?.range();
12 // The assist should be applied only if the cursor is on the operator 12 // The assist should be applied only if the cursor is on the operator
13 let cursor_in_range = ctx.frange.range.is_subrange(&op_range); 13 let cursor_in_range = ctx.frange.range.is_subrange(&op_range);
diff --git a/crates/ra_assists/src/flip_comma.rs b/crates/ra_assists/src/flip_comma.rs
index d8dba779f..13016ae06 100644
--- a/crates/ra_assists/src/flip_comma.rs
+++ b/crates/ra_assists/src/flip_comma.rs
@@ -5,8 +5,8 @@ use crate::{Assist, AssistCtx, AssistId};
5 5
6pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 6pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
7 let comma = ctx.token_at_offset().find(|leaf| leaf.kind() == T![,])?; 7 let comma = ctx.token_at_offset().find(|leaf| leaf.kind() == T![,])?;
8 let prev = non_trivia_sibling(comma.into(), Direction::Prev)?; 8 let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?;
9 let next = non_trivia_sibling(comma.into(), Direction::Next)?; 9 let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?;
10 ctx.add_action(AssistId("flip_comma"), "flip comma", |edit| { 10 ctx.add_action(AssistId("flip_comma"), "flip comma", |edit| {
11 edit.target(comma.range()); 11 edit.target(comma.range());
12 edit.replace(prev.range(), next.to_string()); 12 edit.replace(prev.range(), next.to_string());
diff --git a/crates/ra_assists/src/inline_local_variable.rs b/crates/ra_assists/src/inline_local_variable.rs
index 554de8b46..3c17089de 100644
--- a/crates/ra_assists/src/inline_local_variable.rs
+++ b/crates/ra_assists/src/inline_local_variable.rs
@@ -16,18 +16,18 @@ pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Opt
16 if bind_pat.is_mutable() { 16 if bind_pat.is_mutable() {
17 return None; 17 return None;
18 } 18 }
19 let initializer_expr = let_stmt.initializer(); 19 let initializer_expr = let_stmt.initializer()?;
20 let delete_range = if let Some(whitespace) = let_stmt 20 let delete_range = if let Some(whitespace) = let_stmt
21 .syntax() 21 .syntax()
22 .next_sibling_or_token() 22 .next_sibling_or_token()
23 .and_then(|it| ast::Whitespace::cast(it.as_token()?)) 23 .and_then(|it| ast::Whitespace::cast(it.as_token()?.clone()))
24 { 24 {
25 TextRange::from_to(let_stmt.syntax().range().start(), whitespace.syntax().range().end()) 25 TextRange::from_to(let_stmt.syntax().range().start(), whitespace.syntax().range().end())
26 } else { 26 } else {
27 let_stmt.syntax().range() 27 let_stmt.syntax().range()
28 }; 28 };
29 let analyzer = hir::SourceAnalyzer::new(ctx.db, ctx.frange.file_id, bind_pat.syntax(), None); 29 let analyzer = hir::SourceAnalyzer::new(ctx.db, ctx.frange.file_id, bind_pat.syntax(), None);
30 let refs = analyzer.find_all_refs(bind_pat); 30 let refs = analyzer.find_all_refs(&bind_pat);
31 31
32 let mut wrap_in_parens = vec![true; refs.len()]; 32 let mut wrap_in_parens = vec![true; refs.len()];
33 33
@@ -45,7 +45,7 @@ pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Opt
45 } 45 }
46 }; 46 };
47 47
48 wrap_in_parens[i] = match (initializer_expr?.kind(), usage_parent.kind()) { 48 wrap_in_parens[i] = match (initializer_expr.kind(), usage_parent.kind()) {
49 (ExprKind::CallExpr(_), _) 49 (ExprKind::CallExpr(_), _)
50 | (ExprKind::IndexExpr(_), _) 50 | (ExprKind::IndexExpr(_), _)
51 | (ExprKind::MethodCallExpr(_), _) 51 | (ExprKind::MethodCallExpr(_), _)
@@ -71,7 +71,7 @@ pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Opt
71 }; 71 };
72 } 72 }
73 73
74 let init_str = initializer_expr?.syntax().text().to_string(); 74 let init_str = initializer_expr.syntax().text().to_string();
75 let init_in_paren = format!("({})", &init_str); 75 let init_in_paren = format!("({})", &init_str);
76 76
77 ctx.add_action( 77 ctx.add_action(
diff --git a/crates/ra_assists/src/introduce_variable.rs b/crates/ra_assists/src/introduce_variable.rs
index f7f5ccafa..ce28132c9 100644
--- a/crates/ra_assists/src/introduce_variable.rs
+++ b/crates/ra_assists/src/introduce_variable.rs
@@ -20,8 +20,8 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
20 return None; 20 return None;
21 } 21 }
22 let expr = node.ancestors().find_map(valid_target_expr)?; 22 let expr = node.ancestors().find_map(valid_target_expr)?;
23 let (anchor_stmt, wrap_in_block) = anchor_stmt(expr)?; 23 let (anchor_stmt, wrap_in_block) = anchor_stmt(expr.clone())?;
24 let indent = anchor_stmt.prev_sibling_or_token()?.as_token()?; 24 let indent = anchor_stmt.prev_sibling_or_token()?.as_token()?.clone();
25 if indent.kind() != WHITESPACE { 25 if indent.kind() != WHITESPACE {
26 return None; 26 return None;
27 } 27 }
@@ -37,9 +37,9 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
37 }; 37 };
38 38
39 expr.syntax().text().push_to(&mut buf); 39 expr.syntax().text().push_to(&mut buf);
40 let full_stmt = ast::ExprStmt::cast(anchor_stmt); 40 let full_stmt = ast::ExprStmt::cast(anchor_stmt.clone());
41 let is_full_stmt = if let Some(expr_stmt) = full_stmt { 41 let is_full_stmt = if let Some(expr_stmt) = &full_stmt {
42 Some(expr.syntax()) == expr_stmt.expr().map(|e| e.syntax()) 42 Some(expr.syntax().clone()) == expr_stmt.expr().map(|e| e.syntax().clone())
43 } else { 43 } else {
44 false 44 false
45 }; 45 };
@@ -81,7 +81,7 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
81 81
82/// Check whether the node is a valid expression which can be extracted to a variable. 82/// Check whether the node is a valid expression which can be extracted to a variable.
83/// In general that's true for any expression, but in some cases that would produce invalid code. 83/// In general that's true for any expression, but in some cases that would produce invalid code.
84fn valid_target_expr(node: &SyntaxNode) -> Option<&ast::Expr> { 84fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
85 match node.kind() { 85 match node.kind() {
86 PATH_EXPR => None, 86 PATH_EXPR => None,
87 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()), 87 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
@@ -96,14 +96,10 @@ fn valid_target_expr(node: &SyntaxNode) -> Option<&ast::Expr> {
96/// to produce correct code. 96/// to produce correct code.
97/// It can be a statement, the last in a block expression or a wanna be block 97/// It can be a statement, the last in a block expression or a wanna be block
98/// expression like a lambda or match arm. 98/// expression like a lambda or match arm.
99fn anchor_stmt(expr: &ast::Expr) -> Option<(&SyntaxNode, bool)> { 99fn anchor_stmt(expr: ast::Expr) -> Option<(SyntaxNode, bool)> {
100 expr.syntax().ancestors().find_map(|node| { 100 expr.syntax().ancestors().find_map(|node| {
101 if ast::Stmt::cast(node).is_some() {
102 return Some((node, false));
103 }
104
105 if let Some(expr) = node.parent().and_then(ast::Block::cast).and_then(|it| it.expr()) { 101 if let Some(expr) = node.parent().and_then(ast::Block::cast).and_then(|it| it.expr()) {
106 if expr.syntax() == node { 102 if expr.syntax() == &node {
107 tested_by!(test_introduce_var_last_expr); 103 tested_by!(test_introduce_var_last_expr);
108 return Some((node, false)); 104 return Some((node, false));
109 } 105 }
@@ -115,6 +111,10 @@ fn anchor_stmt(expr: &ast::Expr) -> Option<(&SyntaxNode, bool)> {
115 } 111 }
116 } 112 }
117 113
114 if ast::Stmt::cast(node.clone()).is_some() {
115 return Some((node, false));
116 }
117
118 None 118 None
119 }) 119 })
120} 120}
diff --git a/crates/ra_assists/src/move_guard.rs b/crates/ra_assists/src/move_guard.rs
index e1ce86a33..313c9ad18 100644
--- a/crates/ra_assists/src/move_guard.rs
+++ b/crates/ra_assists/src/move_guard.rs
@@ -18,9 +18,9 @@ pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Op
18 18
19 ctx.add_action(AssistId("move_guard_to_arm_body"), "move guard to arm body", |edit| { 19 ctx.add_action(AssistId("move_guard_to_arm_body"), "move guard to arm body", |edit| {
20 edit.target(guard.syntax().range()); 20 edit.target(guard.syntax().range());
21 let offseting_amount = match space_before_guard { 21 let offseting_amount = match &space_before_guard {
22 Some(SyntaxElement::Token(tok)) => { 22 Some(SyntaxElement::Token(tok)) => {
23 if let Some(_) = ast::Whitespace::cast(tok) { 23 if let Some(_) = ast::Whitespace::cast(tok.clone()) {
24 let ele = space_before_guard.unwrap().range(); 24 let ele = space_before_guard.unwrap().range();
25 edit.delete(ele); 25 edit.delete(ele);
26 ele.len() 26 ele.len()
@@ -39,11 +39,11 @@ pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Op
39} 39}
40 40
41pub(crate) fn move_arm_cond_to_match_guard(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 41pub(crate) fn move_arm_cond_to_match_guard(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
42 let match_arm: &MatchArm = ctx.node_at_offset::<MatchArm>()?; 42 let match_arm: MatchArm = ctx.node_at_offset::<MatchArm>()?;
43 let last_match_pat = match_arm.pats().last()?; 43 let last_match_pat = match_arm.pats().last()?;
44 44
45 let arm_body = match_arm.expr()?; 45 let arm_body = match_arm.expr()?;
46 let if_expr: &IfExpr = IfExpr::cast(arm_body.syntax())?; 46 let if_expr: IfExpr = IfExpr::cast(arm_body.syntax().clone())?;
47 let cond = if_expr.condition()?; 47 let cond = if_expr.condition()?;
48 let then_block = if_expr.then_branch()?; 48 let then_block = if_expr.then_branch()?;
49 49
@@ -65,7 +65,7 @@ pub(crate) fn move_arm_cond_to_match_guard(mut ctx: AssistCtx<impl HirDatabase>)
65 edit.target(if_expr.syntax().range()); 65 edit.target(if_expr.syntax().range());
66 let then_only_expr = then_block.statements().next().is_none(); 66 let then_only_expr = then_block.statements().next().is_none();
67 67
68 match then_block.expr() { 68 match &then_block.expr() {
69 Some(then_expr) if then_only_expr => { 69 Some(then_expr) if then_only_expr => {
70 edit.replace(if_expr.syntax().range(), then_expr.syntax().text()) 70 edit.replace(if_expr.syntax().range(), then_expr.syntax().text())
71 } 71 }
diff --git a/crates/ra_assists/src/remove_dbg.rs b/crates/ra_assists/src/remove_dbg.rs
index 5680f76ca..c330bc827 100644
--- a/crates/ra_assists/src/remove_dbg.rs
+++ b/crates/ra_assists/src/remove_dbg.rs
@@ -8,7 +8,7 @@ use ra_syntax::{
8pub(crate) fn remove_dbg(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 8pub(crate) fn remove_dbg(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
9 let macro_call = ctx.node_at_offset::<ast::MacroCall>()?; 9 let macro_call = ctx.node_at_offset::<ast::MacroCall>()?;
10 10
11 if !is_valid_macrocall(macro_call, "dbg")? { 11 if !is_valid_macrocall(&macro_call, "dbg")? {
12 return None; 12 return None;
13 } 13 }
14 14
@@ -35,7 +35,7 @@ pub(crate) fn remove_dbg(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
35 }; 35 };
36 36
37 let macro_content = { 37 let macro_content = {
38 let macro_args = macro_call.token_tree()?.syntax(); 38 let macro_args = macro_call.token_tree()?.syntax().clone();
39 let range = macro_args.range(); 39 let range = macro_args.range();
40 let start = range.start() + TextUnit::of_char('('); 40 let start = range.start() + TextUnit::of_char('(');
41 let end = range.end() - TextUnit::of_char(')'); 41 let end = range.end() - TextUnit::of_char(')');
@@ -65,7 +65,7 @@ fn is_valid_macrocall(macro_call: &ast::MacroCall, macro_name: &str) -> Option<b
65 return None; 65 return None;
66 } 66 }
67 67
68 let node = macro_call.token_tree()?.syntax(); 68 let node = macro_call.token_tree()?.syntax().clone();
69 let first_child = node.first_child_or_token()?; 69 let first_child = node.first_child_or_token()?;
70 let last_child = node.last_child_or_token()?; 70 let last_child = node.last_child_or_token()?;
71 71
diff --git a/crates/ra_assists/src/replace_if_let_with_match.rs b/crates/ra_assists/src/replace_if_let_with_match.rs
index c2c7cf70b..5de6aa266 100644
--- a/crates/ra_assists/src/replace_if_let_with_match.rs
+++ b/crates/ra_assists/src/replace_if_let_with_match.rs
@@ -5,7 +5,7 @@ use ra_syntax::{ast, AstNode};
5use crate::{Assist, AssistCtx, AssistId}; 5use crate::{Assist, AssistCtx, AssistId};
6 6
7pub(crate) fn replace_if_let_with_match(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { 7pub(crate) fn replace_if_let_with_match(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
8 let if_expr: &ast::IfExpr = ctx.node_at_offset()?; 8 let if_expr: ast::IfExpr = ctx.node_at_offset()?;
9 let cond = if_expr.condition()?; 9 let cond = if_expr.condition()?;
10 let pat = cond.pat()?; 10 let pat = cond.pat()?;
11 let expr = cond.expr()?; 11 let expr = cond.expr()?;
@@ -25,16 +25,11 @@ pub(crate) fn replace_if_let_with_match(mut ctx: AssistCtx<impl HirDatabase>) ->
25 ctx.build() 25 ctx.build()
26} 26}
27 27
28fn build_match_expr( 28fn build_match_expr(expr: ast::Expr, pat1: ast::Pat, arm1: ast::Block, arm2: ast::Block) -> String {
29 expr: &ast::Expr,
30 pat1: &ast::Pat,
31 arm1: &ast::Block,
32 arm2: &ast::Block,
33) -> String {
34 let mut buf = String::new(); 29 let mut buf = String::new();
35 buf.push_str(&format!("match {} {{\n", expr.syntax().text())); 30 buf.push_str(&format!("match {} {{\n", expr.syntax().text()));
36 buf.push_str(&format!(" {} => {}\n", pat1.syntax().text(), format_arm(arm1))); 31 buf.push_str(&format!(" {} => {}\n", pat1.syntax().text(), format_arm(&arm1)));
37 buf.push_str(&format!(" _ => {}\n", format_arm(arm2))); 32 buf.push_str(&format!(" _ => {}\n", format_arm(&arm2)));
38 buf.push_str("}"); 33 buf.push_str("}");
39 buf 34 buf
40} 35}
diff --git a/crates/ra_cli/src/main.rs b/crates/ra_cli/src/main.rs
index b063193cf..375e2f508 100644
--- a/crates/ra_cli/src/main.rs
+++ b/crates/ra_cli/src/main.rs
@@ -7,7 +7,7 @@ use clap::{App, Arg, SubCommand};
7use flexi_logger::Logger; 7use flexi_logger::Logger;
8use ra_ide_api::{file_structure, Analysis}; 8use ra_ide_api::{file_structure, Analysis};
9use ra_prof::profile; 9use ra_prof::profile;
10use ra_syntax::{AstNode, SourceFile, TreeArc}; 10use ra_syntax::{AstNode, SourceFile};
11 11
12type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>; 12type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
13 13
@@ -100,9 +100,9 @@ fn main() -> Result<()> {
100 Ok(()) 100 Ok(())
101} 101}
102 102
103fn file() -> Result<TreeArc<SourceFile>> { 103fn file() -> Result<SourceFile> {
104 let text = read_stdin()?; 104 let text = read_stdin()?;
105 Ok(SourceFile::parse(&text).tree().to_owned()) 105 Ok(SourceFile::parse(&text).tree())
106} 106}
107 107
108fn read_stdin() -> Result<String> { 108fn read_stdin() -> Result<String> {
diff --git a/crates/ra_fmt/src/lib.rs b/crates/ra_fmt/src/lib.rs
index 1c2c04ad2..d6e895729 100644
--- a/crates/ra_fmt/src/lib.rs
+++ b/crates/ra_fmt/src/lib.rs
@@ -3,7 +3,7 @@
3use itertools::Itertools; 3use itertools::Itertools;
4use ra_syntax::{ 4use ra_syntax::{
5 ast::{self, AstNode, AstToken}, 5 ast::{self, AstNode, AstToken},
6 SyntaxKind, 6 SmolStr, SyntaxKind,
7 SyntaxKind::*, 7 SyntaxKind::*,
8 SyntaxNode, SyntaxToken, T, 8 SyntaxNode, SyntaxToken, T,
9}; 9};
@@ -15,12 +15,12 @@ pub fn reindent(text: &str, indent: &str) -> String {
15} 15}
16 16
17/// If the node is on the beginning of the line, calculate indent. 17/// If the node is on the beginning of the line, calculate indent.
18pub fn leading_indent(node: &SyntaxNode) -> Option<&str> { 18pub fn leading_indent(node: &SyntaxNode) -> Option<SmolStr> {
19 for token in prev_tokens(node.first_token()?) { 19 for token in prev_tokens(node.first_token()?) {
20 if let Some(ws) = ast::Whitespace::cast(token) { 20 if let Some(ws) = ast::Whitespace::cast(token.clone()) {
21 let ws_text = ws.text(); 21 let ws_text = ws.text();
22 if let Some(pos) = ws_text.rfind('\n') { 22 if let Some(pos) = ws_text.rfind('\n') {
23 return Some(&ws_text[pos + 1..]); 23 return Some(ws_text[pos + 1..].into());
24 } 24 }
25 } 25 }
26 if token.text().contains('\n') { 26 if token.text().contains('\n') {
@@ -31,17 +31,17 @@ pub fn leading_indent(node: &SyntaxNode) -> Option<&str> {
31} 31}
32 32
33fn prev_tokens(token: SyntaxToken) -> impl Iterator<Item = SyntaxToken> { 33fn prev_tokens(token: SyntaxToken) -> impl Iterator<Item = SyntaxToken> {
34 successors(token.prev_token(), |&token| token.prev_token()) 34 successors(token.prev_token(), |token| token.prev_token())
35} 35}
36 36
37pub fn extract_trivial_expression(block: &ast::Block) -> Option<&ast::Expr> { 37pub fn extract_trivial_expression(block: &ast::Block) -> Option<ast::Expr> {
38 let expr = block.expr()?; 38 let expr = block.expr()?;
39 if expr.syntax().text().contains('\n') { 39 if expr.syntax().text().contains('\n') {
40 return None; 40 return None;
41 } 41 }
42 let non_trivial_children = block.syntax().children().filter(|it| match it.kind() { 42 let non_trivial_children = block.syntax().children().filter(|it| match it.kind() {
43 WHITESPACE | T!['{'] | T!['}'] => false, 43 WHITESPACE | T!['{'] | T!['}'] => false,
44 _ => it != &expr.syntax(), 44 _ => it != expr.syntax(),
45 }); 45 });
46 if non_trivial_children.count() > 0 { 46 if non_trivial_children.count() > 0 {
47 return None; 47 return None;
diff --git a/crates/ra_hir/src/adt.rs b/crates/ra_hir/src/adt.rs
index 8afdac801..c65446df4 100644
--- a/crates/ra_hir/src/adt.rs
+++ b/crates/ra_hir/src/adt.rs
@@ -4,10 +4,7 @@
4use std::sync::Arc; 4use std::sync::Arc;
5 5
6use ra_arena::{impl_arena_id, Arena, RawId}; 6use ra_arena::{impl_arena_id, Arena, RawId};
7use ra_syntax::{ 7use ra_syntax::ast::{self, NameOwner, StructKind, TypeAscriptionOwner};
8 ast::{self, NameOwner, StructKind, TypeAscriptionOwner},
9 TreeArc,
10};
11 8
12use crate::{ 9use crate::{
13 type_ref::TypeRef, AsName, AstDatabase, Crate, DefDatabase, Enum, EnumVariant, FieldSource, 10 type_ref::TypeRef, AsName, AstDatabase, Crate, DefDatabase, Enum, EnumVariant, FieldSource,
@@ -59,11 +56,11 @@ impl StructData {
59 struct_: Struct, 56 struct_: Struct,
60 ) -> Arc<StructData> { 57 ) -> Arc<StructData> {
61 let src = struct_.source(db); 58 let src = struct_.source(db);
62 Arc::new(StructData::new(&*src.ast)) 59 Arc::new(StructData::new(&src.ast))
63 } 60 }
64} 61}
65 62
66fn variants(enum_def: &ast::EnumDef) -> impl Iterator<Item = &ast::EnumVariant> { 63fn variants(enum_def: &ast::EnumDef) -> impl Iterator<Item = ast::EnumVariant> {
67 enum_def.variant_list().into_iter().flat_map(|it| it.variants()) 64 enum_def.variant_list().into_iter().flat_map(|it| it.variants())
68} 65}
69 66
@@ -71,9 +68,9 @@ impl EnumVariant {
71 pub(crate) fn source_impl( 68 pub(crate) fn source_impl(
72 self, 69 self,
73 db: &(impl DefDatabase + AstDatabase), 70 db: &(impl DefDatabase + AstDatabase),
74 ) -> Source<TreeArc<ast::EnumVariant>> { 71 ) -> Source<ast::EnumVariant> {
75 let src = self.parent.source(db); 72 let src = self.parent.source(db);
76 let ast = variants(&*src.ast) 73 let ast = variants(&src.ast)
77 .zip(db.enum_data(self.parent).variants.iter()) 74 .zip(db.enum_data(self.parent).variants.iter())
78 .find(|(_syntax, (id, _))| *id == self.id) 75 .find(|(_syntax, (id, _))| *id == self.id)
79 .unwrap() 76 .unwrap()
@@ -96,7 +93,7 @@ impl EnumData {
96 pub(crate) fn enum_data_query(db: &(impl DefDatabase + AstDatabase), e: Enum) -> Arc<EnumData> { 93 pub(crate) fn enum_data_query(db: &(impl DefDatabase + AstDatabase), e: Enum) -> Arc<EnumData> {
97 let src = e.source(db); 94 let src = e.source(db);
98 let name = src.ast.name().map(|n| n.as_name()); 95 let name = src.ast.name().map(|n| n.as_name());
99 let variants = variants(&*src.ast) 96 let variants = variants(&src.ast)
100 .map(|var| EnumVariantData { 97 .map(|var| EnumVariantData {
101 name: var.name().map(|it| it.as_name()), 98 name: var.name().map(|it| it.as_name()),
102 variant_data: Arc::new(VariantData::new(var.kind())), 99 variant_data: Arc::new(VariantData::new(var.kind())),
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index 4fb5844f4..779764590 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -4,10 +4,7 @@ pub(crate) mod docs;
4use std::sync::Arc; 4use std::sync::Arc;
5 5
6use ra_db::{CrateId, Edition, FileId, SourceRootId}; 6use ra_db::{CrateId, Edition, FileId, SourceRootId};
7use ra_syntax::{ 7use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner};
8 ast::{self, NameOwner, TypeAscriptionOwner},
9 TreeArc,
10};
11 8
12use crate::{ 9use crate::{
13 adt::{EnumVariantId, StructFieldId, VariantDef}, 10 adt::{EnumVariantId, StructFieldId, VariantDef},
@@ -155,8 +152,8 @@ impl_froms!(
155); 152);
156 153
157pub enum ModuleSource { 154pub enum ModuleSource {
158 SourceFile(TreeArc<ast::SourceFile>), 155 SourceFile(ast::SourceFile),
159 Module(TreeArc<ast::Module>), 156 Module(ast::Module),
160} 157}
161 158
162impl ModuleSource { 159impl ModuleSource {
@@ -199,7 +196,7 @@ impl Module {
199 self, 196 self,
200 db: &impl HirDatabase, 197 db: &impl HirDatabase,
201 import: ImportId, 198 import: ImportId,
202 ) -> Either<TreeArc<ast::UseTree>, TreeArc<ast::ExternCrateItem>> { 199 ) -> Either<ast::UseTree, ast::ExternCrateItem> {
203 let src = self.definition_source(db); 200 let src = self.definition_source(db);
204 let (_, source_map) = db.raw_items_with_source_map(src.file_id); 201 let (_, source_map) = db.raw_items_with_source_map(src.file_id);
205 source_map.get(&src.ast, import) 202 source_map.get(&src.ast, import)
@@ -321,8 +318,8 @@ pub struct StructField {
321 318
322#[derive(Debug)] 319#[derive(Debug)]
323pub enum FieldSource { 320pub enum FieldSource {
324 Named(TreeArc<ast::NamedFieldDef>), 321 Named(ast::NamedFieldDef),
325 Pos(TreeArc<ast::PosFieldDef>), 322 Pos(ast::PosFieldDef),
326} 323}
327 324
328impl StructField { 325impl StructField {
@@ -736,7 +733,7 @@ impl ConstData {
736 konst: Const, 733 konst: Const,
737 ) -> Arc<ConstData> { 734 ) -> Arc<ConstData> {
738 let node = konst.source(db).ast; 735 let node = konst.source(db).ast;
739 const_data_for(&*node) 736 const_data_for(&node)
740 } 737 }
741 738
742 pub(crate) fn static_data_query( 739 pub(crate) fn static_data_query(
@@ -744,7 +741,7 @@ impl ConstData {
744 konst: Static, 741 konst: Static,
745 ) -> Arc<ConstData> { 742 ) -> Arc<ConstData> {
746 let node = konst.source(db).ast; 743 let node = konst.source(db).ast;
747 const_data_for(&*node) 744 const_data_for(&node)
748 } 745 }
749} 746}
750 747
diff --git a/crates/ra_hir/src/code_model/docs.rs b/crates/ra_hir/src/code_model/docs.rs
index 007ef315d..a2b4d8e97 100644
--- a/crates/ra_hir/src/code_model/docs.rs
+++ b/crates/ra_hir/src/code_model/docs.rs
@@ -71,21 +71,21 @@ pub(crate) fn documentation_query(
71 def: DocDef, 71 def: DocDef,
72) -> Option<Documentation> { 72) -> Option<Documentation> {
73 match def { 73 match def {
74 DocDef::Module(it) => docs_from_ast(&*it.declaration_source(db)?.ast), 74 DocDef::Module(it) => docs_from_ast(&it.declaration_source(db)?.ast),
75 DocDef::StructField(it) => match it.source(db).ast { 75 DocDef::StructField(it) => match it.source(db).ast {
76 FieldSource::Named(named) => docs_from_ast(&*named), 76 FieldSource::Named(named) => docs_from_ast(&named),
77 FieldSource::Pos(..) => None, 77 FieldSource::Pos(..) => None,
78 }, 78 },
79 DocDef::Struct(it) => docs_from_ast(&*it.source(db).ast), 79 DocDef::Struct(it) => docs_from_ast(&it.source(db).ast),
80 DocDef::Enum(it) => docs_from_ast(&*it.source(db).ast), 80 DocDef::Enum(it) => docs_from_ast(&it.source(db).ast),
81 DocDef::EnumVariant(it) => docs_from_ast(&*it.source(db).ast), 81 DocDef::EnumVariant(it) => docs_from_ast(&it.source(db).ast),
82 DocDef::Static(it) => docs_from_ast(&*it.source(db).ast), 82 DocDef::Static(it) => docs_from_ast(&it.source(db).ast),
83 DocDef::Const(it) => docs_from_ast(&*it.source(db).ast), 83 DocDef::Const(it) => docs_from_ast(&it.source(db).ast),
84 DocDef::Function(it) => docs_from_ast(&*it.source(db).ast), 84 DocDef::Function(it) => docs_from_ast(&it.source(db).ast),
85 DocDef::Union(it) => docs_from_ast(&*it.source(db).ast), 85 DocDef::Union(it) => docs_from_ast(&it.source(db).ast),
86 DocDef::Trait(it) => docs_from_ast(&*it.source(db).ast), 86 DocDef::Trait(it) => docs_from_ast(&it.source(db).ast),
87 DocDef::TypeAlias(it) => docs_from_ast(&*it.source(db).ast), 87 DocDef::TypeAlias(it) => docs_from_ast(&it.source(db).ast),
88 DocDef::MacroDef(it) => docs_from_ast(&*it.source(db).ast), 88 DocDef::MacroDef(it) => docs_from_ast(&it.source(db).ast),
89 } 89 }
90} 90}
91 91
diff --git a/crates/ra_hir/src/code_model/src.rs b/crates/ra_hir/src/code_model/src.rs
index 72451e0e7..32bd9c661 100644
--- a/crates/ra_hir/src/code_model/src.rs
+++ b/crates/ra_hir/src/code_model/src.rs
@@ -1,4 +1,4 @@
1use ra_syntax::{ast, TreeArc}; 1use ra_syntax::ast;
2 2
3use crate::{ 3use crate::{
4 ids::AstItemDef, AstDatabase, Const, DefDatabase, Enum, EnumVariant, FieldSource, Function, 4 ids::AstItemDef, AstDatabase, Const, DefDatabase, Enum, EnumVariant, FieldSource, Function,
@@ -34,7 +34,7 @@ impl Module {
34 pub fn declaration_source( 34 pub fn declaration_source(
35 self, 35 self,
36 db: &(impl DefDatabase + AstDatabase), 36 db: &(impl DefDatabase + AstDatabase),
37 ) -> Option<Source<TreeArc<ast::Module>>> { 37 ) -> Option<Source<ast::Module>> {
38 let def_map = db.crate_def_map(self.krate); 38 let def_map = db.crate_def_map(self.krate);
39 let decl = def_map[self.module_id].declaration?; 39 let decl = def_map[self.module_id].declaration?;
40 let ast = decl.to_node(db); 40 let ast = decl.to_node(db);
@@ -49,62 +49,62 @@ impl HasSource for StructField {
49 } 49 }
50} 50}
51impl HasSource for Struct { 51impl HasSource for Struct {
52 type Ast = TreeArc<ast::StructDef>; 52 type Ast = ast::StructDef;
53 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::StructDef>> { 53 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::StructDef> {
54 self.id.source(db) 54 self.id.source(db)
55 } 55 }
56} 56}
57impl HasSource for Union { 57impl HasSource for Union {
58 type Ast = TreeArc<ast::StructDef>; 58 type Ast = ast::StructDef;
59 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::StructDef>> { 59 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::StructDef> {
60 self.id.source(db) 60 self.id.source(db)
61 } 61 }
62} 62}
63impl HasSource for Enum { 63impl HasSource for Enum {
64 type Ast = TreeArc<ast::EnumDef>; 64 type Ast = ast::EnumDef;
65 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::EnumDef>> { 65 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::EnumDef> {
66 self.id.source(db) 66 self.id.source(db)
67 } 67 }
68} 68}
69impl HasSource for EnumVariant { 69impl HasSource for EnumVariant {
70 type Ast = TreeArc<ast::EnumVariant>; 70 type Ast = ast::EnumVariant;
71 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::EnumVariant>> { 71 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::EnumVariant> {
72 self.source_impl(db) 72 self.source_impl(db)
73 } 73 }
74} 74}
75impl HasSource for Function { 75impl HasSource for Function {
76 type Ast = TreeArc<ast::FnDef>; 76 type Ast = ast::FnDef;
77 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::FnDef>> { 77 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::FnDef> {
78 self.id.source(db) 78 self.id.source(db)
79 } 79 }
80} 80}
81impl HasSource for Const { 81impl HasSource for Const {
82 type Ast = TreeArc<ast::ConstDef>; 82 type Ast = ast::ConstDef;
83 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::ConstDef>> { 83 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::ConstDef> {
84 self.id.source(db) 84 self.id.source(db)
85 } 85 }
86} 86}
87impl HasSource for Static { 87impl HasSource for Static {
88 type Ast = TreeArc<ast::StaticDef>; 88 type Ast = ast::StaticDef;
89 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::StaticDef>> { 89 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::StaticDef> {
90 self.id.source(db) 90 self.id.source(db)
91 } 91 }
92} 92}
93impl HasSource for Trait { 93impl HasSource for Trait {
94 type Ast = TreeArc<ast::TraitDef>; 94 type Ast = ast::TraitDef;
95 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::TraitDef>> { 95 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::TraitDef> {
96 self.id.source(db) 96 self.id.source(db)
97 } 97 }
98} 98}
99impl HasSource for TypeAlias { 99impl HasSource for TypeAlias {
100 type Ast = TreeArc<ast::TypeAliasDef>; 100 type Ast = ast::TypeAliasDef;
101 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::TypeAliasDef>> { 101 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::TypeAliasDef> {
102 self.id.source(db) 102 self.id.source(db)
103 } 103 }
104} 104}
105impl HasSource for MacroDef { 105impl HasSource for MacroDef {
106 type Ast = TreeArc<ast::MacroCall>; 106 type Ast = ast::MacroCall;
107 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::MacroCall>> { 107 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::MacroCall> {
108 Source { file_id: self.id.0.file_id(), ast: self.id.0.to_node(db) } 108 Source { file_id: self.id.0.file_id(), ast: self.id.0.to_node(db) }
109 } 109 }
110} 110}
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs
index da9f3e32d..358365176 100644
--- a/crates/ra_hir/src/db.rs
+++ b/crates/ra_hir/src/db.rs
@@ -2,7 +2,7 @@ use std::sync::Arc;
2 2
3use parking_lot::Mutex; 3use parking_lot::Mutex;
4use ra_db::{salsa, SourceDatabase}; 4use ra_db::{salsa, SourceDatabase};
5use ra_syntax::{ast, Parse, SmolStr, SyntaxNode, TreeArc}; 5use ra_syntax::{ast, Parse, SmolStr, SyntaxNode};
6 6
7use crate::{ 7use crate::{
8 adt::{EnumData, StructData}, 8 adt::{EnumData, StructData},
@@ -62,11 +62,11 @@ pub trait AstDatabase: InternDatabase {
62 62
63 #[salsa::transparent] 63 #[salsa::transparent]
64 #[salsa::invoke(crate::source_id::AstIdMap::file_item_query)] 64 #[salsa::invoke(crate::source_id::AstIdMap::file_item_query)]
65 fn ast_id_to_node(&self, file_id: HirFileId, ast_id: ErasedFileAstId) -> TreeArc<SyntaxNode>; 65 fn ast_id_to_node(&self, file_id: HirFileId, ast_id: ErasedFileAstId) -> SyntaxNode;
66 66
67 #[salsa::transparent] 67 #[salsa::transparent]
68 #[salsa::invoke(crate::ids::HirFileId::parse_or_expand_query)] 68 #[salsa::invoke(crate::ids::HirFileId::parse_or_expand_query)]
69 fn parse_or_expand(&self, file_id: HirFileId) -> Option<TreeArc<SyntaxNode>>; 69 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
70 70
71 #[salsa::invoke(crate::ids::HirFileId::parse_macro_query)] 71 #[salsa::invoke(crate::ids::HirFileId::parse_macro_query)]
72 fn parse_macro(&self, macro_file: ids::MacroFile) -> Option<Parse<SyntaxNode>>; 72 fn parse_macro(&self, macro_file: ids::MacroFile) -> Option<Parse<SyntaxNode>>;
diff --git a/crates/ra_hir/src/diagnostics.rs b/crates/ra_hir/src/diagnostics.rs
index c97f0656d..0290483b3 100644
--- a/crates/ra_hir/src/diagnostics.rs
+++ b/crates/ra_hir/src/diagnostics.rs
@@ -1,6 +1,6 @@
1use std::{any::Any, fmt}; 1use std::{any::Any, fmt};
2 2
3use ra_syntax::{ast, AstNode, AstPtr, SyntaxNode, SyntaxNodePtr, TextRange, TreeArc}; 3use ra_syntax::{ast, AstNode, AstPtr, SyntaxNode, SyntaxNodePtr, TextRange};
4use relative_path::RelativePathBuf; 4use relative_path::RelativePathBuf;
5 5
6use crate::{HirDatabase, HirFileId, Name}; 6use crate::{HirDatabase, HirFileId, Name};
@@ -33,9 +33,9 @@ pub trait AstDiagnostic {
33} 33}
34 34
35impl dyn Diagnostic { 35impl dyn Diagnostic {
36 pub fn syntax_node(&self, db: &impl HirDatabase) -> TreeArc<SyntaxNode> { 36 pub fn syntax_node(&self, db: &impl HirDatabase) -> SyntaxNode {
37 let node = db.parse_or_expand(self.file()).unwrap(); 37 let node = db.parse_or_expand(self.file()).unwrap();
38 self.syntax_node_ptr().to_node(&*node).to_owned() 38 self.syntax_node_ptr().to_node(&node)
39 } 39 }
40 40
41 pub fn downcast_ref<D: Diagnostic>(&self) -> Option<&D> { 41 pub fn downcast_ref<D: Diagnostic>(&self) -> Option<&D> {
@@ -143,11 +143,11 @@ impl Diagnostic for MissingFields {
143} 143}
144 144
145impl AstDiagnostic for MissingFields { 145impl AstDiagnostic for MissingFields {
146 type AST = TreeArc<ast::NamedFieldList>; 146 type AST = ast::NamedFieldList;
147 147
148 fn ast(&self, db: &impl HirDatabase) -> Self::AST { 148 fn ast(&self, db: &impl HirDatabase) -> Self::AST {
149 let root = db.parse_or_expand(self.file()).unwrap(); 149 let root = db.parse_or_expand(self.file()).unwrap();
150 let node = self.syntax_node_ptr().to_node(&*root); 150 let node = self.syntax_node_ptr().to_node(&root);
151 ast::NamedFieldList::cast(&node).unwrap().to_owned() 151 ast::NamedFieldList::cast(node).unwrap()
152 } 152 }
153} 153}
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs
index 3a97d97ce..70af3f119 100644
--- a/crates/ra_hir/src/expr.rs
+++ b/crates/ra_hir/src/expr.rs
@@ -550,7 +550,7 @@ where
550 self.exprs.alloc(block) 550 self.exprs.alloc(block)
551 } 551 }
552 552
553 fn collect_expr(&mut self, expr: &ast::Expr) -> ExprId { 553 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
554 let syntax_ptr = SyntaxNodePtr::new(expr.syntax()); 554 let syntax_ptr = SyntaxNodePtr::new(expr.syntax());
555 match expr.kind() { 555 match expr.kind() {
556 ast::ExprKind::IfExpr(e) => { 556 ast::ExprKind::IfExpr(e) => {
@@ -565,7 +565,8 @@ where
565 .map(|b| match b { 565 .map(|b| match b {
566 ast::ElseBranch::Block(it) => self.collect_block(it), 566 ast::ElseBranch::Block(it) => self.collect_block(it),
567 ast::ElseBranch::IfExpr(elif) => { 567 ast::ElseBranch::IfExpr(elif) => {
568 let expr: &ast::Expr = ast::Expr::cast(elif.syntax()).unwrap(); 568 let expr: ast::Expr =
569 ast::Expr::cast(elif.syntax().clone()).unwrap();
569 self.collect_expr(expr) 570 self.collect_expr(expr)
570 } 571 }
571 }) 572 })
@@ -582,7 +583,7 @@ where
582 let else_branch = e.else_branch().map(|b| match b { 583 let else_branch = e.else_branch().map(|b| match b {
583 ast::ElseBranch::Block(it) => self.collect_block(it), 584 ast::ElseBranch::Block(it) => self.collect_block(it),
584 ast::ElseBranch::IfExpr(elif) => { 585 ast::ElseBranch::IfExpr(elif) => {
585 let expr: &ast::Expr = ast::Expr::cast(elif.syntax()).unwrap(); 586 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
586 self.collect_expr(expr) 587 self.collect_expr(expr)
587 } 588 }
588 }); 589 });
@@ -689,7 +690,7 @@ where
689 let struct_lit = if let Some(nfl) = e.named_field_list() { 690 let struct_lit = if let Some(nfl) = e.named_field_list() {
690 let fields = nfl 691 let fields = nfl
691 .fields() 692 .fields()
692 .inspect(|field| field_ptrs.push(AstPtr::new(*field))) 693 .inspect(|field| field_ptrs.push(AstPtr::new(field)))
693 .map(|field| StructLitField { 694 .map(|field| StructLitField {
694 name: field 695 name: field
695 .name_ref() 696 .name_ref()
@@ -699,7 +700,7 @@ where
699 self.collect_expr(e) 700 self.collect_expr(e)
700 } else if let Some(nr) = field.name_ref() { 701 } else if let Some(nr) = field.name_ref() {
701 // field shorthand 702 // field shorthand
702 let id = self.exprs.alloc(Expr::Path(Path::from_name_ref(nr))); 703 let id = self.exprs.alloc(Expr::Path(Path::from_name_ref(&nr)));
703 self.source_map 704 self.source_map
704 .expr_map 705 .expr_map
705 .insert(SyntaxNodePtr::new(nr.syntax()), id); 706 .insert(SyntaxNodePtr::new(nr.syntax()), id);
@@ -837,7 +838,7 @@ where
837 let ast_id = self 838 let ast_id = self
838 .db 839 .db
839 .ast_id_map(self.current_file_id) 840 .ast_id_map(self.current_file_id)
840 .ast_id(e) 841 .ast_id(&e)
841 .with_file_id(self.current_file_id); 842 .with_file_id(self.current_file_id);
842 843
843 if let Some(path) = e.path().and_then(Path::from_ast) { 844 if let Some(path) = e.path().and_then(Path::from_ast) {
@@ -845,11 +846,11 @@ where
845 let call_id = MacroCallLoc { def: def.id, ast_id }.id(self.db); 846 let call_id = MacroCallLoc { def: def.id, ast_id }.id(self.db);
846 let file_id = call_id.as_file(MacroFileKind::Expr); 847 let file_id = call_id.as_file(MacroFileKind::Expr);
847 if let Some(node) = self.db.parse_or_expand(file_id) { 848 if let Some(node) = self.db.parse_or_expand(file_id) {
848 if let Some(expr) = ast::Expr::cast(&*node) { 849 if let Some(expr) = ast::Expr::cast(node) {
849 log::debug!("macro expansion {}", expr.syntax().debug_dump()); 850 log::debug!("macro expansion {}", expr.syntax().debug_dump());
850 let old_file_id = 851 let old_file_id =
851 std::mem::replace(&mut self.current_file_id, file_id); 852 std::mem::replace(&mut self.current_file_id, file_id);
852 let id = self.collect_expr(&expr); 853 let id = self.collect_expr(expr);
853 self.current_file_id = old_file_id; 854 self.current_file_id = old_file_id;
854 return id; 855 return id;
855 } 856 }
@@ -863,7 +864,7 @@ where
863 } 864 }
864 } 865 }
865 866
866 fn collect_expr_opt(&mut self, expr: Option<&ast::Expr>) -> ExprId { 867 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
867 if let Some(expr) = expr { 868 if let Some(expr) = expr {
868 self.collect_expr(expr) 869 self.collect_expr(expr)
869 } else { 870 } else {
@@ -871,7 +872,7 @@ where
871 } 872 }
872 } 873 }
873 874
874 fn collect_block(&mut self, block: &ast::Block) -> ExprId { 875 fn collect_block(&mut self, block: ast::Block) -> ExprId {
875 let statements = block 876 let statements = block
876 .statements() 877 .statements()
877 .map(|s| match s.kind() { 878 .map(|s| match s.kind() {
@@ -890,7 +891,7 @@ where
890 self.alloc_expr(Expr::Block { statements, tail }, SyntaxNodePtr::new(block.syntax())) 891 self.alloc_expr(Expr::Block { statements, tail }, SyntaxNodePtr::new(block.syntax()))
891 } 892 }
892 893
893 fn collect_block_opt(&mut self, block: Option<&ast::Block>) -> ExprId { 894 fn collect_block_opt(&mut self, block: Option<ast::Block>) -> ExprId {
894 if let Some(block) = block { 895 if let Some(block) = block {
895 self.collect_block(block) 896 self.collect_block(block)
896 } else { 897 } else {
@@ -898,7 +899,7 @@ where
898 } 899 }
899 } 900 }
900 901
901 fn collect_pat(&mut self, pat: &ast::Pat) -> PatId { 902 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
902 let pattern = match pat.kind() { 903 let pattern = match pat.kind() {
903 ast::PatKind::BindPat(bp) => { 904 ast::PatKind::BindPat(bp) => {
904 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing); 905 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
@@ -932,7 +933,8 @@ where
932 let mut fields: Vec<_> = field_pat_list 933 let mut fields: Vec<_> = field_pat_list
933 .bind_pats() 934 .bind_pats()
934 .filter_map(|bind_pat| { 935 .filter_map(|bind_pat| {
935 let ast_pat = ast::Pat::cast(bind_pat.syntax()).expect("bind pat is a pat"); 936 let ast_pat =
937 ast::Pat::cast(bind_pat.syntax().clone()).expect("bind pat is a pat");
936 let pat = self.collect_pat(ast_pat); 938 let pat = self.collect_pat(ast_pat);
937 let name = bind_pat.name()?.as_name(); 939 let name = bind_pat.name()?.as_name();
938 Some(FieldPat { name, pat }) 940 Some(FieldPat { name, pat })
@@ -953,11 +955,11 @@ where
953 ast::PatKind::LiteralPat(_) => Pat::Missing, 955 ast::PatKind::LiteralPat(_) => Pat::Missing,
954 ast::PatKind::SlicePat(_) | ast::PatKind::RangePat(_) => Pat::Missing, 956 ast::PatKind::SlicePat(_) | ast::PatKind::RangePat(_) => Pat::Missing,
955 }; 957 };
956 let ptr = AstPtr::new(pat); 958 let ptr = AstPtr::new(&pat);
957 self.alloc_pat(pattern, Either::A(ptr)) 959 self.alloc_pat(pattern, Either::A(ptr))
958 } 960 }
959 961
960 fn collect_pat_opt(&mut self, pat: Option<&ast::Pat>) -> PatId { 962 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
961 if let Some(pat) = pat { 963 if let Some(pat) = pat {
962 self.collect_pat(pat) 964 self.collect_pat(pat)
963 } else { 965 } else {
@@ -965,20 +967,20 @@ where
965 } 967 }
966 } 968 }
967 969
968 fn collect_const_body(&mut self, node: &ast::ConstDef) { 970 fn collect_const_body(&mut self, node: ast::ConstDef) {
969 let body = self.collect_expr_opt(node.body()); 971 let body = self.collect_expr_opt(node.body());
970 self.body_expr = Some(body); 972 self.body_expr = Some(body);
971 } 973 }
972 974
973 fn collect_static_body(&mut self, node: &ast::StaticDef) { 975 fn collect_static_body(&mut self, node: ast::StaticDef) {
974 let body = self.collect_expr_opt(node.body()); 976 let body = self.collect_expr_opt(node.body());
975 self.body_expr = Some(body); 977 self.body_expr = Some(body);
976 } 978 }
977 979
978 fn collect_fn_body(&mut self, node: &ast::FnDef) { 980 fn collect_fn_body(&mut self, node: ast::FnDef) {
979 if let Some(param_list) = node.param_list() { 981 if let Some(param_list) = node.param_list() {
980 if let Some(self_param) = param_list.self_param() { 982 if let Some(self_param) = param_list.self_param() {
981 let ptr = AstPtr::new(self_param); 983 let ptr = AstPtr::new(&self_param);
982 let param_pat = self.alloc_pat( 984 let param_pat = self.alloc_pat(
983 Pat::Bind { 985 Pat::Bind {
984 name: SELF_PARAM, 986 name: SELF_PARAM,
@@ -1027,17 +1029,17 @@ pub(crate) fn body_with_source_map_query(
1027 DefWithBody::Const(ref c) => { 1029 DefWithBody::Const(ref c) => {
1028 let src = c.source(db); 1030 let src = c.source(db);
1029 collector = ExprCollector::new(def, src.file_id, def.resolver(db), db); 1031 collector = ExprCollector::new(def, src.file_id, def.resolver(db), db);
1030 collector.collect_const_body(&src.ast) 1032 collector.collect_const_body(src.ast)
1031 } 1033 }
1032 DefWithBody::Function(ref f) => { 1034 DefWithBody::Function(ref f) => {
1033 let src = f.source(db); 1035 let src = f.source(db);
1034 collector = ExprCollector::new(def, src.file_id, def.resolver(db), db); 1036 collector = ExprCollector::new(def, src.file_id, def.resolver(db), db);
1035 collector.collect_fn_body(&src.ast) 1037 collector.collect_fn_body(src.ast)
1036 } 1038 }
1037 DefWithBody::Static(ref s) => { 1039 DefWithBody::Static(ref s) => {
1038 let src = s.source(db); 1040 let src = s.source(db);
1039 collector = ExprCollector::new(def, src.file_id, def.resolver(db), db); 1041 collector = ExprCollector::new(def, src.file_id, def.resolver(db), db);
1040 collector.collect_static_body(&src.ast) 1042 collector.collect_static_body(src.ast)
1041 } 1043 }
1042 } 1044 }
1043 1045
diff --git a/crates/ra_hir/src/expr/scope.rs b/crates/ra_hir/src/expr/scope.rs
index 28fd52684..6589b782c 100644
--- a/crates/ra_hir/src/expr/scope.rs
+++ b/crates/ra_hir/src/expr/scope.rs
@@ -190,7 +190,7 @@ mod tests {
190 190
191 let (db, _source_root, file_id) = MockDatabase::with_single_file(&code); 191 let (db, _source_root, file_id) = MockDatabase::with_single_file(&code);
192 let file = db.parse(file_id).ok().unwrap(); 192 let file = db.parse(file_id).ok().unwrap();
193 let marker: &ast::PathExpr = find_node_at_offset(file.syntax(), off).unwrap(); 193 let marker: ast::PathExpr = find_node_at_offset(file.syntax(), off).unwrap();
194 let analyzer = SourceAnalyzer::new(&db, file_id, marker.syntax(), None); 194 let analyzer = SourceAnalyzer::new(&db, file_id, marker.syntax(), None);
195 195
196 let scopes = analyzer.scopes(); 196 let scopes = analyzer.scopes();
@@ -290,10 +290,10 @@ mod tests {
290 let file = db.parse(file_id).ok().unwrap(); 290 let file = db.parse(file_id).ok().unwrap();
291 let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into()) 291 let expected_name = find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into())
292 .expect("failed to find a name at the target offset"); 292 .expect("failed to find a name at the target offset");
293 let name_ref: &ast::NameRef = find_node_at_offset(file.syntax(), off).unwrap(); 293 let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), off).unwrap();
294 let analyzer = SourceAnalyzer::new(&db, file_id, name_ref.syntax(), None); 294 let analyzer = SourceAnalyzer::new(&db, file_id, name_ref.syntax(), None);
295 295
296 let local_name_entry = analyzer.resolve_local_name(name_ref).unwrap(); 296 let local_name_entry = analyzer.resolve_local_name(&name_ref).unwrap();
297 let local_name = 297 let local_name =
298 local_name_entry.ptr().either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()); 298 local_name_entry.ptr().either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
299 assert_eq!(local_name.range(), expected_name.syntax().range()); 299 assert_eq!(local_name.range(), expected_name.syntax().range());
diff --git a/crates/ra_hir/src/expr/validation.rs b/crates/ra_hir/src/expr/validation.rs
index c2a10a0b5..82a06ca25 100644
--- a/crates/ra_hir/src/expr/validation.rs
+++ b/crates/ra_hir/src/expr/validation.rs
@@ -79,7 +79,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
79 .and_then(StructLit::cast) 79 .and_then(StructLit::cast)
80 .and_then(|lit| lit.named_field_list()) 80 .and_then(|lit| lit.named_field_list())
81 { 81 {
82 let field_list_ptr = AstPtr::new(field_list_node); 82 let field_list_ptr = AstPtr::new(&field_list_node);
83 self.sink.push(MissingFields { 83 self.sink.push(MissingFields {
84 file: file_id, 84 file: file_id,
85 field_list: field_list_ptr, 85 field_list: field_list_ptr,
diff --git a/crates/ra_hir/src/generics.rs b/crates/ra_hir/src/generics.rs
index 07a59193f..bcbb4988d 100644
--- a/crates/ra_hir/src/generics.rs
+++ b/crates/ra_hir/src/generics.rs
@@ -76,17 +76,17 @@ impl GenericParams {
76 generics.parent_params = parent.map(|p| db.generic_params(p)); 76 generics.parent_params = parent.map(|p| db.generic_params(p));
77 let start = generics.parent_params.as_ref().map(|p| p.params.len()).unwrap_or(0) as u32; 77 let start = generics.parent_params.as_ref().map(|p| p.params.len()).unwrap_or(0) as u32;
78 match def { 78 match def {
79 GenericDef::Function(it) => generics.fill(&*it.source(db).ast, start), 79 GenericDef::Function(it) => generics.fill(&it.source(db).ast, start),
80 GenericDef::Struct(it) => generics.fill(&*it.source(db).ast, start), 80 GenericDef::Struct(it) => generics.fill(&it.source(db).ast, start),
81 GenericDef::Union(it) => generics.fill(&*it.source(db).ast, start), 81 GenericDef::Union(it) => generics.fill(&it.source(db).ast, start),
82 GenericDef::Enum(it) => generics.fill(&*it.source(db).ast, start), 82 GenericDef::Enum(it) => generics.fill(&it.source(db).ast, start),
83 GenericDef::Trait(it) => { 83 GenericDef::Trait(it) => {
84 // traits get the Self type as an implicit first type parameter 84 // traits get the Self type as an implicit first type parameter
85 generics.params.push(GenericParam { idx: start, name: SELF_TYPE, default: None }); 85 generics.params.push(GenericParam { idx: start, name: SELF_TYPE, default: None });
86 generics.fill(&*it.source(db).ast, start + 1); 86 generics.fill(&it.source(db).ast, start + 1);
87 } 87 }
88 GenericDef::TypeAlias(it) => generics.fill(&*it.source(db).ast, start), 88 GenericDef::TypeAlias(it) => generics.fill(&it.source(db).ast, start),
89 GenericDef::ImplBlock(it) => generics.fill(&*it.source(db).ast, start), 89 GenericDef::ImplBlock(it) => generics.fill(&it.source(db).ast, start),
90 GenericDef::EnumVariant(_) => {} 90 GenericDef::EnumVariant(_) => {}
91 } 91 }
92 92
@@ -102,9 +102,9 @@ impl GenericParams {
102 } 102 }
103 } 103 }
104 104
105 fn fill_params(&mut self, params: &ast::TypeParamList, start: u32) { 105 fn fill_params(&mut self, params: ast::TypeParamList, start: u32) {
106 for (idx, type_param) in params.type_params().enumerate() { 106 for (idx, type_param) in params.type_params().enumerate() {
107 let name = type_param.name().map(AsName::as_name).unwrap_or_else(Name::missing); 107 let name = type_param.name().map_or_else(Name::missing, |it| it.as_name());
108 let default = type_param.default_type().and_then(|t| t.path()).and_then(Path::from_ast); 108 let default = type_param.default_type().and_then(|t| t.path()).and_then(Path::from_ast);
109 109
110 let param = GenericParam { idx: idx as u32 + start, name: name.clone(), default }; 110 let param = GenericParam { idx: idx as u32 + start, name: name.clone(), default };
@@ -121,7 +121,7 @@ impl GenericParams {
121 } 121 }
122 } 122 }
123 123
124 fn fill_where_predicates(&mut self, where_clause: &ast::WhereClause) { 124 fn fill_where_predicates(&mut self, where_clause: ast::WhereClause) {
125 for pred in where_clause.predicates() { 125 for pred in where_clause.predicates() {
126 let type_ref = match pred.type_ref() { 126 let type_ref = match pred.type_ref() {
127 Some(type_ref) => type_ref, 127 Some(type_ref) => type_ref,
@@ -134,7 +134,7 @@ impl GenericParams {
134 } 134 }
135 } 135 }
136 136
137 fn add_where_predicate_from_bound(&mut self, bound: &ast::TypeBound, type_ref: TypeRef) { 137 fn add_where_predicate_from_bound(&mut self, bound: ast::TypeBound, type_ref: TypeRef) {
138 let path = bound 138 let path = bound
139 .type_ref() 139 .type_ref()
140 .and_then(|tr| match tr.kind() { 140 .and_then(|tr| match tr.kind() {
diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs
index 83f5c3f39..05a18eb56 100644
--- a/crates/ra_hir/src/ids.rs
+++ b/crates/ra_hir/src/ids.rs
@@ -6,7 +6,7 @@ use std::{
6use mbe::MacroRules; 6use mbe::MacroRules;
7use ra_db::{salsa, FileId}; 7use ra_db::{salsa, FileId};
8use ra_prof::profile; 8use ra_prof::profile;
9use ra_syntax::{ast, AstNode, Parse, SyntaxNode, TreeArc}; 9use ra_syntax::{ast, AstNode, Parse, SyntaxNode};
10 10
11use crate::{AstDatabase, AstId, DefDatabase, FileAstId, InternDatabase, Module, Source}; 11use crate::{AstDatabase, AstId, DefDatabase, FileAstId, InternDatabase, Module, Source};
12 12
@@ -58,11 +58,11 @@ impl HirFileId {
58 pub(crate) fn parse_or_expand_query( 58 pub(crate) fn parse_or_expand_query(
59 db: &impl AstDatabase, 59 db: &impl AstDatabase,
60 file_id: HirFileId, 60 file_id: HirFileId,
61 ) -> Option<TreeArc<SyntaxNode>> { 61 ) -> Option<SyntaxNode> {
62 match file_id.0 { 62 match file_id.0 {
63 HirFileIdRepr::File(file_id) => Some(db.parse(file_id).tree().syntax().to_owned()), 63 HirFileIdRepr::File(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
64 HirFileIdRepr::Macro(macro_file) => { 64 HirFileIdRepr::Macro(macro_file) => {
65 db.parse_macro(macro_file).map(|it| it.tree().to_owned()) 65 db.parse_macro(macro_file).map(|it| it.syntax_node())
66 } 66 }
67 } 67 }
68 } 68 }
@@ -123,7 +123,7 @@ pub struct MacroDefId(pub(crate) AstId<ast::MacroCall>);
123pub(crate) fn macro_def_query(db: &impl AstDatabase, id: MacroDefId) -> Option<Arc<MacroRules>> { 123pub(crate) fn macro_def_query(db: &impl AstDatabase, id: MacroDefId) -> Option<Arc<MacroRules>> {
124 let macro_call = id.0.to_node(db); 124 let macro_call = id.0.to_node(db);
125 let arg = macro_call.token_tree()?; 125 let arg = macro_call.token_tree()?;
126 let (tt, _) = mbe::ast_to_token_tree(arg).or_else(|| { 126 let (tt, _) = mbe::ast_to_token_tree(&arg).or_else(|| {
127 log::warn!("fail on macro_def to token tree: {:#?}", arg); 127 log::warn!("fail on macro_def to token tree: {:#?}", arg);
128 None 128 None
129 })?; 129 })?;
@@ -138,7 +138,7 @@ pub(crate) fn macro_arg_query(db: &impl AstDatabase, id: MacroCallId) -> Option<
138 let loc = id.loc(db); 138 let loc = id.loc(db);
139 let macro_call = loc.ast_id.to_node(db); 139 let macro_call = loc.ast_id.to_node(db);
140 let arg = macro_call.token_tree()?; 140 let arg = macro_call.token_tree()?;
141 let (tt, _) = mbe::ast_to_token_tree(arg)?; 141 let (tt, _) = mbe::ast_to_token_tree(&arg)?;
142 Some(Arc::new(tt)) 142 Some(Arc::new(tt))
143} 143}
144 144
@@ -262,7 +262,7 @@ pub(crate) trait AstItemDef<N: AstNode>: salsa::InternKey + Clone {
262 let loc = ItemLoc { module: ctx.module, ast_id: ast_id.with_file_id(ctx.file_id) }; 262 let loc = ItemLoc { module: ctx.module, ast_id: ast_id.with_file_id(ctx.file_id) };
263 Self::intern(ctx.db, loc) 263 Self::intern(ctx.db, loc)
264 } 264 }
265 fn source(self, db: &(impl AstDatabase + DefDatabase)) -> Source<TreeArc<N>> { 265 fn source(self, db: &(impl AstDatabase + DefDatabase)) -> Source<N> {
266 let loc = self.lookup_intern(db); 266 let loc = self.lookup_intern(db);
267 let ast = loc.ast_id.to_node(db); 267 let ast = loc.ast_id.to_node(db);
268 Source { file_id: loc.ast_id.file_id(), ast } 268 Source { file_id: loc.ast_id.file_id(), ast }
diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs
index ce134b27a..8e62cf66d 100644
--- a/crates/ra_hir/src/impl_block.rs
+++ b/crates/ra_hir/src/impl_block.rs
@@ -4,7 +4,7 @@ use std::sync::Arc;
4use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; 4use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId};
5use ra_syntax::{ 5use ra_syntax::{
6 ast::{self, AstNode}, 6 ast::{self, AstNode},
7 AstPtr, SourceFile, TreeArc, 7 AstPtr, SourceFile,
8}; 8};
9 9
10use crate::{ 10use crate::{
@@ -28,9 +28,9 @@ impl ImplSourceMap {
28 self.map.insert(impl_id, AstPtr::new(impl_block)) 28 self.map.insert(impl_id, AstPtr::new(impl_block))
29 } 29 }
30 30
31 pub fn get(&self, source: &ModuleSource, impl_id: ImplId) -> TreeArc<ast::ImplBlock> { 31 pub fn get(&self, source: &ModuleSource, impl_id: ImplId) -> ast::ImplBlock {
32 let file = match source { 32 let file = match source {
33 ModuleSource::SourceFile(file) => &*file, 33 ModuleSource::SourceFile(file) => file.clone(),
34 ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(), 34 ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(),
35 }; 35 };
36 36
@@ -45,8 +45,8 @@ pub struct ImplBlock {
45} 45}
46 46
47impl HasSource for ImplBlock { 47impl HasSource for ImplBlock {
48 type Ast = TreeArc<ast::ImplBlock>; 48 type Ast = ast::ImplBlock;
49 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<TreeArc<ast::ImplBlock>> { 49 fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ast::ImplBlock> {
50 let source_map = db.impls_in_module_with_source_map(self.module).1; 50 let source_map = db.impls_in_module_with_source_map(self.module).1;
51 let src = self.module.definition_source(db); 51 let src = self.module.definition_source(db);
52 Source { file_id: src.file_id, ast: source_map.get(&src.ast, self.impl_id) } 52 Source { file_id: src.file_id, ast: source_map.get(&src.ast, self.impl_id) }
@@ -132,9 +132,9 @@ impl ImplData {
132 item_list 132 item_list
133 .impl_items() 133 .impl_items()
134 .map(|item_node| match item_node.kind() { 134 .map(|item_node| match item_node.kind() {
135 ast::ImplItemKind::FnDef(it) => Function { id: ctx.to_def(it) }.into(), 135 ast::ImplItemKind::FnDef(it) => Function { id: ctx.to_def(&it) }.into(),
136 ast::ImplItemKind::ConstDef(it) => Const { id: ctx.to_def(it) }.into(), 136 ast::ImplItemKind::ConstDef(it) => Const { id: ctx.to_def(&it) }.into(),
137 ast::ImplItemKind::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(it) }.into(), 137 ast::ImplItemKind::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(&it) }.into(),
138 }) 138 })
139 .collect() 139 .collect()
140 } else { 140 } else {
@@ -202,20 +202,20 @@ impl ModuleImplBlocks {
202 202
203 let src = m.module.definition_source(db); 203 let src = m.module.definition_source(db);
204 let node = match &src.ast { 204 let node = match &src.ast {
205 ModuleSource::SourceFile(node) => node.syntax(), 205 ModuleSource::SourceFile(node) => node.syntax().clone(),
206 ModuleSource::Module(node) => { 206 ModuleSource::Module(node) => {
207 node.item_list().expect("inline module should have item list").syntax() 207 node.item_list().expect("inline module should have item list").syntax().clone()
208 } 208 }
209 }; 209 };
210 210
211 for impl_block_ast in node.children().filter_map(ast::ImplBlock::cast) { 211 for impl_block_ast in node.children().filter_map(ast::ImplBlock::cast) {
212 let impl_block = ImplData::from_ast(db, src.file_id, m.module, impl_block_ast); 212 let impl_block = ImplData::from_ast(db, src.file_id, m.module, &impl_block_ast);
213 let id = m.impls.alloc(impl_block); 213 let id = m.impls.alloc(impl_block);
214 for &impl_item in &m.impls[id].items { 214 for &impl_item in &m.impls[id].items {
215 m.impls_by_def.insert(impl_item, id); 215 m.impls_by_def.insert(impl_item, id);
216 } 216 }
217 217
218 source_map.insert(id, impl_block_ast); 218 source_map.insert(id, &impl_block_ast);
219 } 219 }
220 220
221 m 221 m
diff --git a/crates/ra_hir/src/lang_item.rs b/crates/ra_hir/src/lang_item.rs
index 0443d4d9a..fd6609fb8 100644
--- a/crates/ra_hir/src/lang_item.rs
+++ b/crates/ra_hir/src/lang_item.rs
@@ -1,7 +1,7 @@
1use rustc_hash::FxHashMap; 1use rustc_hash::FxHashMap;
2use std::sync::Arc; 2use std::sync::Arc;
3 3
4use ra_syntax::{ast::AttrsOwner, SmolStr, TreeArc}; 4use ra_syntax::{ast::AttrsOwner, SmolStr};
5 5
6use crate::{ 6use crate::{
7 AstDatabase, Crate, DefDatabase, Enum, Function, HasSource, HirDatabase, ImplBlock, Module, 7 AstDatabase, Crate, DefDatabase, Enum, Function, HasSource, HirDatabase, ImplBlock, Module,
@@ -95,7 +95,7 @@ impl LangItems {
95 // Look for impl targets 95 // Look for impl targets
96 for impl_block in module.impl_blocks(db) { 96 for impl_block in module.impl_blocks(db) {
97 let src = impl_block.source(db); 97 let src = impl_block.source(db);
98 if let Some(lang_item_name) = lang_item_name(&*src.ast) { 98 if let Some(lang_item_name) = lang_item_name(&src.ast) {
99 self.items 99 self.items
100 .entry(lang_item_name) 100 .entry(lang_item_name)
101 .or_insert_with(|| LangItemTarget::ImplBlock(impl_block)); 101 .or_insert_with(|| LangItemTarget::ImplBlock(impl_block));
@@ -137,11 +137,11 @@ impl LangItems {
137 item: T, 137 item: T,
138 constructor: fn(T) -> LangItemTarget, 138 constructor: fn(T) -> LangItemTarget,
139 ) where 139 ) where
140 T: Copy + HasSource<Ast = TreeArc<N>>, 140 T: Copy + HasSource<Ast = N>,
141 N: AttrsOwner, 141 N: AttrsOwner,
142 { 142 {
143 let node = item.source(db).ast; 143 let node = item.source(db).ast;
144 if let Some(lang_item_name) = lang_item_name(&*node) { 144 if let Some(lang_item_name) = lang_item_name(&node) {
145 self.items.entry(lang_item_name).or_insert_with(|| constructor(item)); 145 self.items.entry(lang_item_name).or_insert_with(|| constructor(item));
146 } 146 }
147 } 147 }
diff --git a/crates/ra_hir/src/name.rs b/crates/ra_hir/src/name.rs
index 40c9d6002..c589f8aba 100644
--- a/crates/ra_hir/src/name.rs
+++ b/crates/ra_hir/src/name.rs
@@ -75,7 +75,7 @@ impl AsName for ast::Name {
75 } 75 }
76} 76}
77 77
78impl<'a> AsName for ast::FieldKind<'a> { 78impl AsName for ast::FieldKind {
79 fn as_name(&self) -> Name { 79 fn as_name(&self) -> Name {
80 match self { 80 match self {
81 ast::FieldKind::Name(nr) => nr.as_name(), 81 ast::FieldKind::Name(nr) => nr.as_name(),
diff --git a/crates/ra_hir/src/nameres/raw.rs b/crates/ra_hir/src/nameres/raw.rs
index 46b2bef5b..8517f3c43 100644
--- a/crates/ra_hir/src/nameres/raw.rs
+++ b/crates/ra_hir/src/nameres/raw.rs
@@ -3,7 +3,7 @@ use std::{ops::Index, sync::Arc};
3use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; 3use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId};
4use ra_syntax::{ 4use ra_syntax::{
5 ast::{self, AttrsOwner, NameOwner}, 5 ast::{self, AttrsOwner, NameOwner},
6 AstNode, AstPtr, SmolStr, SourceFile, TreeArc, 6 AstNode, AstPtr, SmolStr, SourceFile,
7}; 7};
8use test_utils::tested_by; 8use test_utils::tested_by;
9 9
@@ -32,7 +32,7 @@ pub struct ImportSourceMap {
32} 32}
33 33
34type ImportSourcePtr = Either<AstPtr<ast::UseTree>, AstPtr<ast::ExternCrateItem>>; 34type ImportSourcePtr = Either<AstPtr<ast::UseTree>, AstPtr<ast::ExternCrateItem>>;
35type ImportSource = Either<TreeArc<ast::UseTree>, TreeArc<ast::ExternCrateItem>>; 35type ImportSource = Either<ast::UseTree, ast::ExternCrateItem>;
36 36
37impl ImportSourcePtr { 37impl ImportSourcePtr {
38 fn to_node(self, file: &SourceFile) -> ImportSource { 38 fn to_node(self, file: &SourceFile) -> ImportSource {
@@ -50,11 +50,11 @@ impl ImportSourceMap {
50 50
51 pub(crate) fn get(&self, source: &ModuleSource, import: ImportId) -> ImportSource { 51 pub(crate) fn get(&self, source: &ModuleSource, import: ImportId) -> ImportSource {
52 let file = match source { 52 let file = match source {
53 ModuleSource::SourceFile(file) => &*file, 53 ModuleSource::SourceFile(file) => file.clone(),
54 ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(), 54 ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(),
55 }; 55 };
56 56
57 self.map[import].to_node(file) 57 self.map[import].to_node(&file)
58 } 58 }
59} 59}
60 60
@@ -76,8 +76,8 @@ impl RawItems {
76 source_map: ImportSourceMap::default(), 76 source_map: ImportSourceMap::default(),
77 }; 77 };
78 if let Some(node) = db.parse_or_expand(file_id) { 78 if let Some(node) = db.parse_or_expand(file_id) {
79 if let Some(source_file) = ast::SourceFile::cast(&node) { 79 if let Some(source_file) = ast::SourceFile::cast(node) {
80 collector.process_module(None, &*source_file); 80 collector.process_module(None, source_file);
81 } 81 }
82 } 82 }
83 (Arc::new(collector.raw_items), Arc::new(collector.source_map)) 83 (Arc::new(collector.raw_items), Arc::new(collector.source_map))
@@ -188,7 +188,7 @@ struct RawItemsCollector {
188} 188}
189 189
190impl RawItemsCollector { 190impl RawItemsCollector {
191 fn process_module(&mut self, current_module: Option<Module>, body: &impl ast::ModuleItemOwner) { 191 fn process_module(&mut self, current_module: Option<Module>, body: impl ast::ModuleItemOwner) {
192 for item_or_macro in body.items_with_macros() { 192 for item_or_macro in body.items_with_macros() {
193 match item_or_macro { 193 match item_or_macro {
194 ast::ItemOrMacro::Macro(m) => self.add_macro(current_module, m), 194 ast::ItemOrMacro::Macro(m) => self.add_macro(current_module, m),
@@ -197,7 +197,7 @@ impl RawItemsCollector {
197 } 197 }
198 } 198 }
199 199
200 fn add_item(&mut self, current_module: Option<Module>, item: &ast::ModuleItem) { 200 fn add_item(&mut self, current_module: Option<Module>, item: ast::ModuleItem) {
201 let (kind, name) = match item.kind() { 201 let (kind, name) = match item.kind() {
202 ast::ModuleItemKind::Module(module) => { 202 ast::ModuleItemKind::Module(module) => {
203 self.add_module(current_module, module); 203 self.add_module(current_module, module);
@@ -216,7 +216,7 @@ impl RawItemsCollector {
216 return; 216 return;
217 } 217 }
218 ast::ModuleItemKind::StructDef(it) => { 218 ast::ModuleItemKind::StructDef(it) => {
219 let id = self.source_ast_id_map.ast_id(it); 219 let id = self.source_ast_id_map.ast_id(&it);
220 let name = it.name(); 220 let name = it.name();
221 if it.is_union() { 221 if it.is_union() {
222 (DefKind::Union(id), name) 222 (DefKind::Union(id), name)
@@ -225,22 +225,22 @@ impl RawItemsCollector {
225 } 225 }
226 } 226 }
227 ast::ModuleItemKind::EnumDef(it) => { 227 ast::ModuleItemKind::EnumDef(it) => {
228 (DefKind::Enum(self.source_ast_id_map.ast_id(it)), it.name()) 228 (DefKind::Enum(self.source_ast_id_map.ast_id(&it)), it.name())
229 } 229 }
230 ast::ModuleItemKind::FnDef(it) => { 230 ast::ModuleItemKind::FnDef(it) => {
231 (DefKind::Function(self.source_ast_id_map.ast_id(it)), it.name()) 231 (DefKind::Function(self.source_ast_id_map.ast_id(&it)), it.name())
232 } 232 }
233 ast::ModuleItemKind::TraitDef(it) => { 233 ast::ModuleItemKind::TraitDef(it) => {
234 (DefKind::Trait(self.source_ast_id_map.ast_id(it)), it.name()) 234 (DefKind::Trait(self.source_ast_id_map.ast_id(&it)), it.name())
235 } 235 }
236 ast::ModuleItemKind::TypeAliasDef(it) => { 236 ast::ModuleItemKind::TypeAliasDef(it) => {
237 (DefKind::TypeAlias(self.source_ast_id_map.ast_id(it)), it.name()) 237 (DefKind::TypeAlias(self.source_ast_id_map.ast_id(&it)), it.name())
238 } 238 }
239 ast::ModuleItemKind::ConstDef(it) => { 239 ast::ModuleItemKind::ConstDef(it) => {
240 (DefKind::Const(self.source_ast_id_map.ast_id(it)), it.name()) 240 (DefKind::Const(self.source_ast_id_map.ast_id(&it)), it.name())
241 } 241 }
242 ast::ModuleItemKind::StaticDef(it) => { 242 ast::ModuleItemKind::StaticDef(it) => {
243 (DefKind::Static(self.source_ast_id_map.ast_id(it)), it.name()) 243 (DefKind::Static(self.source_ast_id_map.ast_id(&it)), it.name())
244 } 244 }
245 }; 245 };
246 if let Some(name) = name { 246 if let Some(name) = name {
@@ -250,14 +250,14 @@ impl RawItemsCollector {
250 } 250 }
251 } 251 }
252 252
253 fn add_module(&mut self, current_module: Option<Module>, module: &ast::Module) { 253 fn add_module(&mut self, current_module: Option<Module>, module: ast::Module) {
254 let name = match module.name() { 254 let name = match module.name() {
255 Some(it) => it.as_name(), 255 Some(it) => it.as_name(),
256 None => return, 256 None => return,
257 }; 257 };
258 258
259 let attr_path = extract_mod_path_attribute(module); 259 let attr_path = extract_mod_path_attribute(&module);
260 let ast_id = self.source_ast_id_map.ast_id(module); 260 let ast_id = self.source_ast_id_map.ast_id(&module);
261 if module.has_semi() { 261 if module.has_semi() {
262 let item = 262 let item =
263 self.raw_items.modules.alloc(ModuleData::Declaration { name, ast_id, attr_path }); 263 self.raw_items.modules.alloc(ModuleData::Declaration { name, ast_id, attr_path });
@@ -278,10 +278,10 @@ impl RawItemsCollector {
278 tested_by!(name_res_works_for_broken_modules); 278 tested_by!(name_res_works_for_broken_modules);
279 } 279 }
280 280
281 fn add_use_item(&mut self, current_module: Option<Module>, use_item: &ast::UseItem) { 281 fn add_use_item(&mut self, current_module: Option<Module>, use_item: ast::UseItem) {
282 let is_prelude = use_item.has_atom_attr("prelude_import"); 282 let is_prelude = use_item.has_atom_attr("prelude_import");
283 283
284 Path::expand_use_item(use_item, |path, use_tree, is_glob, alias| { 284 Path::expand_use_item(&use_item, |path, use_tree, is_glob, alias| {
285 let import_data = 285 let import_data =
286 ImportData { path, alias, is_glob, is_prelude, is_extern_crate: false }; 286 ImportData { path, alias, is_glob, is_prelude, is_extern_crate: false };
287 self.push_import(current_module, import_data, Either::A(AstPtr::new(use_tree))); 287 self.push_import(current_module, import_data, Either::A(AstPtr::new(use_tree)));
@@ -291,11 +291,11 @@ impl RawItemsCollector {
291 fn add_extern_crate_item( 291 fn add_extern_crate_item(
292 &mut self, 292 &mut self,
293 current_module: Option<Module>, 293 current_module: Option<Module>,
294 extern_crate: &ast::ExternCrateItem, 294 extern_crate: ast::ExternCrateItem,
295 ) { 295 ) {
296 if let Some(name_ref) = extern_crate.name_ref() { 296 if let Some(name_ref) = extern_crate.name_ref() {
297 let path = Path::from_name_ref(name_ref); 297 let path = Path::from_name_ref(&name_ref);
298 let alias = extern_crate.alias().and_then(|a| a.name()).map(AsName::as_name); 298 let alias = extern_crate.alias().and_then(|a| a.name()).map(|it| it.as_name());
299 let import_data = ImportData { 299 let import_data = ImportData {
300 path, 300 path,
301 alias, 301 alias,
@@ -303,18 +303,18 @@ impl RawItemsCollector {
303 is_prelude: false, 303 is_prelude: false,
304 is_extern_crate: true, 304 is_extern_crate: true,
305 }; 305 };
306 self.push_import(current_module, import_data, Either::B(AstPtr::new(extern_crate))); 306 self.push_import(current_module, import_data, Either::B(AstPtr::new(&extern_crate)));
307 } 307 }
308 } 308 }
309 309
310 fn add_macro(&mut self, current_module: Option<Module>, m: &ast::MacroCall) { 310 fn add_macro(&mut self, current_module: Option<Module>, m: ast::MacroCall) {
311 let path = match m.path().and_then(Path::from_ast) { 311 let path = match m.path().and_then(Path::from_ast) {
312 Some(it) => it, 312 Some(it) => it,
313 _ => return, 313 _ => return,
314 }; 314 };
315 315
316 let name = m.name().map(|it| it.as_name()); 316 let name = m.name().map(|it| it.as_name());
317 let ast_id = self.source_ast_id_map.ast_id(m); 317 let ast_id = self.source_ast_id_map.ast_id(&m);
318 let export = m.has_atom_attr("macro_export"); 318 let export = m.has_atom_attr("macro_export");
319 let m = self.raw_items.macros.alloc(MacroData { ast_id, path, name, export }); 319 let m = self.raw_items.macros.alloc(MacroData { ast_id, path, name, export });
320 self.push_item(current_module, RawItem::Macro(m)); 320 self.push_item(current_module, RawItem::Macro(m));
diff --git a/crates/ra_hir/src/path.rs b/crates/ra_hir/src/path.rs
index bce9d2d4b..882db7681 100644
--- a/crates/ra_hir/src/path.rs
+++ b/crates/ra_hir/src/path.rs
@@ -47,9 +47,9 @@ pub enum PathKind {
47 47
48impl Path { 48impl Path {
49 /// Calls `cb` with all paths, represented by this use item. 49 /// Calls `cb` with all paths, represented by this use item.
50 pub fn expand_use_item<'a>( 50 pub fn expand_use_item(
51 item: &'a ast::UseItem, 51 item: &ast::UseItem,
52 mut cb: impl FnMut(Path, &'a ast::UseTree, bool, Option<Name>), 52 mut cb: impl FnMut(Path, &ast::UseTree, bool, Option<Name>),
53 ) { 53 ) {
54 if let Some(tree) = item.use_tree() { 54 if let Some(tree) = item.use_tree() {
55 expand_use_tree(None, tree, &mut cb); 55 expand_use_tree(None, tree, &mut cb);
@@ -57,7 +57,7 @@ impl Path {
57 } 57 }
58 58
59 /// Converts an `ast::Path` to `Path`. Works with use trees. 59 /// Converts an `ast::Path` to `Path`. Works with use trees.
60 pub fn from_ast(mut path: &ast::Path) -> Option<Path> { 60 pub fn from_ast(mut path: ast::Path) -> Option<Path> {
61 let mut kind = PathKind::Plain; 61 let mut kind = PathKind::Plain;
62 let mut segments = Vec::new(); 62 let mut segments = Vec::new();
63 loop { 63 loop {
@@ -87,7 +87,7 @@ impl Path {
87 break; 87 break;
88 } 88 }
89 } 89 }
90 path = match qualifier(path) { 90 path = match qualifier(&path) {
91 Some(it) => it, 91 Some(it) => it,
92 None => break, 92 None => break,
93 }; 93 };
@@ -95,7 +95,7 @@ impl Path {
95 segments.reverse(); 95 segments.reverse();
96 return Some(Path { kind, segments }); 96 return Some(Path { kind, segments });
97 97
98 fn qualifier(path: &ast::Path) -> Option<&ast::Path> { 98 fn qualifier(path: &ast::Path) -> Option<ast::Path> {
99 if let Some(q) = path.qualifier() { 99 if let Some(q) = path.qualifier() {
100 return Some(q); 100 return Some(q);
101 } 101 }
@@ -136,7 +136,7 @@ impl Path {
136} 136}
137 137
138impl GenericArgs { 138impl GenericArgs {
139 pub(crate) fn from_ast(node: &ast::TypeArgList) -> Option<GenericArgs> { 139 pub(crate) fn from_ast(node: ast::TypeArgList) -> Option<GenericArgs> {
140 let mut args = Vec::new(); 140 let mut args = Vec::new();
141 for type_arg in node.type_args() { 141 for type_arg in node.type_args() {
142 let type_ref = TypeRef::from_ast_opt(type_arg.type_ref()); 142 let type_ref = TypeRef::from_ast_opt(type_arg.type_ref());
@@ -160,10 +160,10 @@ impl From<Name> for Path {
160 } 160 }
161} 161}
162 162
163fn expand_use_tree<'a>( 163fn expand_use_tree(
164 prefix: Option<Path>, 164 prefix: Option<Path>,
165 tree: &'a ast::UseTree, 165 tree: ast::UseTree,
166 cb: &mut impl FnMut(Path, &'a ast::UseTree, bool, Option<Name>), 166 cb: &mut impl FnMut(Path, &ast::UseTree, bool, Option<Name>),
167) { 167) {
168 if let Some(use_tree_list) = tree.use_tree_list() { 168 if let Some(use_tree_list) = tree.use_tree_list() {
169 let prefix = match tree.path() { 169 let prefix = match tree.path() {
@@ -188,7 +188,7 @@ fn expand_use_tree<'a>(
188 if let Some(segment) = ast_path.segment() { 188 if let Some(segment) = ast_path.segment() {
189 if segment.kind() == Some(ast::PathSegmentKind::SelfKw) { 189 if segment.kind() == Some(ast::PathSegmentKind::SelfKw) {
190 if let Some(prefix) = prefix { 190 if let Some(prefix) = prefix {
191 cb(prefix, tree, false, alias); 191 cb(prefix, &tree, false, alias);
192 return; 192 return;
193 } 193 }
194 } 194 }
@@ -196,7 +196,7 @@ fn expand_use_tree<'a>(
196 } 196 }
197 if let Some(path) = convert_path(prefix, ast_path) { 197 if let Some(path) = convert_path(prefix, ast_path) {
198 let is_glob = tree.has_star(); 198 let is_glob = tree.has_star();
199 cb(path, tree, is_glob, alias) 199 cb(path, &tree, is_glob, alias)
200 } 200 }
201 // FIXME: report errors somewhere 201 // FIXME: report errors somewhere
202 // We get here if we do 202 // We get here if we do
@@ -204,7 +204,7 @@ fn expand_use_tree<'a>(
204 } 204 }
205} 205}
206 206
207fn convert_path(prefix: Option<Path>, path: &ast::Path) -> Option<Path> { 207fn convert_path(prefix: Option<Path>, path: ast::Path) -> Option<Path> {
208 let prefix = 208 let prefix =
209 if let Some(qual) = path.qualifier() { Some(convert_path(prefix, qual)?) } else { prefix }; 209 if let Some(qual) = path.qualifier() { Some(convert_path(prefix, qual)?) } else { prefix };
210 let segment = path.segment()?; 210 let segment = path.segment()?;
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
index 071c1bb18..e7bc4df97 100644
--- a/crates/ra_hir/src/source_binder.rs
+++ b/crates/ra_hir/src/source_binder.rs
@@ -37,7 +37,7 @@ pub fn module_from_file_id(db: &impl HirDatabase, file_id: FileId) -> Option<Mod
37pub fn module_from_declaration( 37pub fn module_from_declaration(
38 db: &impl HirDatabase, 38 db: &impl HirDatabase,
39 file_id: FileId, 39 file_id: FileId,
40 decl: &ast::Module, 40 decl: ast::Module,
41) -> Option<Module> { 41) -> Option<Module> {
42 let parent_module = module_from_file_id(db, file_id); 42 let parent_module = module_from_file_id(db, file_id);
43 let child_name = decl.name(); 43 let child_name = decl.name();
@@ -50,8 +50,8 @@ pub fn module_from_declaration(
50/// Locates the module by position in the source code. 50/// Locates the module by position in the source code.
51pub fn module_from_position(db: &impl HirDatabase, position: FilePosition) -> Option<Module> { 51pub fn module_from_position(db: &impl HirDatabase, position: FilePosition) -> Option<Module> {
52 let parse = db.parse(position.file_id); 52 let parse = db.parse(position.file_id);
53 match find_node_at_offset::<ast::Module>(parse.tree().syntax(), position.offset) { 53 match &find_node_at_offset::<ast::Module>(parse.tree().syntax(), position.offset) {
54 Some(m) if !m.has_semi() => module_from_inline(db, position.file_id, m), 54 Some(m) if !m.has_semi() => module_from_inline(db, position.file_id, m.clone()),
55 _ => module_from_file_id(db, position.file_id), 55 _ => module_from_file_id(db, position.file_id),
56 } 56 }
57} 57}
@@ -59,12 +59,12 @@ pub fn module_from_position(db: &impl HirDatabase, position: FilePosition) -> Op
59fn module_from_inline( 59fn module_from_inline(
60 db: &impl HirDatabase, 60 db: &impl HirDatabase,
61 file_id: FileId, 61 file_id: FileId,
62 module: &ast::Module, 62 module: ast::Module,
63) -> Option<Module> { 63) -> Option<Module> {
64 assert!(!module.has_semi()); 64 assert!(!module.has_semi());
65 let file_id = file_id.into(); 65 let file_id = file_id.into();
66 let ast_id_map = db.ast_id_map(file_id); 66 let ast_id_map = db.ast_id_map(file_id);
67 let item_id = ast_id_map.ast_id(module).with_file_id(file_id); 67 let item_id = ast_id_map.ast_id(&module).with_file_id(file_id);
68 module_from_source(db, file_id, Some(item_id)) 68 module_from_source(db, file_id, Some(item_id))
69} 69}
70 70
@@ -127,16 +127,16 @@ fn try_get_resolver_for_node(
127 file_id: FileId, 127 file_id: FileId,
128 node: &SyntaxNode, 128 node: &SyntaxNode,
129) -> Option<Resolver> { 129) -> Option<Resolver> {
130 if let Some(module) = ast::Module::cast(node) { 130 if let Some(module) = ast::Module::cast(node.clone()) {
131 Some(module_from_declaration(db, file_id, module)?.resolver(db)) 131 Some(module_from_declaration(db, file_id, module)?.resolver(db))
132 } else if let Some(_) = ast::SourceFile::cast(node) { 132 } else if let Some(_) = ast::SourceFile::cast(node.clone()) {
133 Some(module_from_source(db, file_id.into(), None)?.resolver(db)) 133 Some(module_from_source(db, file_id.into(), None)?.resolver(db))
134 } else if let Some(s) = ast::StructDef::cast(node) { 134 } else if let Some(s) = ast::StructDef::cast(node.clone()) {
135 let module = module_from_child_node(db, file_id, s.syntax())?; 135 let module = module_from_child_node(db, file_id, s.syntax())?;
136 Some(struct_from_module(db, module, s).resolver(db)) 136 Some(struct_from_module(db, module, &s).resolver(db))
137 } else if let Some(e) = ast::EnumDef::cast(node) { 137 } else if let Some(e) = ast::EnumDef::cast(node.clone()) {
138 let module = module_from_child_node(db, file_id, e.syntax())?; 138 let module = module_from_child_node(db, file_id, e.syntax())?;
139 Some(enum_from_module(db, module, e).resolver(db)) 139 Some(enum_from_module(db, module, &e).resolver(db))
140 } else if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF { 140 } else if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF {
141 Some(def_with_body_from_child_node(db, file_id, node)?.resolver(db)) 141 Some(def_with_body_from_child_node(db, file_id, node)?.resolver(db))
142 } else { 142 } else {
@@ -153,14 +153,14 @@ fn def_with_body_from_child_node(
153 let module = module_from_child_node(db, file_id, node)?; 153 let module = module_from_child_node(db, file_id, node)?;
154 let ctx = LocationCtx::new(db, module, file_id.into()); 154 let ctx = LocationCtx::new(db, module, file_id.into());
155 node.ancestors().find_map(|node| { 155 node.ancestors().find_map(|node| {
156 if let Some(def) = ast::FnDef::cast(node) { 156 if let Some(def) = ast::FnDef::cast(node.clone()) {
157 return Some(Function { id: ctx.to_def(def) }.into()); 157 return Some(Function { id: ctx.to_def(&def) }.into());
158 } 158 }
159 if let Some(def) = ast::ConstDef::cast(node) { 159 if let Some(def) = ast::ConstDef::cast(node.clone()) {
160 return Some(Const { id: ctx.to_def(def) }.into()); 160 return Some(Const { id: ctx.to_def(&def) }.into());
161 } 161 }
162 if let Some(def) = ast::StaticDef::cast(node) { 162 if let Some(def) = ast::StaticDef::cast(node.clone()) {
163 return Some(Static { id: ctx.to_def(def) }.into()); 163 return Some(Static { id: ctx.to_def(&def) }.into());
164 } 164 }
165 None 165 None
166 }) 166 })
@@ -237,7 +237,7 @@ impl SourceAnalyzer {
237 SourceAnalyzer { 237 SourceAnalyzer {
238 resolver: node 238 resolver: node
239 .ancestors() 239 .ancestors()
240 .find_map(|node| try_get_resolver_for_node(db, file_id, node)) 240 .find_map(|node| try_get_resolver_for_node(db, file_id, &node))
241 .unwrap_or_default(), 241 .unwrap_or_default(),
242 body_source_map: None, 242 body_source_map: None,
243 infer: None, 243 infer: None,
@@ -257,17 +257,17 @@ impl SourceAnalyzer {
257 } 257 }
258 258
259 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> { 259 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
260 let expr_id = self.body_source_map.as_ref()?.node_expr(call.into())?; 260 let expr_id = self.body_source_map.as_ref()?.node_expr(&call.clone().into())?;
261 self.infer.as_ref()?.method_resolution(expr_id) 261 self.infer.as_ref()?.method_resolution(expr_id)
262 } 262 }
263 263
264 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> { 264 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> {
265 let expr_id = self.body_source_map.as_ref()?.node_expr(field.into())?; 265 let expr_id = self.body_source_map.as_ref()?.node_expr(&field.clone().into())?;
266 self.infer.as_ref()?.field_resolution(expr_id) 266 self.infer.as_ref()?.field_resolution(expr_id)
267 } 267 }
268 268
269 pub fn resolve_variant(&self, struct_lit: &ast::StructLit) -> Option<crate::VariantDef> { 269 pub fn resolve_variant(&self, struct_lit: &ast::StructLit) -> Option<crate::VariantDef> {
270 let expr_id = self.body_source_map.as_ref()?.node_expr(struct_lit.into())?; 270 let expr_id = self.body_source_map.as_ref()?.node_expr(&struct_lit.clone().into())?;
271 self.infer.as_ref()?.variant_resolution(expr_id) 271 self.infer.as_ref()?.variant_resolution(expr_id)
272 } 272 }
273 273
@@ -290,18 +290,18 @@ impl SourceAnalyzer {
290 290
291 pub fn resolve_path(&self, db: &impl HirDatabase, path: &ast::Path) -> Option<PathResolution> { 291 pub fn resolve_path(&self, db: &impl HirDatabase, path: &ast::Path) -> Option<PathResolution> {
292 if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) { 292 if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
293 let expr_id = self.body_source_map.as_ref()?.node_expr(path_expr.into())?; 293 let expr_id = self.body_source_map.as_ref()?.node_expr(&path_expr.into())?;
294 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) { 294 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) {
295 return Some(PathResolution::AssocItem(assoc)); 295 return Some(PathResolution::AssocItem(assoc));
296 } 296 }
297 } 297 }
298 if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) { 298 if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) {
299 let pat_id = self.body_source_map.as_ref()?.node_pat(path_pat.into())?; 299 let pat_id = self.body_source_map.as_ref()?.node_pat(&path_pat.into())?;
300 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) { 300 if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) {
301 return Some(PathResolution::AssocItem(assoc)); 301 return Some(PathResolution::AssocItem(assoc));
302 } 302 }
303 } 303 }
304 let hir_path = crate::Path::from_ast(path)?; 304 let hir_path = crate::Path::from_ast(path.clone())?;
305 let res = self.resolver.resolve_path_without_assoc_items(db, &hir_path); 305 let res = self.resolver.resolve_path_without_assoc_items(db, &hir_path);
306 let res = res.clone().take_types().or_else(|| res.take_values())?; 306 let res = res.clone().take_types().or_else(|| res.take_values())?;
307 let res = match res { 307 let res = match res {
@@ -343,12 +343,12 @@ impl SourceAnalyzer {
343 // FIXME: at least, this should work with any DefWithBody, but ideally 343 // FIXME: at least, this should work with any DefWithBody, but ideally
344 // this should be hir-based altogether 344 // this should be hir-based altogether
345 let fn_def = pat.syntax().ancestors().find_map(ast::FnDef::cast).unwrap(); 345 let fn_def = pat.syntax().ancestors().find_map(ast::FnDef::cast).unwrap();
346 let ptr = Either::A(AstPtr::new(pat.into())); 346 let ptr = Either::A(AstPtr::new(&ast::Pat::from(pat.clone())));
347 fn_def 347 fn_def
348 .syntax() 348 .syntax()
349 .descendants() 349 .descendants()
350 .filter_map(ast::NameRef::cast) 350 .filter_map(ast::NameRef::cast)
351 .filter(|name_ref| match self.resolve_local_name(*name_ref) { 351 .filter(|name_ref| match self.resolve_local_name(&name_ref) {
352 None => false, 352 None => false,
353 Some(entry) => entry.ptr() == ptr, 353 Some(entry) => entry.ptr() == ptr,
354 }) 354 })
@@ -411,7 +411,7 @@ fn scope_for(
411 node: &SyntaxNode, 411 node: &SyntaxNode,
412) -> Option<ScopeId> { 412) -> Option<ScopeId> {
413 node.ancestors() 413 node.ancestors()
414 .map(SyntaxNodePtr::new) 414 .map(|it| SyntaxNodePtr::new(&it))
415 .filter_map(|ptr| source_map.syntax_expr(ptr)) 415 .filter_map(|ptr| source_map.syntax_expr(ptr))
416 .find_map(|it| scopes.scope_for(it)) 416 .find_map(|it| scopes.scope_for(it))
417} 417}
diff --git a/crates/ra_hir/src/source_id.rs b/crates/ra_hir/src/source_id.rs
index 6cdb90141..51cd65dda 100644
--- a/crates/ra_hir/src/source_id.rs
+++ b/crates/ra_hir/src/source_id.rs
@@ -5,7 +5,7 @@ use std::{
5}; 5};
6 6
7use ra_arena::{impl_arena_id, Arena, RawId}; 7use ra_arena::{impl_arena_id, Arena, RawId};
8use ra_syntax::{ast, AstNode, SyntaxNode, SyntaxNodePtr, TreeArc}; 8use ra_syntax::{ast, AstNode, SyntaxNode, SyntaxNodePtr};
9 9
10use crate::{AstDatabase, HirFileId}; 10use crate::{AstDatabase, HirFileId};
11 11
@@ -42,9 +42,9 @@ impl<N: AstNode> AstId<N> {
42 self.file_id 42 self.file_id
43 } 43 }
44 44
45 pub(crate) fn to_node(&self, db: &impl AstDatabase) -> TreeArc<N> { 45 pub(crate) fn to_node(&self, db: &impl AstDatabase) -> N {
46 let syntax_node = db.ast_id_to_node(self.file_id, self.file_ast_id.raw); 46 let syntax_node = db.ast_id_to_node(self.file_id, self.file_ast_id.raw);
47 N::cast(&syntax_node).unwrap().to_owned() 47 N::cast(syntax_node).unwrap()
48 } 48 }
49} 49}
50 50
@@ -93,7 +93,7 @@ pub struct AstIdMap {
93impl AstIdMap { 93impl AstIdMap {
94 pub(crate) fn ast_id_map_query(db: &impl AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> { 94 pub(crate) fn ast_id_map_query(db: &impl AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
95 let map = if let Some(node) = db.parse_or_expand(file_id) { 95 let map = if let Some(node) = db.parse_or_expand(file_id) {
96 AstIdMap::from_source(&*node) 96 AstIdMap::from_source(&node)
97 } else { 97 } else {
98 AstIdMap::default() 98 AstIdMap::default()
99 }; 99 };
@@ -104,9 +104,9 @@ impl AstIdMap {
104 db: &impl AstDatabase, 104 db: &impl AstDatabase,
105 file_id: HirFileId, 105 file_id: HirFileId,
106 ast_id: ErasedFileAstId, 106 ast_id: ErasedFileAstId,
107 ) -> TreeArc<SyntaxNode> { 107 ) -> SyntaxNode {
108 let node = db.parse_or_expand(file_id).unwrap(); 108 let node = db.parse_or_expand(file_id).unwrap();
109 db.ast_id_map(file_id).arena[ast_id].to_node(&*node).to_owned() 109 db.ast_id_map(file_id).arena[ast_id].to_node(&node)
110 } 110 }
111 111
112 pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> FileAstId<N> { 112 pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> FileAstId<N> {
@@ -131,7 +131,7 @@ impl AstIdMap {
131 // change parent's id. This means that, say, adding a new function to a 131 // change parent's id. This means that, say, adding a new function to a
132 // trait does not change ids of top-level items, which helps caching. 132 // trait does not change ids of top-level items, which helps caching.
133 bfs(node, |it| { 133 bfs(node, |it| {
134 if let Some(module_item) = ast::ModuleItem::cast(it) { 134 if let Some(module_item) = ast::ModuleItem::cast(it.clone()) {
135 res.alloc(module_item.syntax()); 135 res.alloc(module_item.syntax());
136 } else if let Some(macro_call) = ast::MacroCall::cast(it) { 136 } else if let Some(macro_call) = ast::MacroCall::cast(it) {
137 res.alloc(macro_call.syntax()); 137 res.alloc(macro_call.syntax());
@@ -146,8 +146,8 @@ impl AstIdMap {
146} 146}
147 147
148/// Walks the subtree in bfs order, calling `f` for each node. 148/// Walks the subtree in bfs order, calling `f` for each node.
149fn bfs(node: &SyntaxNode, mut f: impl FnMut(&SyntaxNode)) { 149fn bfs(node: &SyntaxNode, mut f: impl FnMut(SyntaxNode)) {
150 let mut curr_layer = vec![node]; 150 let mut curr_layer = vec![node.clone()];
151 let mut next_layer = vec![]; 151 let mut next_layer = vec![];
152 while !curr_layer.is_empty() { 152 while !curr_layer.is_empty() {
153 curr_layer.drain(..).for_each(|node| { 153 curr_layer.drain(..).for_each(|node| {
diff --git a/crates/ra_hir/src/traits.rs b/crates/ra_hir/src/traits.rs
index fc0368303..de26f1a68 100644
--- a/crates/ra_hir/src/traits.rs
+++ b/crates/ra_hir/src/traits.rs
@@ -31,9 +31,9 @@ impl TraitData {
31 item_list 31 item_list
32 .impl_items() 32 .impl_items()
33 .map(|item_node| match item_node.kind() { 33 .map(|item_node| match item_node.kind() {
34 ast::ImplItemKind::FnDef(it) => Function { id: ctx.to_def(it) }.into(), 34 ast::ImplItemKind::FnDef(it) => Function { id: ctx.to_def(&it) }.into(),
35 ast::ImplItemKind::ConstDef(it) => Const { id: ctx.to_def(it) }.into(), 35 ast::ImplItemKind::ConstDef(it) => Const { id: ctx.to_def(&it) }.into(),
36 ast::ImplItemKind::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(it) }.into(), 36 ast::ImplItemKind::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(&it) }.into(),
37 }) 37 })
38 .collect() 38 .collect()
39 } else { 39 } else {
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs
index 2410602a6..265740e54 100644
--- a/crates/ra_hir/src/ty/tests.rs
+++ b/crates/ra_hir/src/ty/tests.rs
@@ -3086,7 +3086,7 @@ fn type_at_pos(db: &MockDatabase, pos: FilePosition) -> String {
3086 let file = db.parse(pos.file_id).ok().unwrap(); 3086 let file = db.parse(pos.file_id).ok().unwrap();
3087 let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap(); 3087 let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap();
3088 let analyzer = SourceAnalyzer::new(db, pos.file_id, expr.syntax(), Some(pos.offset)); 3088 let analyzer = SourceAnalyzer::new(db, pos.file_id, expr.syntax(), Some(pos.offset));
3089 let ty = analyzer.type_of(db, expr).unwrap(); 3089 let ty = analyzer.type_of(db, &expr).unwrap();
3090 ty.display(db).to_string() 3090 ty.display(db).to_string()
3091} 3091}
3092 3092
@@ -3126,7 +3126,7 @@ fn infer(content: &str) -> String {
3126 types.sort_by_key(|(ptr, _)| (ptr.range().start(), ptr.range().end())); 3126 types.sort_by_key(|(ptr, _)| (ptr.range().start(), ptr.range().end()));
3127 for (syntax_ptr, ty) in &types { 3127 for (syntax_ptr, ty) in &types {
3128 let node = syntax_ptr.to_node(source_file.syntax()); 3128 let node = syntax_ptr.to_node(source_file.syntax());
3129 let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node) { 3129 let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.clone()) {
3130 (self_param.self_kw_token().range(), "self".to_string()) 3130 (self_param.self_kw_token().range(), "self".to_string())
3131 } else { 3131 } else {
3132 (syntax_ptr.range(), node.text().to_string().replace("\n", " ")) 3132 (syntax_ptr.range(), node.text().to_string().replace("\n", " "))
@@ -3137,7 +3137,7 @@ fn infer(content: &str) -> String {
3137 3137
3138 for node in source_file.syntax().descendants() { 3138 for node in source_file.syntax().descendants() {
3139 if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF { 3139 if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF {
3140 let analyzer = SourceAnalyzer::new(&db, file_id, node, None); 3140 let analyzer = SourceAnalyzer::new(&db, file_id, &node, None);
3141 infer_def(analyzer.inference_result(), analyzer.body_source_map()); 3141 infer_def(analyzer.inference_result(), analyzer.body_source_map());
3142 } 3142 }
3143 } 3143 }
@@ -3179,7 +3179,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
3179 let node = 3179 let node =
3180 algo::find_token_at_offset(file.syntax(), pos.offset).right_biased().unwrap().parent(); 3180 algo::find_token_at_offset(file.syntax(), pos.offset).right_biased().unwrap().parent();
3181 let events = db.log_executed(|| { 3181 let events = db.log_executed(|| {
3182 SourceAnalyzer::new(&db, pos.file_id, node, None); 3182 SourceAnalyzer::new(&db, pos.file_id, &node, None);
3183 }); 3183 });
3184 assert!(format!("{:?}", events).contains("infer")) 3184 assert!(format!("{:?}", events).contains("infer"))
3185 } 3185 }
@@ -3200,7 +3200,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
3200 let node = 3200 let node =
3201 algo::find_token_at_offset(file.syntax(), pos.offset).right_biased().unwrap().parent(); 3201 algo::find_token_at_offset(file.syntax(), pos.offset).right_biased().unwrap().parent();
3202 let events = db.log_executed(|| { 3202 let events = db.log_executed(|| {
3203 SourceAnalyzer::new(&db, pos.file_id, node, None); 3203 SourceAnalyzer::new(&db, pos.file_id, &node, None);
3204 }); 3204 });
3205 assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events) 3205 assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
3206 } 3206 }
diff --git a/crates/ra_hir/src/type_ref.rs b/crates/ra_hir/src/type_ref.rs
index 8aa807648..8536ae44a 100644
--- a/crates/ra_hir/src/type_ref.rs
+++ b/crates/ra_hir/src/type_ref.rs
@@ -56,7 +56,7 @@ pub enum TypeRef {
56 56
57impl TypeRef { 57impl TypeRef {
58 /// Converts an `ast::TypeRef` to a `hir::TypeRef`. 58 /// Converts an `ast::TypeRef` to a `hir::TypeRef`.
59 pub(crate) fn from_ast(node: &ast::TypeRef) -> Self { 59 pub(crate) fn from_ast(node: ast::TypeRef) -> Self {
60 use ra_syntax::ast::TypeRefKind::*; 60 use ra_syntax::ast::TypeRefKind::*;
61 match node.kind() { 61 match node.kind() {
62 ParenType(inner) => TypeRef::from_ast_opt(inner.type_ref()), 62 ParenType(inner) => TypeRef::from_ast_opt(inner.type_ref()),
@@ -95,7 +95,7 @@ impl TypeRef {
95 } 95 }
96 } 96 }
97 97
98 pub(crate) fn from_ast_opt(node: Option<&ast::TypeRef>) -> Self { 98 pub(crate) fn from_ast_opt(node: Option<ast::TypeRef>) -> Self {
99 if let Some(node) = node { 99 if let Some(node) = node {
100 TypeRef::from_ast(node) 100 TypeRef::from_ast(node)
101 } else { 101 } else {
diff --git a/crates/ra_ide_api/src/call_info.rs b/crates/ra_ide_api/src/call_info.rs
index 11dea7c14..270499612 100644
--- a/crates/ra_ide_api/src/call_info.rs
+++ b/crates/ra_ide_api/src/call_info.rs
@@ -11,24 +11,24 @@ use crate::{db::RootDatabase, CallInfo, FilePosition, FunctionSignature};
11/// Computes parameter information for the given call expression. 11/// Computes parameter information for the given call expression.
12pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> { 12pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
13 let parse = db.parse(position.file_id); 13 let parse = db.parse(position.file_id);
14 let syntax = parse.tree().syntax(); 14 let syntax = parse.tree().syntax().clone();
15 15
16 // Find the calling expression and it's NameRef 16 // Find the calling expression and it's NameRef
17 let calling_node = FnCallNode::with_node(syntax, position.offset)?; 17 let calling_node = FnCallNode::with_node(&syntax, position.offset)?;
18 let name_ref = calling_node.name_ref()?; 18 let name_ref = calling_node.name_ref()?;
19 19
20 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, name_ref.syntax(), None); 20 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, name_ref.syntax(), None);
21 let function = match calling_node { 21 let function = match &calling_node {
22 FnCallNode::CallExpr(expr) => { 22 FnCallNode::CallExpr(expr) => {
23 //FIXME: apply subst 23 //FIXME: apply subst
24 let (callable_def, _subst) = analyzer.type_of(db, expr.expr()?)?.as_callable()?; 24 let (callable_def, _subst) = analyzer.type_of(db, &expr.expr()?)?.as_callable()?;
25 match callable_def { 25 match callable_def {
26 hir::CallableDef::Function(it) => it, 26 hir::CallableDef::Function(it) => it,
27 //FIXME: handle other callables 27 //FIXME: handle other callables
28 _ => return None, 28 _ => return None,
29 } 29 }
30 } 30 }
31 FnCallNode::MethodCallExpr(expr) => analyzer.resolve_method_call(expr)?, 31 FnCallNode::MethodCallExpr(expr) => analyzer.resolve_method_call(&expr)?,
32 }; 32 };
33 33
34 let mut call_info = CallInfo::new(db, function); 34 let mut call_info = CallInfo::new(db, function);
@@ -73,13 +73,13 @@ pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<Cal
73 Some(call_info) 73 Some(call_info)
74} 74}
75 75
76enum FnCallNode<'a> { 76enum FnCallNode {
77 CallExpr(&'a ast::CallExpr), 77 CallExpr(ast::CallExpr),
78 MethodCallExpr(&'a ast::MethodCallExpr), 78 MethodCallExpr(ast::MethodCallExpr),
79} 79}
80 80
81impl<'a> FnCallNode<'a> { 81impl FnCallNode {
82 fn with_node(syntax: &'a SyntaxNode, offset: TextUnit) -> Option<FnCallNode<'a>> { 82 fn with_node(syntax: &SyntaxNode, offset: TextUnit) -> Option<FnCallNode> {
83 if let Some(expr) = find_node_at_offset::<ast::CallExpr>(syntax, offset) { 83 if let Some(expr) = find_node_at_offset::<ast::CallExpr>(syntax, offset) {
84 return Some(FnCallNode::CallExpr(expr)); 84 return Some(FnCallNode::CallExpr(expr));
85 } 85 }
@@ -89,8 +89,8 @@ impl<'a> FnCallNode<'a> {
89 None 89 None
90 } 90 }
91 91
92 fn name_ref(&self) -> Option<&'a ast::NameRef> { 92 fn name_ref(&self) -> Option<ast::NameRef> {
93 match *self { 93 match self {
94 FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()?.kind() { 94 FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()?.kind() {
95 ast::ExprKind::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?, 95 ast::ExprKind::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
96 _ => return None, 96 _ => return None,
@@ -102,8 +102,8 @@ impl<'a> FnCallNode<'a> {
102 } 102 }
103 } 103 }
104 104
105 fn arg_list(&self) -> Option<&'a ast::ArgList> { 105 fn arg_list(&self) -> Option<ast::ArgList> {
106 match *self { 106 match self {
107 FnCallNode::CallExpr(expr) => expr.arg_list(), 107 FnCallNode::CallExpr(expr) => expr.arg_list(),
108 FnCallNode::MethodCallExpr(expr) => expr.arg_list(), 108 FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
109 } 109 }
diff --git a/crates/ra_ide_api/src/completion/complete_dot.rs b/crates/ra_ide_api/src/completion/complete_dot.rs
index a5f071442..536ba36df 100644
--- a/crates/ra_ide_api/src/completion/complete_dot.rs
+++ b/crates/ra_ide_api/src/completion/complete_dot.rs
@@ -5,10 +5,11 @@ use rustc_hash::FxHashSet;
5 5
6/// Complete dot accesses, i.e. fields or methods (currently only fields). 6/// Complete dot accesses, i.e. fields or methods (currently only fields).
7pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) { 7pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
8 let receiver_ty = match ctx.dot_receiver.and_then(|it| ctx.analyzer.type_of(ctx.db, it)) { 8 let receiver_ty =
9 Some(it) => it, 9 match ctx.dot_receiver.as_ref().and_then(|it| ctx.analyzer.type_of(ctx.db, it)) {
10 None => return, 10 Some(it) => it,
11 }; 11 None => return,
12 };
12 if !ctx.is_call { 13 if !ctx.is_call {
13 complete_fields(acc, ctx, receiver_ty.clone()); 14 complete_fields(acc, ctx, receiver_ty.clone());
14 } 15 }
diff --git a/crates/ra_ide_api/src/completion/complete_fn_param.rs b/crates/ra_ide_api/src/completion/complete_fn_param.rs
index 5a117c485..0887ef1f6 100644
--- a/crates/ra_ide_api/src/completion/complete_fn_param.rs
+++ b/crates/ra_ide_api/src/completion/complete_fn_param.rs
@@ -20,7 +20,7 @@ pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
20 let _ = visitor_ctx(&mut params) 20 let _ = visitor_ctx(&mut params)
21 .visit::<ast::SourceFile, _>(process) 21 .visit::<ast::SourceFile, _>(process)
22 .visit::<ast::ItemList, _>(process) 22 .visit::<ast::ItemList, _>(process)
23 .accept(node); 23 .accept(&node);
24 } 24 }
25 params 25 params
26 .into_iter() 26 .into_iter()
@@ -38,10 +38,7 @@ pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
38 .add_to(acc) 38 .add_to(acc)
39 }); 39 });
40 40
41 fn process<'a, N: ast::FnDefOwner>( 41 fn process<N: ast::FnDefOwner>(node: N, params: &mut FxHashMap<String, (u32, ast::Param)>) {
42 node: &'a N,
43 params: &mut FxHashMap<String, (u32, &'a ast::Param)>,
44 ) {
45 node.functions().filter_map(|it| it.param_list()).flat_map(|it| it.params()).for_each( 42 node.functions().filter_map(|it| it.param_list()).flat_map(|it| it.params()).for_each(
46 |param| { 43 |param| {
47 let text = param.syntax().text().to_string(); 44 let text = param.syntax().text().to_string();
diff --git a/crates/ra_ide_api/src/completion/complete_keyword.rs b/crates/ra_ide_api/src/completion/complete_keyword.rs
index 034ed934d..4cf34eff8 100644
--- a/crates/ra_ide_api/src/completion/complete_keyword.rs
+++ b/crates/ra_ide_api/src/completion/complete_keyword.rs
@@ -52,7 +52,7 @@ pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionConte
52 return; 52 return;
53 } 53 }
54 54
55 let fn_def = match ctx.function_syntax { 55 let fn_def = match &ctx.function_syntax {
56 Some(it) => it, 56 Some(it) => it,
57 None => return, 57 None => return,
58 }; 58 };
@@ -65,7 +65,7 @@ pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionConte
65 acc.add(keyword(ctx, "else", "else {$0}")); 65 acc.add(keyword(ctx, "else", "else {$0}"));
66 acc.add(keyword(ctx, "else if", "else if $0 {}")); 66 acc.add(keyword(ctx, "else if", "else if $0 {}"));
67 } 67 }
68 if is_in_loop_body(ctx.token) { 68 if is_in_loop_body(&ctx.token) {
69 if ctx.can_be_stmt { 69 if ctx.can_be_stmt {
70 acc.add(keyword(ctx, "continue", "continue;")); 70 acc.add(keyword(ctx, "continue", "continue;"));
71 acc.add(keyword(ctx, "break", "break;")); 71 acc.add(keyword(ctx, "break", "break;"));
@@ -74,19 +74,19 @@ pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionConte
74 acc.add(keyword(ctx, "break", "break")); 74 acc.add(keyword(ctx, "break", "break"));
75 } 75 }
76 } 76 }
77 acc.add_all(complete_return(ctx, fn_def, ctx.can_be_stmt)); 77 acc.add_all(complete_return(ctx, &fn_def, ctx.can_be_stmt));
78} 78}
79 79
80fn is_in_loop_body(leaf: SyntaxToken) -> bool { 80fn is_in_loop_body(leaf: &SyntaxToken) -> bool {
81 for node in leaf.parent().ancestors() { 81 for node in leaf.parent().ancestors() {
82 if node.kind() == FN_DEF || node.kind() == LAMBDA_EXPR { 82 if node.kind() == FN_DEF || node.kind() == LAMBDA_EXPR {
83 break; 83 break;
84 } 84 }
85 let loop_body = visitor() 85 let loop_body = visitor()
86 .visit::<ast::ForExpr, _>(LoopBodyOwner::loop_body) 86 .visit::<ast::ForExpr, _>(|it| it.loop_body())
87 .visit::<ast::WhileExpr, _>(LoopBodyOwner::loop_body) 87 .visit::<ast::WhileExpr, _>(|it| it.loop_body())
88 .visit::<ast::LoopExpr, _>(LoopBodyOwner::loop_body) 88 .visit::<ast::LoopExpr, _>(|it| it.loop_body())
89 .accept(node); 89 .accept(&node);
90 if let Some(Some(body)) = loop_body { 90 if let Some(Some(body)) = loop_body {
91 if leaf.range().is_subrange(&body.syntax().range()) { 91 if leaf.range().is_subrange(&body.syntax().range()) {
92 return true; 92 return true;
diff --git a/crates/ra_ide_api/src/completion/complete_postfix.rs b/crates/ra_ide_api/src/completion/complete_postfix.rs
index 4f5062214..c75b1c159 100644
--- a/crates/ra_ide_api/src/completion/complete_postfix.rs
+++ b/crates/ra_ide_api/src/completion/complete_postfix.rs
@@ -11,7 +11,8 @@ use ra_text_edit::TextEditBuilder;
11 11
12fn postfix_snippet(ctx: &CompletionContext, label: &str, detail: &str, snippet: &str) -> Builder { 12fn postfix_snippet(ctx: &CompletionContext, label: &str, detail: &str, snippet: &str) -> Builder {
13 let edit = { 13 let edit = {
14 let receiver_range = ctx.dot_receiver.expect("no receiver available").syntax().range(); 14 let receiver_range =
15 ctx.dot_receiver.as_ref().expect("no receiver available").syntax().range();
15 let delete_range = TextRange::from_to(receiver_range.start(), ctx.source_range().end()); 16 let delete_range = TextRange::from_to(receiver_range.start(), ctx.source_range().end());
16 let mut builder = TextEditBuilder::default(); 17 let mut builder = TextEditBuilder::default();
17 builder.replace(delete_range, snippet.to_string()); 18 builder.replace(delete_range, snippet.to_string());
@@ -38,9 +39,9 @@ fn is_bool_or_unknown(ty: Option<Ty>) -> bool {
38} 39}
39 40
40pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { 41pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
41 if let Some(dot_receiver) = ctx.dot_receiver { 42 if let Some(dot_receiver) = &ctx.dot_receiver {
42 let receiver_text = dot_receiver.syntax().text().to_string(); 43 let receiver_text = dot_receiver.syntax().text().to_string();
43 let receiver_ty = ctx.analyzer.type_of(ctx.db, dot_receiver); 44 let receiver_ty = ctx.analyzer.type_of(ctx.db, &dot_receiver);
44 if is_bool_or_unknown(receiver_ty) { 45 if is_bool_or_unknown(receiver_ty) {
45 postfix_snippet(ctx, "if", "if expr {}", &format!("if {} {{$0}}", receiver_text)) 46 postfix_snippet(ctx, "if", "if expr {}", &format!("if {} {{$0}}", receiver_text))
46 .add_to(acc); 47 .add_to(acc);
diff --git a/crates/ra_ide_api/src/completion/complete_scope.rs b/crates/ra_ide_api/src/completion/complete_scope.rs
index 1ba871257..f92034055 100644
--- a/crates/ra_ide_api/src/completion/complete_scope.rs
+++ b/crates/ra_ide_api/src/completion/complete_scope.rs
@@ -20,8 +20,8 @@ pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) {
20 let mut builder = TextEditBuilder::default(); 20 let mut builder = TextEditBuilder::default();
21 builder.replace(ctx.source_range(), name.to_string()); 21 builder.replace(ctx.source_range(), name.to_string());
22 auto_import::auto_import_text_edit( 22 auto_import::auto_import_text_edit(
23 ctx.token.parent(), 23 &ctx.token.parent(),
24 ctx.token.parent(), 24 &ctx.token.parent(),
25 &path, 25 &path,
26 &mut builder, 26 &mut builder,
27 ); 27 );
diff --git a/crates/ra_ide_api/src/completion/complete_struct_literal.rs b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
index b6216f857..9410f740f 100644
--- a/crates/ra_ide_api/src/completion/complete_struct_literal.rs
+++ b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
@@ -4,8 +4,8 @@ use crate::completion::{CompletionContext, Completions};
4 4
5/// Complete fields in fields literals. 5/// Complete fields in fields literals.
6pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) { 6pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) {
7 let (ty, variant) = match ctx.struct_lit_syntax.and_then(|it| { 7 let (ty, variant) = match ctx.struct_lit_syntax.as_ref().and_then(|it| {
8 Some((ctx.analyzer.type_of(ctx.db, it.into())?, ctx.analyzer.resolve_variant(it)?)) 8 Some((ctx.analyzer.type_of(ctx.db, &it.clone().into())?, ctx.analyzer.resolve_variant(it)?))
9 }) { 9 }) {
10 Some(it) => it, 10 Some(it) => it,
11 _ => return, 11 _ => return,
diff --git a/crates/ra_ide_api/src/completion/completion_context.rs b/crates/ra_ide_api/src/completion/completion_context.rs
index 4aa84751f..b803271ab 100644
--- a/crates/ra_ide_api/src/completion/completion_context.rs
+++ b/crates/ra_ide_api/src/completion/completion_context.rs
@@ -16,11 +16,11 @@ pub(crate) struct CompletionContext<'a> {
16 pub(super) db: &'a db::RootDatabase, 16 pub(super) db: &'a db::RootDatabase,
17 pub(super) analyzer: hir::SourceAnalyzer, 17 pub(super) analyzer: hir::SourceAnalyzer,
18 pub(super) offset: TextUnit, 18 pub(super) offset: TextUnit,
19 pub(super) token: SyntaxToken<'a>, 19 pub(super) token: SyntaxToken,
20 pub(super) module: Option<hir::Module>, 20 pub(super) module: Option<hir::Module>,
21 pub(super) function_syntax: Option<&'a ast::FnDef>, 21 pub(super) function_syntax: Option<ast::FnDef>,
22 pub(super) use_item_syntax: Option<&'a ast::UseItem>, 22 pub(super) use_item_syntax: Option<ast::UseItem>,
23 pub(super) struct_lit_syntax: Option<&'a ast::StructLit>, 23 pub(super) struct_lit_syntax: Option<ast::StructLit>,
24 pub(super) is_param: bool, 24 pub(super) is_param: bool,
25 /// If a name-binding or reference to a const in a pattern. 25 /// If a name-binding or reference to a const in a pattern.
26 /// Irrefutable patterns (like let) are excluded. 26 /// Irrefutable patterns (like let) are excluded.
@@ -35,7 +35,7 @@ pub(crate) struct CompletionContext<'a> {
35 /// Something is typed at the "top" level, in module or impl/trait. 35 /// Something is typed at the "top" level, in module or impl/trait.
36 pub(super) is_new_item: bool, 36 pub(super) is_new_item: bool,
37 /// The receiver if this is a field or method access, i.e. writing something.<|> 37 /// The receiver if this is a field or method access, i.e. writing something.<|>
38 pub(super) dot_receiver: Option<&'a ast::Expr>, 38 pub(super) dot_receiver: Option<ast::Expr>,
39 /// If this is a call (method or function) in particular, i.e. the () are already there. 39 /// If this is a call (method or function) in particular, i.e. the () are already there.
40 pub(super) is_call: bool, 40 pub(super) is_call: bool,
41} 41}
@@ -50,7 +50,7 @@ impl<'a> CompletionContext<'a> {
50 let token = 50 let token =
51 find_token_at_offset(original_parse.tree().syntax(), position.offset).left_biased()?; 51 find_token_at_offset(original_parse.tree().syntax(), position.offset).left_biased()?;
52 let analyzer = 52 let analyzer =
53 hir::SourceAnalyzer::new(db, position.file_id, token.parent(), Some(position.offset)); 53 hir::SourceAnalyzer::new(db, position.file_id, &token.parent(), Some(position.offset));
54 let mut ctx = CompletionContext { 54 let mut ctx = CompletionContext {
55 db, 55 db,
56 analyzer, 56 analyzer,
@@ -109,7 +109,7 @@ impl<'a> CompletionContext<'a> {
109 if is_node::<ast::BindPat>(name.syntax()) { 109 if is_node::<ast::BindPat>(name.syntax()) {
110 let bind_pat = name.syntax().ancestors().find_map(ast::BindPat::cast).unwrap(); 110 let bind_pat = name.syntax().ancestors().find_map(ast::BindPat::cast).unwrap();
111 let parent = bind_pat.syntax().parent(); 111 let parent = bind_pat.syntax().parent();
112 if parent.and_then(ast::MatchArm::cast).is_some() 112 if parent.clone().and_then(ast::MatchArm::cast).is_some()
113 || parent.and_then(ast::Condition::cast).is_some() 113 || parent.and_then(ast::Condition::cast).is_some()
114 { 114 {
115 self.is_pat_binding = true; 115 self.is_pat_binding = true;
@@ -122,7 +122,7 @@ impl<'a> CompletionContext<'a> {
122 } 122 }
123 } 123 }
124 124
125 fn classify_name_ref(&mut self, original_file: &'a SourceFile, name_ref: &ast::NameRef) { 125 fn classify_name_ref(&mut self, original_file: SourceFile, name_ref: ast::NameRef) {
126 let name_range = name_ref.syntax().range(); 126 let name_range = name_ref.syntax().range();
127 if name_ref.syntax().parent().and_then(ast::NamedField::cast).is_some() { 127 if name_ref.syntax().parent().and_then(ast::NamedField::cast).is_some() {
128 self.struct_lit_syntax = find_node_at_offset(original_file.syntax(), self.offset); 128 self.struct_lit_syntax = find_node_at_offset(original_file.syntax(), self.offset);
@@ -153,7 +153,7 @@ impl<'a> CompletionContext<'a> {
153 None => return, 153 None => return,
154 }; 154 };
155 155
156 if let Some(segment) = ast::PathSegment::cast(parent) { 156 if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
157 let path = segment.parent_path(); 157 let path = segment.parent_path();
158 self.is_call = path 158 self.is_call = path
159 .syntax() 159 .syntax()
@@ -162,7 +162,7 @@ impl<'a> CompletionContext<'a> {
162 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast)) 162 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
163 .is_some(); 163 .is_some();
164 164
165 if let Some(mut path) = hir::Path::from_ast(path) { 165 if let Some(mut path) = hir::Path::from_ast(path.clone()) {
166 if !path.is_ident() { 166 if !path.is_ident() {
167 path.segments.pop().unwrap(); 167 path.segments.pop().unwrap();
168 self.path_prefix = Some(path); 168 self.path_prefix = Some(path);
@@ -179,7 +179,7 @@ impl<'a> CompletionContext<'a> {
179 .syntax() 179 .syntax()
180 .ancestors() 180 .ancestors()
181 .find_map(|node| { 181 .find_map(|node| {
182 if let Some(stmt) = ast::ExprStmt::cast(node) { 182 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
183 return Some(stmt.syntax().range() == name_ref.syntax().range()); 183 return Some(stmt.syntax().range() == name_ref.syntax().range());
184 } 184 }
185 if let Some(block) = ast::Block::cast(node) { 185 if let Some(block) = ast::Block::cast(node) {
@@ -203,7 +203,7 @@ impl<'a> CompletionContext<'a> {
203 } 203 }
204 } 204 }
205 } 205 }
206 if let Some(field_expr) = ast::FieldExpr::cast(parent) { 206 if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
207 // The receiver comes before the point of insertion of the fake 207 // The receiver comes before the point of insertion of the fake
208 // ident, so it should have the same range in the non-modified file 208 // ident, so it should have the same range in the non-modified file
209 self.dot_receiver = field_expr 209 self.dot_receiver = field_expr
@@ -222,7 +222,7 @@ impl<'a> CompletionContext<'a> {
222 } 222 }
223} 223}
224 224
225fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<&N> { 225fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
226 find_covering_element(syntax, range).ancestors().find_map(N::cast) 226 find_covering_element(syntax, range).ancestors().find_map(N::cast)
227} 227}
228 228
diff --git a/crates/ra_ide_api/src/diagnostics.rs b/crates/ra_ide_api/src/diagnostics.rs
index 3f5b9e0a0..affbad6cd 100644
--- a/crates/ra_ide_api/src/diagnostics.rs
+++ b/crates/ra_ide_api/src/diagnostics.rs
@@ -35,8 +35,8 @@ pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic>
35 })); 35 }));
36 36
37 for node in parse.tree().syntax().descendants() { 37 for node in parse.tree().syntax().descendants() {
38 check_unnecessary_braces_in_use_statement(&mut res, file_id, node); 38 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
39 check_struct_shorthand_initialization(&mut res, file_id, node); 39 check_struct_shorthand_initialization(&mut res, file_id, &node);
40 } 40 }
41 let res = RefCell::new(res); 41 let res = RefCell::new(res);
42 let mut sink = DiagnosticSink::new(|d| { 42 let mut sink = DiagnosticSink::new(|d| {
@@ -60,7 +60,7 @@ pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic>
60 }) 60 })
61 .on::<hir::diagnostics::MissingFields, _>(|d| { 61 .on::<hir::diagnostics::MissingFields, _>(|d| {
62 let node = d.ast(db); 62 let node = d.ast(db);
63 let mut ast_editor = AstEditor::new(&*node); 63 let mut ast_editor = AstEditor::new(node);
64 for f in d.missed_fields.iter() { 64 for f in d.missed_fields.iter() {
65 ast_editor.append_field(&AstBuilder::<NamedField>::from_name(f)); 65 ast_editor.append_field(&AstBuilder::<NamedField>::from_name(f));
66 } 66 }
@@ -94,11 +94,11 @@ fn check_unnecessary_braces_in_use_statement(
94 file_id: FileId, 94 file_id: FileId,
95 node: &SyntaxNode, 95 node: &SyntaxNode,
96) -> Option<()> { 96) -> Option<()> {
97 let use_tree_list = ast::UseTreeList::cast(node)?; 97 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
98 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() { 98 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
99 let range = use_tree_list.syntax().range(); 99 let range = use_tree_list.syntax().range();
100 let edit = 100 let edit =
101 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(single_use_tree) 101 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
102 .unwrap_or_else(|| { 102 .unwrap_or_else(|| {
103 let to_replace = single_use_tree.syntax().text().to_string(); 103 let to_replace = single_use_tree.syntax().text().to_string();
104 let mut edit_builder = TextEditBuilder::default(); 104 let mut edit_builder = TextEditBuilder::default();
@@ -141,7 +141,7 @@ fn check_struct_shorthand_initialization(
141 file_id: FileId, 141 file_id: FileId,
142 node: &SyntaxNode, 142 node: &SyntaxNode,
143) -> Option<()> { 143) -> Option<()> {
144 let struct_lit = ast::StructLit::cast(node)?; 144 let struct_lit = ast::StructLit::cast(node.clone())?;
145 let named_field_list = struct_lit.named_field_list()?; 145 let named_field_list = struct_lit.named_field_list()?;
146 for named_field in named_field_list.fields() { 146 for named_field in named_field_list.fields() {
147 if let (Some(name_ref), Some(expr)) = (named_field.name_ref(), named_field.expr()) { 147 if let (Some(name_ref), Some(expr)) = (named_field.name_ref(), named_field.expr()) {
@@ -184,7 +184,7 @@ mod tests {
184 let parse = SourceFile::parse(code); 184 let parse = SourceFile::parse(code);
185 let mut diagnostics = Vec::new(); 185 let mut diagnostics = Vec::new();
186 for node in parse.tree().syntax().descendants() { 186 for node in parse.tree().syntax().descendants() {
187 func(&mut diagnostics, FileId(0), node); 187 func(&mut diagnostics, FileId(0), &node);
188 } 188 }
189 assert!(diagnostics.is_empty()); 189 assert!(diagnostics.is_empty());
190 } 190 }
@@ -193,7 +193,7 @@ mod tests {
193 let parse = SourceFile::parse(before); 193 let parse = SourceFile::parse(before);
194 let mut diagnostics = Vec::new(); 194 let mut diagnostics = Vec::new();
195 for node in parse.tree().syntax().descendants() { 195 for node in parse.tree().syntax().descendants() {
196 func(&mut diagnostics, FileId(0), node); 196 func(&mut diagnostics, FileId(0), &node);
197 } 197 }
198 let diagnostic = 198 let diagnostic =
199 diagnostics.pop().unwrap_or_else(|| panic!("no diagnostics for:\n{}\n", before)); 199 diagnostics.pop().unwrap_or_else(|| panic!("no diagnostics for:\n{}\n", before));
diff --git a/crates/ra_ide_api/src/display/function_signature.rs b/crates/ra_ide_api/src/display/function_signature.rs
index e7ad5a0d1..644a4532b 100644
--- a/crates/ra_ide_api/src/display/function_signature.rs
+++ b/crates/ra_ide_api/src/display/function_signature.rs
@@ -38,7 +38,7 @@ impl FunctionSignature {
38 pub(crate) fn from_hir(db: &db::RootDatabase, function: hir::Function) -> Self { 38 pub(crate) fn from_hir(db: &db::RootDatabase, function: hir::Function) -> Self {
39 let doc = function.docs(db); 39 let doc = function.docs(db);
40 let ast_node = function.source(db).ast; 40 let ast_node = function.source(db).ast;
41 FunctionSignature::from(&*ast_node).with_doc_opt(doc) 41 FunctionSignature::from(&ast_node).with_doc_opt(doc)
42 } 42 }
43} 43}
44 44
diff --git a/crates/ra_ide_api/src/display/navigation_target.rs b/crates/ra_ide_api/src/display/navigation_target.rs
index 20a8d418e..8cc853dd1 100644
--- a/crates/ra_ide_api/src/display/navigation_target.rs
+++ b/crates/ra_ide_api/src/display/navigation_target.rs
@@ -5,7 +5,7 @@ use ra_syntax::{
5 ast::{self, DocCommentsOwner}, 5 ast::{self, DocCommentsOwner},
6 AstNode, AstPtr, SmolStr, 6 AstNode, AstPtr, SmolStr,
7 SyntaxKind::{self, NAME}, 7 SyntaxKind::{self, NAME},
8 SyntaxNode, TextRange, TreeArc, 8 SyntaxNode, TextRange,
9}; 9};
10 10
11use super::short_label::ShortLabel; 11use super::short_label::ShortLabel;
@@ -169,7 +169,7 @@ impl NavigationTarget {
169 let file_id = src.file_id.original_file(db); 169 let file_id = src.file_id.original_file(db);
170 match src.ast { 170 match src.ast {
171 FieldSource::Named(it) => { 171 FieldSource::Named(it) => {
172 NavigationTarget::from_named(file_id, &*it, it.doc_comment_text(), it.short_label()) 172 NavigationTarget::from_named(file_id, &it, it.doc_comment_text(), it.short_label())
173 } 173 }
174 FieldSource::Pos(it) => { 174 FieldSource::Pos(it) => {
175 NavigationTarget::from_syntax(file_id, "".into(), None, it.syntax(), None, None) 175 NavigationTarget::from_syntax(file_id, "".into(), None, it.syntax(), None, None)
@@ -179,13 +179,13 @@ impl NavigationTarget {
179 179
180 pub(crate) fn from_def_source<A, D>(db: &RootDatabase, def: D) -> NavigationTarget 180 pub(crate) fn from_def_source<A, D>(db: &RootDatabase, def: D) -> NavigationTarget
181 where 181 where
182 D: HasSource<Ast = TreeArc<A>>, 182 D: HasSource<Ast = A>,
183 A: ast::DocCommentsOwner + ast::NameOwner + ShortLabel, 183 A: ast::DocCommentsOwner + ast::NameOwner + ShortLabel,
184 { 184 {
185 let src = def.source(db); 185 let src = def.source(db);
186 NavigationTarget::from_named( 186 NavigationTarget::from_named(
187 src.file_id.original_file(db), 187 src.file_id.original_file(db),
188 &*src.ast, 188 &src.ast,
189 src.ast.doc_comment_text(), 189 src.ast.doc_comment_text(),
190 src.ast.short_label(), 190 src.ast.short_label(),
191 ) 191 )
@@ -249,7 +249,7 @@ impl NavigationTarget {
249 log::debug!("nav target {}", src.ast.syntax().debug_dump()); 249 log::debug!("nav target {}", src.ast.syntax().debug_dump());
250 NavigationTarget::from_named( 250 NavigationTarget::from_named(
251 src.file_id.original_file(db), 251 src.file_id.original_file(db),
252 &*src.ast, 252 &src.ast,
253 src.ast.doc_comment_text(), 253 src.ast.doc_comment_text(),
254 None, 254 None,
255 ) 255 )
@@ -318,22 +318,18 @@ pub(crate) fn docs_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option
318 let parse = db.parse(symbol.file_id); 318 let parse = db.parse(symbol.file_id);
319 let node = symbol.ptr.to_node(parse.tree().syntax()).to_owned(); 319 let node = symbol.ptr.to_node(parse.tree().syntax()).to_owned();
320 320
321 fn doc_comments<N: ast::DocCommentsOwner>(node: &N) -> Option<String> {
322 node.doc_comment_text()
323 }
324
325 visitor() 321 visitor()
326 .visit(doc_comments::<ast::FnDef>) 322 .visit(|it: ast::FnDef| it.doc_comment_text())
327 .visit(doc_comments::<ast::StructDef>) 323 .visit(|it: ast::StructDef| it.doc_comment_text())
328 .visit(doc_comments::<ast::EnumDef>) 324 .visit(|it: ast::EnumDef| it.doc_comment_text())
329 .visit(doc_comments::<ast::TraitDef>) 325 .visit(|it: ast::TraitDef| it.doc_comment_text())
330 .visit(doc_comments::<ast::Module>) 326 .visit(|it: ast::Module| it.doc_comment_text())
331 .visit(doc_comments::<ast::TypeAliasDef>) 327 .visit(|it: ast::TypeAliasDef| it.doc_comment_text())
332 .visit(doc_comments::<ast::ConstDef>) 328 .visit(|it: ast::ConstDef| it.doc_comment_text())
333 .visit(doc_comments::<ast::StaticDef>) 329 .visit(|it: ast::StaticDef| it.doc_comment_text())
334 .visit(doc_comments::<ast::NamedFieldDef>) 330 .visit(|it: ast::NamedFieldDef| it.doc_comment_text())
335 .visit(doc_comments::<ast::EnumVariant>) 331 .visit(|it: ast::EnumVariant| it.doc_comment_text())
336 .visit(doc_comments::<ast::MacroCall>) 332 .visit(|it: ast::MacroCall| it.doc_comment_text())
337 .accept(&node)? 333 .accept(&node)?
338} 334}
339 335
@@ -345,15 +341,15 @@ pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) ->
345 let node = symbol.ptr.to_node(parse.tree().syntax()).to_owned(); 341 let node = symbol.ptr.to_node(parse.tree().syntax()).to_owned();
346 342
347 visitor() 343 visitor()
348 .visit(|node: &ast::FnDef| node.short_label()) 344 .visit(|node: ast::FnDef| node.short_label())
349 .visit(|node: &ast::StructDef| node.short_label()) 345 .visit(|node: ast::StructDef| node.short_label())
350 .visit(|node: &ast::EnumDef| node.short_label()) 346 .visit(|node: ast::EnumDef| node.short_label())
351 .visit(|node: &ast::TraitDef| node.short_label()) 347 .visit(|node: ast::TraitDef| node.short_label())
352 .visit(|node: &ast::Module| node.short_label()) 348 .visit(|node: ast::Module| node.short_label())
353 .visit(|node: &ast::TypeAliasDef| node.short_label()) 349 .visit(|node: ast::TypeAliasDef| node.short_label())
354 .visit(|node: &ast::ConstDef| node.short_label()) 350 .visit(|node: ast::ConstDef| node.short_label())
355 .visit(|node: &ast::StaticDef| node.short_label()) 351 .visit(|node: ast::StaticDef| node.short_label())
356 .visit(|node: &ast::NamedFieldDef| node.short_label()) 352 .visit(|node: ast::NamedFieldDef| node.short_label())
357 .visit(|node: &ast::EnumVariant| node.short_label()) 353 .visit(|node: ast::EnumVariant| node.short_label())
358 .accept(&node)? 354 .accept(&node)?
359} 355}
diff --git a/crates/ra_ide_api/src/display/structure.rs b/crates/ra_ide_api/src/display/structure.rs
index 638484a9b..2e183d2f6 100644
--- a/crates/ra_ide_api/src/display/structure.rs
+++ b/crates/ra_ide_api/src/display/structure.rs
@@ -24,14 +24,14 @@ pub fn file_structure(file: &SourceFile) -> Vec<StructureNode> {
24 for event in file.syntax().preorder() { 24 for event in file.syntax().preorder() {
25 match event { 25 match event {
26 WalkEvent::Enter(node) => { 26 WalkEvent::Enter(node) => {
27 if let Some(mut symbol) = structure_node(node) { 27 if let Some(mut symbol) = structure_node(&node) {
28 symbol.parent = stack.last().copied(); 28 symbol.parent = stack.last().copied();
29 stack.push(res.len()); 29 stack.push(res.len());
30 res.push(symbol); 30 res.push(symbol);
31 } 31 }
32 } 32 }
33 WalkEvent::Leave(node) => { 33 WalkEvent::Leave(node) => {
34 if structure_node(node).is_some() { 34 if structure_node(&node).is_some() {
35 stack.pop().unwrap(); 35 stack.pop().unwrap();
36 } 36 }
37 } 37 }
@@ -41,19 +41,20 @@ pub fn file_structure(file: &SourceFile) -> Vec<StructureNode> {
41} 41}
42 42
43fn structure_node(node: &SyntaxNode) -> Option<StructureNode> { 43fn structure_node(node: &SyntaxNode) -> Option<StructureNode> {
44 fn decl<N: NameOwner + AttrsOwner>(node: &N) -> Option<StructureNode> { 44 fn decl<N: NameOwner + AttrsOwner>(node: N) -> Option<StructureNode> {
45 decl_with_detail(node, None) 45 decl_with_detail(node, None)
46 } 46 }
47 47
48 fn decl_with_ascription<N: NameOwner + AttrsOwner + TypeAscriptionOwner>( 48 fn decl_with_ascription<N: NameOwner + AttrsOwner + TypeAscriptionOwner>(
49 node: &N, 49 node: N,
50 ) -> Option<StructureNode> { 50 ) -> Option<StructureNode> {
51 decl_with_type_ref(node, node.ascribed_type()) 51 let ty = node.ascribed_type();
52 decl_with_type_ref(node, ty)
52 } 53 }
53 54
54 fn decl_with_type_ref<N: NameOwner + AttrsOwner>( 55 fn decl_with_type_ref<N: NameOwner + AttrsOwner>(
55 node: &N, 56 node: N,
56 type_ref: Option<&ast::TypeRef>, 57 type_ref: Option<ast::TypeRef>,
57 ) -> Option<StructureNode> { 58 ) -> Option<StructureNode> {
58 let detail = type_ref.map(|type_ref| { 59 let detail = type_ref.map(|type_ref| {
59 let mut detail = String::new(); 60 let mut detail = String::new();
@@ -64,7 +65,7 @@ fn structure_node(node: &SyntaxNode) -> Option<StructureNode> {
64 } 65 }
65 66
66 fn decl_with_detail<N: NameOwner + AttrsOwner>( 67 fn decl_with_detail<N: NameOwner + AttrsOwner>(
67 node: &N, 68 node: N,
68 detail: Option<String>, 69 detail: Option<String>,
69 ) -> Option<StructureNode> { 70 ) -> Option<StructureNode> {
70 let name = node.name()?; 71 let name = node.name()?;
@@ -82,22 +83,24 @@ fn structure_node(node: &SyntaxNode) -> Option<StructureNode> {
82 83
83 fn collapse_ws(node: &SyntaxNode, output: &mut String) { 84 fn collapse_ws(node: &SyntaxNode, output: &mut String) {
84 let mut can_insert_ws = false; 85 let mut can_insert_ws = false;
85 for line in node.text().chunks().flat_map(|chunk| chunk.lines()) { 86 for chunk in node.text().chunks() {
86 let line = line.trim(); 87 for line in chunk.lines() {
87 if line.is_empty() { 88 let line = line.trim();
88 if can_insert_ws { 89 if line.is_empty() {
89 output.push_str(" "); 90 if can_insert_ws {
90 can_insert_ws = false; 91 output.push_str(" ");
92 can_insert_ws = false;
93 }
94 } else {
95 output.push_str(line);
96 can_insert_ws = true;
91 } 97 }
92 } else {
93 output.push_str(line);
94 can_insert_ws = true;
95 } 98 }
96 } 99 }
97 } 100 }
98 101
99 visitor() 102 visitor()
100 .visit(|fn_def: &ast::FnDef| { 103 .visit(|fn_def: ast::FnDef| {
101 let mut detail = String::from("fn"); 104 let mut detail = String::from("fn");
102 if let Some(type_param_list) = fn_def.type_param_list() { 105 if let Some(type_param_list) = fn_def.type_param_list() {
103 collapse_ws(type_param_list.syntax(), &mut detail); 106 collapse_ws(type_param_list.syntax(), &mut detail);
@@ -117,11 +120,14 @@ fn structure_node(node: &SyntaxNode) -> Option<StructureNode> {
117 .visit(decl::<ast::EnumVariant>) 120 .visit(decl::<ast::EnumVariant>)
118 .visit(decl::<ast::TraitDef>) 121 .visit(decl::<ast::TraitDef>)
119 .visit(decl::<ast::Module>) 122 .visit(decl::<ast::Module>)
120 .visit(|td: &ast::TypeAliasDef| decl_with_type_ref(td, td.type_ref())) 123 .visit(|td: ast::TypeAliasDef| {
124 let ty = td.type_ref();
125 decl_with_type_ref(td, ty)
126 })
121 .visit(decl_with_ascription::<ast::NamedFieldDef>) 127 .visit(decl_with_ascription::<ast::NamedFieldDef>)
122 .visit(decl_with_ascription::<ast::ConstDef>) 128 .visit(decl_with_ascription::<ast::ConstDef>)
123 .visit(decl_with_ascription::<ast::StaticDef>) 129 .visit(decl_with_ascription::<ast::StaticDef>)
124 .visit(|im: &ast::ImplBlock| { 130 .visit(|im: ast::ImplBlock| {
125 let target_type = im.target_type()?; 131 let target_type = im.target_type()?;
126 let target_trait = im.target_trait(); 132 let target_trait = im.target_trait();
127 let label = match target_trait { 133 let label = match target_trait {
@@ -142,14 +148,14 @@ fn structure_node(node: &SyntaxNode) -> Option<StructureNode> {
142 }; 148 };
143 Some(node) 149 Some(node)
144 }) 150 })
145 .visit(|mc: &ast::MacroCall| { 151 .visit(|mc: ast::MacroCall| {
146 let first_token = mc.syntax().first_token().unwrap(); 152 let first_token = mc.syntax().first_token().unwrap();
147 if first_token.text().as_str() != "macro_rules" { 153 if first_token.text().as_str() != "macro_rules" {
148 return None; 154 return None;
149 } 155 }
150 decl(mc) 156 decl(mc)
151 }) 157 })
152 .accept(node)? 158 .accept(&node)?
153} 159}
154 160
155#[cfg(test)] 161#[cfg(test)]
diff --git a/crates/ra_ide_api/src/extend_selection.rs b/crates/ra_ide_api/src/extend_selection.rs
index 491b15702..8c49960f5 100644
--- a/crates/ra_ide_api/src/extend_selection.rs
+++ b/crates/ra_ide_api/src/extend_selection.rs
@@ -42,7 +42,7 @@ fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange
42 TokenAtOffset::None => return None, 42 TokenAtOffset::None => return None,
43 TokenAtOffset::Single(l) => { 43 TokenAtOffset::Single(l) => {
44 if string_kinds.contains(&l.kind()) { 44 if string_kinds.contains(&l.kind()) {
45 extend_single_word_in_comment_or_string(l, offset).unwrap_or_else(|| l.range()) 45 extend_single_word_in_comment_or_string(&l, offset).unwrap_or_else(|| l.range())
46 } else { 46 } else {
47 l.range() 47 l.range()
48 } 48 }
@@ -56,7 +56,7 @@ fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange
56 if token.range() != range { 56 if token.range() != range {
57 return Some(token.range()); 57 return Some(token.range());
58 } 58 }
59 if let Some(comment) = ast::Comment::cast(token) { 59 if let Some(comment) = ast::Comment::cast(token.clone()) {
60 if let Some(range) = extend_comments(comment) { 60 if let Some(range) = extend_comments(comment) {
61 return Some(range); 61 return Some(range);
62 } 62 }
@@ -73,7 +73,7 @@ fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange
73 let node = node.ancestors().take_while(|n| n.range() == node.range()).last().unwrap(); 73 let node = node.ancestors().take_while(|n| n.range() == node.range()).last().unwrap();
74 74
75 if node.parent().map(|n| list_kinds.contains(&n.kind())) == Some(true) { 75 if node.parent().map(|n| list_kinds.contains(&n.kind())) == Some(true) {
76 if let Some(range) = extend_list_item(node) { 76 if let Some(range) = extend_list_item(&node) {
77 return Some(range); 77 return Some(range);
78 } 78 }
79 } 79 }
@@ -82,7 +82,7 @@ fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange
82} 82}
83 83
84fn extend_single_word_in_comment_or_string( 84fn extend_single_word_in_comment_or_string(
85 leaf: SyntaxToken, 85 leaf: &SyntaxToken,
86 offset: TextUnit, 86 offset: TextUnit,
87) -> Option<TextRange> { 87) -> Option<TextRange> {
88 let text: &str = leaf.text(); 88 let text: &str = leaf.text();
@@ -131,9 +131,9 @@ fn extend_ws(root: &SyntaxNode, ws: SyntaxToken, offset: TextUnit) -> TextRange
131 ws.range() 131 ws.range()
132} 132}
133 133
134fn pick_best<'a>(l: SyntaxToken<'a>, r: SyntaxToken<'a>) -> SyntaxToken<'a> { 134fn pick_best<'a>(l: SyntaxToken, r: SyntaxToken) -> SyntaxToken {
135 return if priority(r) > priority(l) { r } else { l }; 135 return if priority(&r) > priority(&l) { r } else { l };
136 fn priority(n: SyntaxToken) -> usize { 136 fn priority(n: &SyntaxToken) -> usize {
137 match n.kind() { 137 match n.kind() {
138 WHITESPACE => 0, 138 WHITESPACE => 0,
139 IDENT | T![self] | T![super] | T![crate] | LIFETIME => 2, 139 IDENT | T![self] | T![super] | T![crate] | LIFETIME => 2,
@@ -156,7 +156,7 @@ fn extend_list_item(node: &SyntaxNode) -> Option<TextRange> {
156 SyntaxElement::Token(it) => is_single_line_ws(it), 156 SyntaxElement::Token(it) => is_single_line_ws(it),
157 }) 157 })
158 .next() 158 .next()
159 .and_then(|it| it.as_token()) 159 .and_then(|it| it.as_token().cloned())
160 .filter(|node| node.kind() == T![,]) 160 .filter(|node| node.kind() == T![,])
161 } 161 }
162 162
@@ -167,7 +167,7 @@ fn extend_list_item(node: &SyntaxNode) -> Option<TextRange> {
167 // Include any following whitespace when comma if after list item. 167 // Include any following whitespace when comma if after list item.
168 let final_node = comma_node 168 let final_node = comma_node
169 .next_sibling_or_token() 169 .next_sibling_or_token()
170 .and_then(|it| it.as_token()) 170 .and_then(|it| it.as_token().cloned())
171 .filter(|node| is_single_line_ws(node)) 171 .filter(|node| is_single_line_ws(node))
172 .unwrap_or(comma_node); 172 .unwrap_or(comma_node);
173 173
@@ -178,8 +178,8 @@ fn extend_list_item(node: &SyntaxNode) -> Option<TextRange> {
178} 178}
179 179
180fn extend_comments(comment: ast::Comment) -> Option<TextRange> { 180fn extend_comments(comment: ast::Comment) -> Option<TextRange> {
181 let prev = adj_comments(comment, Direction::Prev); 181 let prev = adj_comments(&comment, Direction::Prev);
182 let next = adj_comments(comment, Direction::Next); 182 let next = adj_comments(&comment, Direction::Next);
183 if prev != next { 183 if prev != next {
184 Some(TextRange::from_to(prev.syntax().range().start(), next.syntax().range().end())) 184 Some(TextRange::from_to(prev.syntax().range().start(), next.syntax().range().end()))
185 } else { 185 } else {
@@ -187,14 +187,14 @@ fn extend_comments(comment: ast::Comment) -> Option<TextRange> {
187 } 187 }
188} 188}
189 189
190fn adj_comments(comment: ast::Comment, dir: Direction) -> ast::Comment { 190fn adj_comments(comment: &ast::Comment, dir: Direction) -> ast::Comment {
191 let mut res = comment; 191 let mut res = comment.clone();
192 for element in comment.syntax().siblings_with_tokens(dir) { 192 for element in comment.syntax().siblings_with_tokens(dir) {
193 let token = match element.as_token() { 193 let token = match element.as_token() {
194 None => break, 194 None => break,
195 Some(token) => token, 195 Some(token) => token,
196 }; 196 };
197 if let Some(c) = ast::Comment::cast(token) { 197 if let Some(c) = ast::Comment::cast(token.clone()) {
198 res = c 198 res = c
199 } else if token.kind() != WHITESPACE || token.text().contains("\n\n") { 199 } else if token.kind() != WHITESPACE || token.text().contains("\n\n") {
200 break; 200 break;
diff --git a/crates/ra_ide_api/src/folding_ranges.rs b/crates/ra_ide_api/src/folding_ranges.rs
index 9d4855a64..c2b981aed 100644
--- a/crates/ra_ide_api/src/folding_ranges.rs
+++ b/crates/ra_ide_api/src/folding_ranges.rs
@@ -30,7 +30,7 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec<Fold> {
30 for element in file.syntax().descendants_with_tokens() { 30 for element in file.syntax().descendants_with_tokens() {
31 // Fold items that span multiple lines 31 // Fold items that span multiple lines
32 if let Some(kind) = fold_kind(element.kind()) { 32 if let Some(kind) = fold_kind(element.kind()) {
33 let is_multiline = match element { 33 let is_multiline = match &element {
34 SyntaxElement::Node(node) => node.text().contains('\n'), 34 SyntaxElement::Node(node) => node.text().contains('\n'),
35 SyntaxElement::Token(token) => token.text().contains('\n'), 35 SyntaxElement::Token(token) => token.text().contains('\n'),
36 }; 36 };
@@ -56,7 +56,7 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec<Fold> {
56 SyntaxElement::Node(node) => { 56 SyntaxElement::Node(node) => {
57 // Fold groups of imports 57 // Fold groups of imports
58 if node.kind() == USE_ITEM && !visited_imports.contains(&node) { 58 if node.kind() == USE_ITEM && !visited_imports.contains(&node) {
59 if let Some(range) = contiguous_range_for_group(node, &mut visited_imports) { 59 if let Some(range) = contiguous_range_for_group(&node, &mut visited_imports) {
60 res.push(Fold { range, kind: FoldKind::Imports }) 60 res.push(Fold { range, kind: FoldKind::Imports })
61 } 61 }
62 } 62 }
@@ -65,7 +65,7 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec<Fold> {
65 if node.kind() == MODULE && !has_visibility(&node) && !visited_mods.contains(&node) 65 if node.kind() == MODULE && !has_visibility(&node) && !visited_mods.contains(&node)
66 { 66 {
67 if let Some(range) = 67 if let Some(range) =
68 contiguous_range_for_group_unless(node, has_visibility, &mut visited_mods) 68 contiguous_range_for_group_unless(&node, has_visibility, &mut visited_mods)
69 { 69 {
70 res.push(Fold { range, kind: FoldKind::Mods }) 70 res.push(Fold { range, kind: FoldKind::Mods })
71 } 71 }
@@ -88,24 +88,24 @@ fn fold_kind(kind: SyntaxKind) -> Option<FoldKind> {
88} 88}
89 89
90fn has_visibility(node: &SyntaxNode) -> bool { 90fn has_visibility(node: &SyntaxNode) -> bool {
91 ast::Module::cast(node).and_then(|m| m.visibility()).is_some() 91 ast::Module::cast(node.clone()).and_then(|m| m.visibility()).is_some()
92} 92}
93 93
94fn contiguous_range_for_group<'a>( 94fn contiguous_range_for_group(
95 first: &'a SyntaxNode, 95 first: &SyntaxNode,
96 visited: &mut FxHashSet<&'a SyntaxNode>, 96 visited: &mut FxHashSet<SyntaxNode>,
97) -> Option<TextRange> { 97) -> Option<TextRange> {
98 contiguous_range_for_group_unless(first, |_| false, visited) 98 contiguous_range_for_group_unless(first, |_| false, visited)
99} 99}
100 100
101fn contiguous_range_for_group_unless<'a>( 101fn contiguous_range_for_group_unless(
102 first: &'a SyntaxNode, 102 first: &SyntaxNode,
103 unless: impl Fn(&'a SyntaxNode) -> bool, 103 unless: impl Fn(&SyntaxNode) -> bool,
104 visited: &mut FxHashSet<&'a SyntaxNode>, 104 visited: &mut FxHashSet<SyntaxNode>,
105) -> Option<TextRange> { 105) -> Option<TextRange> {
106 visited.insert(first); 106 visited.insert(first.clone());
107 107
108 let mut last = first; 108 let mut last = first.clone();
109 for element in first.siblings_with_tokens(Direction::Next) { 109 for element in first.siblings_with_tokens(Direction::Next) {
110 let node = match element { 110 let node = match element {
111 SyntaxElement::Token(token) => { 111 SyntaxElement::Token(token) => {
@@ -123,15 +123,15 @@ fn contiguous_range_for_group_unless<'a>(
123 }; 123 };
124 124
125 // Stop if we find a node that doesn't belong to the group 125 // Stop if we find a node that doesn't belong to the group
126 if node.kind() != first.kind() || unless(node) { 126 if node.kind() != first.kind() || unless(&node) {
127 break; 127 break;
128 } 128 }
129 129
130 visited.insert(node); 130 visited.insert(node.clone());
131 last = node; 131 last = node;
132 } 132 }
133 133
134 if first != last { 134 if first != &last {
135 Some(TextRange::from_to(first.range().start(), last.range().end())) 135 Some(TextRange::from_to(first.range().start(), last.range().end()))
136 } else { 136 } else {
137 // The group consists of only one element, therefore it cannot be folded 137 // The group consists of only one element, therefore it cannot be folded
@@ -139,11 +139,11 @@ fn contiguous_range_for_group_unless<'a>(
139 } 139 }
140} 140}
141 141
142fn contiguous_range_for_comment<'a>( 142fn contiguous_range_for_comment(
143 first: ast::Comment<'a>, 143 first: ast::Comment,
144 visited: &mut FxHashSet<ast::Comment<'a>>, 144 visited: &mut FxHashSet<ast::Comment>,
145) -> Option<TextRange> { 145) -> Option<TextRange> {
146 visited.insert(first); 146 visited.insert(first.clone());
147 147
148 // Only fold comments of the same flavor 148 // Only fold comments of the same flavor
149 let group_kind = first.kind(); 149 let group_kind = first.kind();
@@ -151,11 +151,11 @@ fn contiguous_range_for_comment<'a>(
151 return None; 151 return None;
152 } 152 }
153 153
154 let mut last = first; 154 let mut last = first.clone();
155 for element in first.syntax().siblings_with_tokens(Direction::Next) { 155 for element in first.syntax().siblings_with_tokens(Direction::Next) {
156 match element { 156 match element {
157 SyntaxElement::Token(token) => { 157 SyntaxElement::Token(token) => {
158 if let Some(ws) = ast::Whitespace::cast(token) { 158 if let Some(ws) = ast::Whitespace::cast(token.clone()) {
159 if !ws.spans_multiple_lines() { 159 if !ws.spans_multiple_lines() {
160 // Ignore whitespace without blank lines 160 // Ignore whitespace without blank lines
161 continue; 161 continue;
@@ -163,7 +163,7 @@ fn contiguous_range_for_comment<'a>(
163 } 163 }
164 if let Some(c) = ast::Comment::cast(token) { 164 if let Some(c) = ast::Comment::cast(token) {
165 if c.kind() == group_kind { 165 if c.kind() == group_kind {
166 visited.insert(c); 166 visited.insert(c.clone());
167 last = c; 167 last = c;
168 continue; 168 continue;
169 } 169 }
@@ -193,7 +193,7 @@ mod tests {
193 fn do_check(text: &str, fold_kinds: &[FoldKind]) { 193 fn do_check(text: &str, fold_kinds: &[FoldKind]) {
194 let (ranges, text) = extract_ranges(text, "fold"); 194 let (ranges, text) = extract_ranges(text, "fold");
195 let parse = SourceFile::parse(&text); 195 let parse = SourceFile::parse(&text);
196 let folds = folding_ranges(parse.tree()); 196 let folds = folding_ranges(&parse.tree());
197 197
198 assert_eq!( 198 assert_eq!(
199 folds.len(), 199 folds.len(),
diff --git a/crates/ra_ide_api/src/goto_definition.rs b/crates/ra_ide_api/src/goto_definition.rs
index 1066bf155..82b5e3b5e 100644
--- a/crates/ra_ide_api/src/goto_definition.rs
+++ b/crates/ra_ide_api/src/goto_definition.rs
@@ -20,13 +20,13 @@ pub(crate) fn goto_definition(
20 position: FilePosition, 20 position: FilePosition,
21) -> Option<RangeInfo<Vec<NavigationTarget>>> { 21) -> Option<RangeInfo<Vec<NavigationTarget>>> {
22 let parse = db.parse(position.file_id); 22 let parse = db.parse(position.file_id);
23 let syntax = parse.tree().syntax(); 23 let syntax = parse.tree().syntax().clone();
24 if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, position.offset) { 24 if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(&syntax, position.offset) {
25 let navs = reference_definition(db, position.file_id, name_ref).to_vec(); 25 let navs = reference_definition(db, position.file_id, &name_ref).to_vec();
26 return Some(RangeInfo::new(name_ref.syntax().range(), navs.to_vec())); 26 return Some(RangeInfo::new(name_ref.syntax().range(), navs.to_vec()));
27 } 27 }
28 if let Some(name) = find_node_at_offset::<ast::Name>(syntax, position.offset) { 28 if let Some(name) = find_node_at_offset::<ast::Name>(&syntax, position.offset) {
29 let navs = name_definition(db, position.file_id, name)?; 29 let navs = name_definition(db, position.file_id, &name)?;
30 return Some(RangeInfo::new(name.syntax().range(), navs)); 30 return Some(RangeInfo::new(name.syntax().range(), navs));
31 } 31 }
32 None 32 None
@@ -94,7 +94,7 @@ pub(crate) fn name_definition(
94) -> Option<Vec<NavigationTarget>> { 94) -> Option<Vec<NavigationTarget>> {
95 let parent = name.syntax().parent()?; 95 let parent = name.syntax().parent()?;
96 96
97 if let Some(module) = ast::Module::cast(&parent) { 97 if let Some(module) = ast::Module::cast(parent.clone()) {
98 if module.has_semi() { 98 if module.has_semi() {
99 if let Some(child_module) = 99 if let Some(child_module) =
100 hir::source_binder::module_from_declaration(db, file_id, module) 100 hir::source_binder::module_from_declaration(db, file_id, module)
@@ -114,38 +114,88 @@ pub(crate) fn name_definition(
114 114
115fn named_target(file_id: FileId, node: &SyntaxNode) -> Option<NavigationTarget> { 115fn named_target(file_id: FileId, node: &SyntaxNode) -> Option<NavigationTarget> {
116 visitor() 116 visitor()
117 .visit(|node: &ast::StructDef| { 117 .visit(|node: ast::StructDef| {
118 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 118 NavigationTarget::from_named(
119 file_id,
120 &node,
121 node.doc_comment_text(),
122 node.short_label(),
123 )
119 }) 124 })
120 .visit(|node: &ast::EnumDef| { 125 .visit(|node: ast::EnumDef| {
121 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 126 NavigationTarget::from_named(
127 file_id,
128 &node,
129 node.doc_comment_text(),
130 node.short_label(),
131 )
122 }) 132 })
123 .visit(|node: &ast::EnumVariant| { 133 .visit(|node: ast::EnumVariant| {
124 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 134 NavigationTarget::from_named(
135 file_id,
136 &node,
137 node.doc_comment_text(),
138 node.short_label(),
139 )
125 }) 140 })
126 .visit(|node: &ast::FnDef| { 141 .visit(|node: ast::FnDef| {
127 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 142 NavigationTarget::from_named(
143 file_id,
144 &node,
145 node.doc_comment_text(),
146 node.short_label(),
147 )
128 }) 148 })
129 .visit(|node: &ast::TypeAliasDef| { 149 .visit(|node: ast::TypeAliasDef| {
130 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 150 NavigationTarget::from_named(
151 file_id,
152 &node,
153 node.doc_comment_text(),
154 node.short_label(),
155 )
131 }) 156 })
132 .visit(|node: &ast::ConstDef| { 157 .visit(|node: ast::ConstDef| {
133 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 158 NavigationTarget::from_named(
159 file_id,
160 &node,
161 node.doc_comment_text(),
162 node.short_label(),
163 )
134 }) 164 })
135 .visit(|node: &ast::StaticDef| { 165 .visit(|node: ast::StaticDef| {
136 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 166 NavigationTarget::from_named(
167 file_id,
168 &node,
169 node.doc_comment_text(),
170 node.short_label(),
171 )
137 }) 172 })
138 .visit(|node: &ast::TraitDef| { 173 .visit(|node: ast::TraitDef| {
139 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 174 NavigationTarget::from_named(
175 file_id,
176 &node,
177 node.doc_comment_text(),
178 node.short_label(),
179 )
140 }) 180 })
141 .visit(|node: &ast::NamedFieldDef| { 181 .visit(|node: ast::NamedFieldDef| {
142 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 182 NavigationTarget::from_named(
183 file_id,
184 &node,
185 node.doc_comment_text(),
186 node.short_label(),
187 )
143 }) 188 })
144 .visit(|node: &ast::Module| { 189 .visit(|node: ast::Module| {
145 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), node.short_label()) 190 NavigationTarget::from_named(
191 file_id,
192 &node,
193 node.doc_comment_text(),
194 node.short_label(),
195 )
146 }) 196 })
147 .visit(|node: &ast::MacroCall| { 197 .visit(|node: ast::MacroCall| {
148 NavigationTarget::from_named(file_id, node, node.doc_comment_text(), None) 198 NavigationTarget::from_named(file_id, &node, node.doc_comment_text(), None)
149 }) 199 })
150 .accept(node) 200 .accept(node)
151} 201}
diff --git a/crates/ra_ide_api/src/goto_type_definition.rs b/crates/ra_ide_api/src/goto_type_definition.rs
index 6ce5e214f..fc4b6e1af 100644
--- a/crates/ra_ide_api/src/goto_type_definition.rs
+++ b/crates/ra_ide_api/src/goto_type_definition.rs
@@ -13,15 +13,17 @@ pub(crate) fn goto_type_definition(
13 token 13 token
14 .parent() 14 .parent()
15 .ancestors() 15 .ancestors()
16 .find(|n| ast::Expr::cast(*n).is_some() || ast::Pat::cast(*n).is_some()) 16 .find(|n| ast::Expr::cast(n.clone()).is_some() || ast::Pat::cast(n.clone()).is_some())
17 })?; 17 })?;
18 18
19 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, node, None); 19 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, &node, None);
20 20
21 let ty: hir::Ty = if let Some(ty) = ast::Expr::cast(node).and_then(|e| analyzer.type_of(db, e)) 21 let ty: hir::Ty = if let Some(ty) =
22 ast::Expr::cast(node.clone()).and_then(|e| analyzer.type_of(db, &e))
22 { 23 {
23 ty 24 ty
24 } else if let Some(ty) = ast::Pat::cast(node).and_then(|p| analyzer.type_of_pat(db, p)) { 25 } else if let Some(ty) = ast::Pat::cast(node.clone()).and_then(|p| analyzer.type_of_pat(db, &p))
26 {
25 ty 27 ty
26 } else { 28 } else {
27 return None; 29 return None;
diff --git a/crates/ra_ide_api/src/hover.rs b/crates/ra_ide_api/src/hover.rs
index 253d21f48..e503bf6a9 100644
--- a/crates/ra_ide_api/src/hover.rs
+++ b/crates/ra_ide_api/src/hover.rs
@@ -6,7 +6,7 @@ use ra_syntax::{
6 visit::{visitor, Visitor}, 6 visit::{visitor, Visitor},
7 }, 7 },
8 ast::{self, DocCommentsOwner}, 8 ast::{self, DocCommentsOwner},
9 AstNode, TreeArc, 9 AstNode,
10}; 10};
11 11
12use crate::{ 12use crate::{
@@ -104,7 +104,7 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
104 104
105 let mut no_fallback = false; 105 let mut no_fallback = false;
106 106
107 match classify_name_ref(db, &analyzer, name_ref) { 107 match classify_name_ref(db, &analyzer, &name_ref) {
108 Some(Method(it)) => res.extend(from_def_source(db, it)), 108 Some(Method(it)) => res.extend(from_def_source(db, it)),
109 Some(Macro(it)) => { 109 Some(Macro(it)) => {
110 let src = it.source(db); 110 let src = it.source(db);
@@ -163,7 +163,7 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
163 163
164 if res.is_empty() && !no_fallback { 164 if res.is_empty() && !no_fallback {
165 // Fallback index based approach: 165 // Fallback index based approach:
166 let symbols = crate::symbol_index::index_resolve(db, name_ref); 166 let symbols = crate::symbol_index::index_resolve(db, &name_ref);
167 for sym in symbols { 167 for sym in symbols {
168 let docs = docs_from_symbol(db, &sym); 168 let docs = docs_from_symbol(db, &sym);
169 let desc = description_from_symbol(db, &sym); 169 let desc = description_from_symbol(db, &sym);
@@ -177,34 +177,32 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
177 } else if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), position.offset) { 177 } else if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), position.offset) {
178 if let Some(parent) = name.syntax().parent() { 178 if let Some(parent) = name.syntax().parent() {
179 let text = visitor() 179 let text = visitor()
180 .visit(|node: &ast::StructDef| { 180 .visit(|node: ast::StructDef| {
181 hover_text(node.doc_comment_text(), node.short_label()) 181 hover_text(node.doc_comment_text(), node.short_label())
182 }) 182 })
183 .visit(|node: &ast::EnumDef| { 183 .visit(|node: ast::EnumDef| hover_text(node.doc_comment_text(), node.short_label()))
184 .visit(|node: ast::EnumVariant| {
184 hover_text(node.doc_comment_text(), node.short_label()) 185 hover_text(node.doc_comment_text(), node.short_label())
185 }) 186 })
186 .visit(|node: &ast::EnumVariant| { 187 .visit(|node: ast::FnDef| hover_text(node.doc_comment_text(), node.short_label()))
188 .visit(|node: ast::TypeAliasDef| {
187 hover_text(node.doc_comment_text(), node.short_label()) 189 hover_text(node.doc_comment_text(), node.short_label())
188 }) 190 })
189 .visit(|node: &ast::FnDef| hover_text(node.doc_comment_text(), node.short_label())) 191 .visit(|node: ast::ConstDef| {
190 .visit(|node: &ast::TypeAliasDef| {
191 hover_text(node.doc_comment_text(), node.short_label()) 192 hover_text(node.doc_comment_text(), node.short_label())
192 }) 193 })
193 .visit(|node: &ast::ConstDef| { 194 .visit(|node: ast::StaticDef| {
194 hover_text(node.doc_comment_text(), node.short_label()) 195 hover_text(node.doc_comment_text(), node.short_label())
195 }) 196 })
196 .visit(|node: &ast::StaticDef| { 197 .visit(|node: ast::TraitDef| {
197 hover_text(node.doc_comment_text(), node.short_label()) 198 hover_text(node.doc_comment_text(), node.short_label())
198 }) 199 })
199 .visit(|node: &ast::TraitDef| { 200 .visit(|node: ast::NamedFieldDef| {
200 hover_text(node.doc_comment_text(), node.short_label()) 201 hover_text(node.doc_comment_text(), node.short_label())
201 }) 202 })
202 .visit(|node: &ast::NamedFieldDef| { 203 .visit(|node: ast::Module| hover_text(node.doc_comment_text(), node.short_label()))
203 hover_text(node.doc_comment_text(), node.short_label()) 204 .visit(|node: ast::MacroCall| hover_text(node.doc_comment_text(), None))
204 }) 205 .accept(&parent);
205 .visit(|node: &ast::Module| hover_text(node.doc_comment_text(), node.short_label()))
206 .visit(|node: &ast::MacroCall| hover_text(node.doc_comment_text(), None))
207 .accept(parent);
208 206
209 if let Some(text) = text { 207 if let Some(text) = text {
210 res.extend(text); 208 res.extend(text);
@@ -217,8 +215,9 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
217 } 215 }
218 216
219 if range.is_none() { 217 if range.is_none() {
220 let node = ancestors_at_offset(file.syntax(), position.offset) 218 let node = ancestors_at_offset(file.syntax(), position.offset).find(|n| {
221 .find(|n| ast::Expr::cast(*n).is_some() || ast::Pat::cast(*n).is_some())?; 219 ast::Expr::cast(n.clone()).is_some() || ast::Pat::cast(n.clone()).is_some()
220 })?;
222 let frange = FileRange { file_id: position.file_id, range: node.range() }; 221 let frange = FileRange { file_id: position.file_id, range: node.range() };
223 res.extend(type_of(db, frange).map(rust_code_markup)); 222 res.extend(type_of(db, frange).map(rust_code_markup));
224 range = Some(node.range()); 223 range = Some(node.range());
@@ -233,7 +232,7 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
233 232
234 fn from_def_source<A, D>(db: &RootDatabase, def: D) -> Option<String> 233 fn from_def_source<A, D>(db: &RootDatabase, def: D) -> Option<String>
235 where 234 where
236 D: HasSource<Ast = TreeArc<A>>, 235 D: HasSource<Ast = A>,
237 A: ast::DocCommentsOwner + ast::NameOwner + ShortLabel, 236 A: ast::DocCommentsOwner + ast::NameOwner + ShortLabel,
238 { 237 {
239 let src = def.source(db); 238 let src = def.source(db);
@@ -243,17 +242,17 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
243 242
244pub(crate) fn type_of(db: &RootDatabase, frange: FileRange) -> Option<String> { 243pub(crate) fn type_of(db: &RootDatabase, frange: FileRange) -> Option<String> {
245 let parse = db.parse(frange.file_id); 244 let parse = db.parse(frange.file_id);
246 let syntax = parse.tree().syntax(); 245 let leaf_node = find_covering_element(parse.tree().syntax(), frange.range);
247 let leaf_node = find_covering_element(syntax, frange.range);
248 // if we picked identifier, expand to pattern/expression 246 // if we picked identifier, expand to pattern/expression
249 let node = leaf_node 247 let node = leaf_node
250 .ancestors() 248 .ancestors()
251 .take_while(|it| it.range() == leaf_node.range()) 249 .take_while(|it| it.range() == leaf_node.range())
252 .find(|&it| ast::Expr::cast(it).is_some() || ast::Pat::cast(it).is_some())?; 250 .find(|it| ast::Expr::cast(it.clone()).is_some() || ast::Pat::cast(it.clone()).is_some())?;
253 let analyzer = hir::SourceAnalyzer::new(db, frange.file_id, node, None); 251 let analyzer = hir::SourceAnalyzer::new(db, frange.file_id, &node, None);
254 let ty = if let Some(ty) = ast::Expr::cast(node).and_then(|e| analyzer.type_of(db, e)) { 252 let ty = if let Some(ty) = ast::Expr::cast(node.clone()).and_then(|e| analyzer.type_of(db, &e))
253 {
255 ty 254 ty
256 } else if let Some(ty) = ast::Pat::cast(node).and_then(|p| analyzer.type_of_pat(db, p)) { 255 } else if let Some(ty) = ast::Pat::cast(node).and_then(|p| analyzer.type_of_pat(db, &p)) {
257 ty 256 ty
258 } else { 257 } else {
259 return None; 258 return None;
diff --git a/crates/ra_ide_api/src/impls.rs b/crates/ra_ide_api/src/impls.rs
index 6d69f36aa..15999d433 100644
--- a/crates/ra_ide_api/src/impls.rs
+++ b/crates/ra_ide_api/src/impls.rs
@@ -9,19 +9,19 @@ pub(crate) fn goto_implementation(
9 position: FilePosition, 9 position: FilePosition,
10) -> Option<RangeInfo<Vec<NavigationTarget>>> { 10) -> Option<RangeInfo<Vec<NavigationTarget>>> {
11 let parse = db.parse(position.file_id); 11 let parse = db.parse(position.file_id);
12 let syntax = parse.tree().syntax(); 12 let syntax = parse.tree().syntax().clone();
13 13
14 let module = source_binder::module_from_position(db, position)?; 14 let module = source_binder::module_from_position(db, position)?;
15 15
16 if let Some(nominal_def) = find_node_at_offset::<ast::NominalDef>(syntax, position.offset) { 16 if let Some(nominal_def) = find_node_at_offset::<ast::NominalDef>(&syntax, position.offset) {
17 return Some(RangeInfo::new( 17 return Some(RangeInfo::new(
18 nominal_def.syntax().range(), 18 nominal_def.syntax().range(),
19 impls_for_def(db, nominal_def, module)?, 19 impls_for_def(db, &nominal_def, module)?,
20 )); 20 ));
21 } else if let Some(trait_def) = find_node_at_offset::<ast::TraitDef>(syntax, position.offset) { 21 } else if let Some(trait_def) = find_node_at_offset::<ast::TraitDef>(&syntax, position.offset) {
22 return Some(RangeInfo::new( 22 return Some(RangeInfo::new(
23 trait_def.syntax().range(), 23 trait_def.syntax().range(),
24 impls_for_trait(db, trait_def, module)?, 24 impls_for_trait(db, &trait_def, module)?,
25 )); 25 ));
26 } 26 }
27 27
diff --git a/crates/ra_ide_api/src/join_lines.rs b/crates/ra_ide_api/src/join_lines.rs
index e20cb1370..50bcfb5b7 100644
--- a/crates/ra_ide_api/src/join_lines.rs
+++ b/crates/ra_ide_api/src/join_lines.rs
@@ -27,7 +27,7 @@ pub fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
27 SyntaxElement::Token(token) => token.parent(), 27 SyntaxElement::Token(token) => token.parent(),
28 }; 28 };
29 let mut edit = TextEditBuilder::default(); 29 let mut edit = TextEditBuilder::default();
30 for token in node.descendants_with_tokens().filter_map(|it| it.as_token()) { 30 for token in node.descendants_with_tokens().filter_map(|it| it.as_token().cloned()) {
31 let range = match range.intersection(&token.range()) { 31 let range = match range.intersection(&token.range()) {
32 Some(range) => range, 32 Some(range) => range,
33 None => continue, 33 None => continue,
@@ -37,7 +37,7 @@ pub fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
37 let pos: TextUnit = (pos as u32).into(); 37 let pos: TextUnit = (pos as u32).into();
38 let off = token.range().start() + range.start() + pos; 38 let off = token.range().start() + range.start() + pos;
39 if !edit.invalidates_offset(off) { 39 if !edit.invalidates_offset(off) {
40 remove_newline(&mut edit, token, off); 40 remove_newline(&mut edit, &token, off);
41 } 41 }
42 } 42 }
43 } 43 }
@@ -45,7 +45,7 @@ pub fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
45 edit.finish() 45 edit.finish()
46} 46}
47 47
48fn remove_newline(edit: &mut TextEditBuilder, token: SyntaxToken, offset: TextUnit) { 48fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextUnit) {
49 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 { 49 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 {
50 // The node is either the first or the last in the file 50 // The node is either the first or the last in the file
51 let suff = &token.text()[TextRange::from_to( 51 let suff = &token.text()[TextRange::from_to(
@@ -98,9 +98,10 @@ fn remove_newline(edit: &mut TextEditBuilder, token: SyntaxToken, offset: TextUn
98 TextRange::from_to(prev.range().start(), token.range().end()), 98 TextRange::from_to(prev.range().start(), token.range().end()),
99 space.to_string(), 99 space.to_string(),
100 ); 100 );
101 } else if let (Some(_), Some(next)) = 101 } else if let (Some(_), Some(next)) = (
102 (prev.as_token().and_then(ast::Comment::cast), next.as_token().and_then(ast::Comment::cast)) 102 prev.as_token().cloned().and_then(ast::Comment::cast),
103 { 103 next.as_token().cloned().and_then(ast::Comment::cast),
104 ) {
104 // Removes: newline (incl. surrounding whitespace), start of the next comment 105 // Removes: newline (incl. surrounding whitespace), start of the next comment
105 edit.delete(TextRange::from_to( 106 edit.delete(TextRange::from_to(
106 token.range().start(), 107 token.range().start(),
@@ -113,16 +114,16 @@ fn remove_newline(edit: &mut TextEditBuilder, token: SyntaxToken, offset: TextUn
113} 114}
114 115
115fn has_comma_after(node: &SyntaxNode) -> bool { 116fn has_comma_after(node: &SyntaxNode) -> bool {
116 match non_trivia_sibling(node.into(), Direction::Next) { 117 match non_trivia_sibling(node.clone().into(), Direction::Next) {
117 Some(n) => n.kind() == T![,], 118 Some(n) => n.kind() == T![,],
118 _ => false, 119 _ => false,
119 } 120 }
120} 121}
121 122
122fn join_single_expr_block(edit: &mut TextEditBuilder, token: SyntaxToken) -> Option<()> { 123fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
123 let block = ast::Block::cast(token.parent())?; 124 let block = ast::Block::cast(token.parent())?;
124 let block_expr = ast::BlockExpr::cast(block.syntax().parent()?)?; 125 let block_expr = ast::BlockExpr::cast(block.syntax().parent()?)?;
125 let expr = extract_trivial_expression(block)?; 126 let expr = extract_trivial_expression(&block)?;
126 127
127 let block_range = block_expr.syntax().range(); 128 let block_range = block_expr.syntax().range();
128 let mut buf = expr.syntax().text().to_string(); 129 let mut buf = expr.syntax().text().to_string();
@@ -139,7 +140,7 @@ fn join_single_expr_block(edit: &mut TextEditBuilder, token: SyntaxToken) -> Opt
139 Some(()) 140 Some(())
140} 141}
141 142
142fn join_single_use_tree(edit: &mut TextEditBuilder, token: SyntaxToken) -> Option<()> { 143fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
143 let use_tree_list = ast::UseTreeList::cast(token.parent())?; 144 let use_tree_list = ast::UseTreeList::cast(token.parent())?;
144 let (tree,) = use_tree_list.use_trees().collect_tuple()?; 145 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
145 edit.replace(use_tree_list.syntax().range(), tree.syntax().text().to_string()); 146 edit.replace(use_tree_list.syntax().range(), tree.syntax().text().to_string());
@@ -504,7 +505,7 @@ fn foo() {
504 fn check_join_lines_sel(before: &str, after: &str) { 505 fn check_join_lines_sel(before: &str, after: &str) {
505 let (sel, before) = extract_range(before); 506 let (sel, before) = extract_range(before);
506 let parse = SourceFile::parse(&before); 507 let parse = SourceFile::parse(&before);
507 let result = join_lines(parse.tree(), sel); 508 let result = join_lines(&parse.tree(), sel);
508 let actual = result.apply(&before); 509 let actual = result.apply(&before);
509 assert_eq_text!(after, &actual); 510 assert_eq_text!(after, &actual);
510 } 511 }
diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs
index 9f3b18d9d..c54d574bc 100644
--- a/crates/ra_ide_api/src/lib.rs
+++ b/crates/ra_ide_api/src/lib.rs
@@ -50,7 +50,7 @@ use ra_db::{
50 salsa::{self, ParallelDatabase}, 50 salsa::{self, ParallelDatabase},
51 CheckCanceled, SourceDatabase, 51 CheckCanceled, SourceDatabase,
52}; 52};
53use ra_syntax::{SourceFile, TextRange, TextUnit, TreeArc}; 53use ra_syntax::{SourceFile, TextRange, TextUnit};
54use ra_text_edit::TextEdit; 54use ra_text_edit::TextEdit;
55use relative_path::RelativePathBuf; 55use relative_path::RelativePathBuf;
56 56
@@ -325,8 +325,8 @@ impl Analysis {
325 } 325 }
326 326
327 /// Gets the syntax tree of the file. 327 /// Gets the syntax tree of the file.
328 pub fn parse(&self, file_id: FileId) -> TreeArc<SourceFile> { 328 pub fn parse(&self, file_id: FileId) -> SourceFile {
329 self.db.parse(file_id).tree().to_owned() 329 self.db.parse(file_id).tree()
330 } 330 }
331 331
332 /// Gets the file's `LineIndex`: data structure to convert between absolute 332 /// Gets the file's `LineIndex`: data structure to convert between absolute
@@ -360,7 +360,7 @@ impl Analysis {
360 let parse = self.db.parse(frange.file_id); 360 let parse = self.db.parse(frange.file_id);
361 let file_edit = SourceFileEdit { 361 let file_edit = SourceFileEdit {
362 file_id: frange.file_id, 362 file_id: frange.file_id,
363 edit: join_lines::join_lines(parse.tree(), frange.range), 363 edit: join_lines::join_lines(&parse.tree(), frange.range),
364 }; 364 };
365 SourceChange::source_file_edit("join lines", file_edit) 365 SourceChange::source_file_edit("join lines", file_edit)
366 } 366 }
@@ -393,13 +393,13 @@ impl Analysis {
393 /// file outline. 393 /// file outline.
394 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> { 394 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
395 let parse = self.db.parse(file_id); 395 let parse = self.db.parse(file_id);
396 file_structure(parse.tree()) 396 file_structure(&parse.tree())
397 } 397 }
398 398
399 /// Returns the set of folding ranges. 399 /// Returns the set of folding ranges.
400 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> { 400 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
401 let parse = self.db.parse(file_id); 401 let parse = self.db.parse(file_id);
402 folding_ranges::folding_ranges(parse.tree()) 402 folding_ranges::folding_ranges(&parse.tree())
403 } 403 }
404 404
405 /// Fuzzy searches for a symbol. 405 /// Fuzzy searches for a symbol.
diff --git a/crates/ra_ide_api/src/matching_brace.rs b/crates/ra_ide_api/src/matching_brace.rs
index 455a5c891..102327fd7 100644
--- a/crates/ra_ide_api/src/matching_brace.rs
+++ b/crates/ra_ide_api/src/matching_brace.rs
@@ -26,7 +26,7 @@ mod tests {
26 fn do_check(before: &str, after: &str) { 26 fn do_check(before: &str, after: &str) {
27 let (pos, before) = extract_offset(before); 27 let (pos, before) = extract_offset(before);
28 let parse = SourceFile::parse(&before); 28 let parse = SourceFile::parse(&before);
29 let new_pos = match matching_brace(parse.tree(), pos) { 29 let new_pos = match matching_brace(&parse.tree(), pos) {
30 None => pos, 30 None => pos,
31 Some(pos) => pos, 31 Some(pos) => pos,
32 }; 32 };
diff --git a/crates/ra_ide_api/src/name_ref_kind.rs b/crates/ra_ide_api/src/name_ref_kind.rs
index 67381c9c8..6832acf5d 100644
--- a/crates/ra_ide_api/src/name_ref_kind.rs
+++ b/crates/ra_ide_api/src/name_ref_kind.rs
@@ -26,7 +26,7 @@ pub(crate) fn classify_name_ref(
26 // Check if it is a method 26 // Check if it is a method
27 if let Some(method_call) = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast) { 27 if let Some(method_call) = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast) {
28 tested_by!(goto_definition_works_for_methods); 28 tested_by!(goto_definition_works_for_methods);
29 if let Some(func) = analyzer.resolve_method_call(method_call) { 29 if let Some(func) = analyzer.resolve_method_call(&method_call) {
30 return Some(Method(func)); 30 return Some(Method(func));
31 } 31 }
32 } 32 }
@@ -40,7 +40,7 @@ pub(crate) fn classify_name_ref(
40 .and_then(ast::MacroCall::cast) 40 .and_then(ast::MacroCall::cast)
41 { 41 {
42 tested_by!(goto_definition_works_for_macros); 42 tested_by!(goto_definition_works_for_macros);
43 if let Some(mac) = analyzer.resolve_macro_call(db, macro_call) { 43 if let Some(mac) = analyzer.resolve_macro_call(db, &macro_call) {
44 return Some(Macro(mac)); 44 return Some(Macro(mac));
45 } 45 }
46 } 46 }
@@ -48,7 +48,7 @@ pub(crate) fn classify_name_ref(
48 // It could also be a field access 48 // It could also be a field access
49 if let Some(field_expr) = name_ref.syntax().parent().and_then(ast::FieldExpr::cast) { 49 if let Some(field_expr) = name_ref.syntax().parent().and_then(ast::FieldExpr::cast) {
50 tested_by!(goto_definition_works_for_fields); 50 tested_by!(goto_definition_works_for_fields);
51 if let Some(field) = analyzer.resolve_field(field_expr) { 51 if let Some(field) = analyzer.resolve_field(&field_expr) {
52 return Some(FieldAccess(field)); 52 return Some(FieldAccess(field));
53 }; 53 };
54 } 54 }
@@ -59,7 +59,7 @@ pub(crate) fn classify_name_ref(
59 59
60 let struct_lit = field_expr.syntax().ancestors().find_map(ast::StructLit::cast); 60 let struct_lit = field_expr.syntax().ancestors().find_map(ast::StructLit::cast);
61 61
62 if let Some(ty) = struct_lit.and_then(|lit| analyzer.type_of(db, lit.into())) { 62 if let Some(ty) = struct_lit.and_then(|lit| analyzer.type_of(db, &lit.into())) {
63 if let Some((hir::AdtDef::Struct(s), _)) = ty.as_adt() { 63 if let Some((hir::AdtDef::Struct(s), _)) = ty.as_adt() {
64 let hir_path = hir::Path::from_name_ref(name_ref); 64 let hir_path = hir::Path::from_name_ref(name_ref);
65 let hir_name = hir_path.as_ident().unwrap(); 65 let hir_name = hir_path.as_ident().unwrap();
@@ -73,7 +73,7 @@ pub(crate) fn classify_name_ref(
73 73
74 // General case, a path or a local: 74 // General case, a path or a local:
75 if let Some(path) = name_ref.syntax().ancestors().find_map(ast::Path::cast) { 75 if let Some(path) = name_ref.syntax().ancestors().find_map(ast::Path::cast) {
76 if let Some(resolved) = analyzer.resolve_path(db, path) { 76 if let Some(resolved) = analyzer.resolve_path(db, &path) {
77 return match resolved { 77 return match resolved {
78 hir::PathResolution::Def(def) => Some(Def(def)), 78 hir::PathResolution::Def(def) => Some(Def(def)),
79 hir::PathResolution::LocalBinding(Either::A(pat)) => Some(Pat(pat)), 79 hir::PathResolution::LocalBinding(Either::A(pat)) => Some(Pat(pat)),
diff --git a/crates/ra_ide_api/src/references.rs b/crates/ra_ide_api/src/references.rs
index 0af1ae811..1c4cd49dc 100644
--- a/crates/ra_ide_api/src/references.rs
+++ b/crates/ra_ide_api/src/references.rs
@@ -50,11 +50,11 @@ pub(crate) fn find_all_refs(
50 position: FilePosition, 50 position: FilePosition,
51) -> Option<ReferenceSearchResult> { 51) -> Option<ReferenceSearchResult> {
52 let parse = db.parse(position.file_id); 52 let parse = db.parse(position.file_id);
53 let (binding, analyzer) = find_binding(db, parse.tree(), position)?; 53 let (binding, analyzer) = find_binding(db, &parse.tree(), position)?;
54 let declaration = NavigationTarget::from_bind_pat(position.file_id, binding); 54 let declaration = NavigationTarget::from_bind_pat(position.file_id, &binding);
55 55
56 let references = analyzer 56 let references = analyzer
57 .find_all_refs(binding) 57 .find_all_refs(&binding)
58 .into_iter() 58 .into_iter()
59 .map(move |ref_desc| FileRange { file_id: position.file_id, range: ref_desc.range }) 59 .map(move |ref_desc| FileRange { file_id: position.file_id, range: ref_desc.range })
60 .collect::<Vec<_>>(); 60 .collect::<Vec<_>>();
@@ -63,9 +63,9 @@ pub(crate) fn find_all_refs(
63 63
64 fn find_binding<'a>( 64 fn find_binding<'a>(
65 db: &RootDatabase, 65 db: &RootDatabase,
66 source_file: &'a SourceFile, 66 source_file: &SourceFile,
67 position: FilePosition, 67 position: FilePosition,
68 ) -> Option<(&'a ast::BindPat, hir::SourceAnalyzer)> { 68 ) -> Option<(ast::BindPat, hir::SourceAnalyzer)> {
69 let syntax = source_file.syntax(); 69 let syntax = source_file.syntax();
70 if let Some(binding) = find_node_at_offset::<ast::BindPat>(syntax, position.offset) { 70 if let Some(binding) = find_node_at_offset::<ast::BindPat>(syntax, position.offset) {
71 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, binding.syntax(), None); 71 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, binding.syntax(), None);
@@ -73,7 +73,7 @@ pub(crate) fn find_all_refs(
73 }; 73 };
74 let name_ref = find_node_at_offset::<ast::NameRef>(syntax, position.offset)?; 74 let name_ref = find_node_at_offset::<ast::NameRef>(syntax, position.offset)?;
75 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, name_ref.syntax(), None); 75 let analyzer = hir::SourceAnalyzer::new(db, position.file_id, name_ref.syntax(), None);
76 let resolved = analyzer.resolve_local_name(name_ref)?; 76 let resolved = analyzer.resolve_local_name(&name_ref)?;
77 if let Either::A(ptr) = resolved.ptr() { 77 if let Either::A(ptr) = resolved.ptr() {
78 if let ast::PatKind::BindPat(binding) = ptr.to_node(source_file.syntax()).kind() { 78 if let ast::PatKind::BindPat(binding) = ptr.to_node(source_file.syntax()).kind() {
79 return Some((binding, analyzer)); 79 return Some((binding, analyzer));
@@ -89,10 +89,10 @@ pub(crate) fn rename(
89 new_name: &str, 89 new_name: &str,
90) -> Option<SourceChange> { 90) -> Option<SourceChange> {
91 let parse = db.parse(position.file_id); 91 let parse = db.parse(position.file_id);
92 let syntax = parse.tree().syntax(); 92 if let Some((ast_name, ast_module)) =
93 93 find_name_and_module_at_offset(parse.tree().syntax(), position)
94 if let Some((ast_name, ast_module)) = find_name_and_module_at_offset(syntax, position) { 94 {
95 rename_mod(db, ast_name, ast_module, position, new_name) 95 rename_mod(db, &ast_name, &ast_module, position, new_name)
96 } else { 96 } else {
97 rename_reference(db, position, new_name) 97 rename_reference(db, position, new_name)
98 } 98 }
@@ -101,14 +101,10 @@ pub(crate) fn rename(
101fn find_name_and_module_at_offset( 101fn find_name_and_module_at_offset(
102 syntax: &SyntaxNode, 102 syntax: &SyntaxNode,
103 position: FilePosition, 103 position: FilePosition,
104) -> Option<(&ast::Name, &ast::Module)> { 104) -> Option<(ast::Name, ast::Module)> {
105 let ast_name = find_node_at_offset::<ast::Name>(syntax, position.offset); 105 let ast_name = find_node_at_offset::<ast::Name>(syntax, position.offset)?;
106 let ast_name_parent = ast::Module::cast(ast_name?.syntax().parent()?); 106 let ast_module = ast::Module::cast(ast_name.syntax().parent()?)?;
107 107 Some((ast_name, ast_module))
108 if let (Some(ast_module), Some(name)) = (ast_name_parent, ast_name) {
109 return Some((name, ast_module));
110 }
111 None
112} 108}
113 109
114fn source_edit_from_fileid_range( 110fn source_edit_from_fileid_range(
@@ -135,7 +131,8 @@ fn rename_mod(
135) -> Option<SourceChange> { 131) -> Option<SourceChange> {
136 let mut source_file_edits = Vec::new(); 132 let mut source_file_edits = Vec::new();
137 let mut file_system_edits = Vec::new(); 133 let mut file_system_edits = Vec::new();
138 if let Some(module) = source_binder::module_from_declaration(db, position.file_id, &ast_module) 134 if let Some(module) =
135 source_binder::module_from_declaration(db, position.file_id, ast_module.clone())
139 { 136 {
140 let src = module.definition_source(db); 137 let src = module.definition_source(db);
141 let file_id = src.file_id.as_original_file(); 138 let file_id = src.file_id.as_original_file();
diff --git a/crates/ra_ide_api/src/runnables.rs b/crates/ra_ide_api/src/runnables.rs
index 8cb859b37..200958434 100644
--- a/crates/ra_ide_api/src/runnables.rs
+++ b/crates/ra_ide_api/src/runnables.rs
@@ -26,8 +26,8 @@ pub(crate) fn runnables(db: &RootDatabase, file_id: FileId) -> Vec<Runnable> {
26 parse.tree().syntax().descendants().filter_map(|i| runnable(db, file_id, i)).collect() 26 parse.tree().syntax().descendants().filter_map(|i| runnable(db, file_id, i)).collect()
27} 27}
28 28
29fn runnable(db: &RootDatabase, file_id: FileId, item: &SyntaxNode) -> Option<Runnable> { 29fn runnable(db: &RootDatabase, file_id: FileId, item: SyntaxNode) -> Option<Runnable> {
30 if let Some(fn_def) = ast::FnDef::cast(item) { 30 if let Some(fn_def) = ast::FnDef::cast(item.clone()) {
31 runnable_fn(fn_def) 31 runnable_fn(fn_def)
32 } else if let Some(m) = ast::Module::cast(item) { 32 } else if let Some(m) = ast::Module::cast(item) {
33 runnable_mod(db, file_id, m) 33 runnable_mod(db, file_id, m)
@@ -36,8 +36,8 @@ fn runnable(db: &RootDatabase, file_id: FileId, item: &SyntaxNode) -> Option<Run
36 } 36 }
37} 37}
38 38
39fn runnable_fn(fn_def: &ast::FnDef) -> Option<Runnable> { 39fn runnable_fn(fn_def: ast::FnDef) -> Option<Runnable> {
40 let name = fn_def.name()?.text(); 40 let name = fn_def.name()?.text().clone();
41 let kind = if name == "main" { 41 let kind = if name == "main" {
42 RunnableKind::Bin 42 RunnableKind::Bin
43 } else if fn_def.has_atom_attr("test") { 43 } else if fn_def.has_atom_attr("test") {
@@ -50,7 +50,7 @@ fn runnable_fn(fn_def: &ast::FnDef) -> Option<Runnable> {
50 Some(Runnable { range: fn_def.syntax().range(), kind }) 50 Some(Runnable { range: fn_def.syntax().range(), kind })
51} 51}
52 52
53fn runnable_mod(db: &RootDatabase, file_id: FileId, module: &ast::Module) -> Option<Runnable> { 53fn runnable_mod(db: &RootDatabase, file_id: FileId, module: ast::Module) -> Option<Runnable> {
54 let has_test_function = module 54 let has_test_function = module
55 .item_list()? 55 .item_list()?
56 .items() 56 .items()
diff --git a/crates/ra_ide_api/src/status.rs b/crates/ra_ide_api/src/status.rs
index a31e15245..d533d1742 100644
--- a/crates/ra_ide_api/src/status.rs
+++ b/crates/ra_ide_api/src/status.rs
@@ -104,7 +104,7 @@ impl FromIterator<TableEntry<MacroFile, Option<Parse<SyntaxNode>>>> for SyntaxTr
104 let mut res = SyntaxTreeStats::default(); 104 let mut res = SyntaxTreeStats::default();
105 for entry in iter { 105 for entry in iter {
106 res.total += 1; 106 res.total += 1;
107 if let Some(tree) = entry.value.and_then(|it| it).map(|it| it.tree().to_owned()) { 107 if let Some(tree) = entry.value.and_then(|it| it).map(|it| it.syntax_node()) {
108 res.retained += 1; 108 res.retained += 1;
109 res.retained_size += tree.memory_size_of_subtree(); 109 res.retained_size += tree.memory_size_of_subtree();
110 } 110 }
diff --git a/crates/ra_ide_api/src/symbol_index.rs b/crates/ra_ide_api/src/symbol_index.rs
index 9b3a45319..e784b5f69 100644
--- a/crates/ra_ide_api/src/symbol_index.rs
+++ b/crates/ra_ide_api/src/symbol_index.rs
@@ -61,7 +61,7 @@ fn file_symbols(db: &impl SymbolsDatabase, file_id: FileId) -> Arc<SymbolIndex>
61 db.check_canceled(); 61 db.check_canceled();
62 let parse = db.parse(file_id); 62 let parse = db.parse(file_id);
63 63
64 let symbols = source_file_to_file_symbols(parse.tree(), file_id); 64 let symbols = source_file_to_file_symbols(&parse.tree(), file_id);
65 65
66 // FIXME: add macros here 66 // FIXME: add macros here
67 67
@@ -173,7 +173,7 @@ impl SymbolIndex {
173 files: impl ParallelIterator<Item = (FileId, Parse<ast::SourceFile>)>, 173 files: impl ParallelIterator<Item = (FileId, Parse<ast::SourceFile>)>,
174 ) -> SymbolIndex { 174 ) -> SymbolIndex {
175 let symbols = files 175 let symbols = files
176 .flat_map(|(file_id, file)| source_file_to_file_symbols(file.tree(), file_id)) 176 .flat_map(|(file_id, file)| source_file_to_file_symbols(&file.tree(), file_id))
177 .collect::<Vec<_>>(); 177 .collect::<Vec<_>>();
178 SymbolIndex::new(symbols) 178 SymbolIndex::new(symbols)
179 } 179 }
@@ -249,7 +249,7 @@ fn source_file_to_file_symbols(source_file: &SourceFile, file_id: FileId) -> Vec
249 for event in source_file.syntax().preorder() { 249 for event in source_file.syntax().preorder() {
250 match event { 250 match event {
251 WalkEvent::Enter(node) => { 251 WalkEvent::Enter(node) => {
252 if let Some(mut symbol) = to_file_symbol(node, file_id) { 252 if let Some(mut symbol) = to_file_symbol(&node, file_id) {
253 symbol.container_name = stack.last().cloned(); 253 symbol.container_name = stack.last().cloned();
254 254
255 stack.push(symbol.name.clone()); 255 stack.push(symbol.name.clone());
@@ -258,7 +258,7 @@ fn source_file_to_file_symbols(source_file: &SourceFile, file_id: FileId) -> Vec
258 } 258 }
259 259
260 WalkEvent::Leave(node) => { 260 WalkEvent::Leave(node) => {
261 if to_symbol(node).is_some() { 261 if to_symbol(&node).is_some() {
262 stack.pop(); 262 stack.pop();
263 } 263 }
264 } 264 }
@@ -269,7 +269,7 @@ fn source_file_to_file_symbols(source_file: &SourceFile, file_id: FileId) -> Vec
269} 269}
270 270
271fn to_symbol(node: &SyntaxNode) -> Option<(SmolStr, SyntaxNodePtr, TextRange)> { 271fn to_symbol(node: &SyntaxNode) -> Option<(SmolStr, SyntaxNodePtr, TextRange)> {
272 fn decl<N: NameOwner>(node: &N) -> Option<(SmolStr, SyntaxNodePtr, TextRange)> { 272 fn decl<N: NameOwner>(node: N) -> Option<(SmolStr, SyntaxNodePtr, TextRange)> {
273 let name = node.name()?; 273 let name = node.name()?;
274 let name_range = name.syntax().range(); 274 let name_range = name.syntax().range();
275 let name = name.text().clone(); 275 let name = name.text().clone();
diff --git a/crates/ra_ide_api/src/syntax_highlighting.rs b/crates/ra_ide_api/src/syntax_highlighting.rs
index eb392d5da..16a728789 100644
--- a/crates/ra_ide_api/src/syntax_highlighting.rs
+++ b/crates/ra_ide_api/src/syntax_highlighting.rs
@@ -31,8 +31,8 @@ fn is_control_keyword(kind: SyntaxKind) -> bool {
31 } 31 }
32} 32}
33 33
34fn is_variable_mutable(db: &RootDatabase, analyzer: &hir::SourceAnalyzer, pat: &ast::Pat) -> bool { 34fn is_variable_mutable(db: &RootDatabase, analyzer: &hir::SourceAnalyzer, pat: ast::Pat) -> bool {
35 let ty = analyzer.type_of_pat(db, pat).unwrap_or(Ty::Unknown); 35 let ty = analyzer.type_of_pat(db, &pat).unwrap_or(Ty::Unknown);
36 let is_ty_mut = { 36 let is_ty_mut = {
37 if let Some((_, mutability)) = ty.as_reference() { 37 if let Some((_, mutability)) = ty.as_reference() {
38 match mutability { 38 match mutability {
@@ -55,7 +55,7 @@ fn is_variable_mutable(db: &RootDatabase, analyzer: &hir::SourceAnalyzer, pat: &
55pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> { 55pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> {
56 let _p = profile("highlight"); 56 let _p = profile("highlight");
57 let parse = db.parse(file_id); 57 let parse = db.parse(file_id);
58 let root = parse.tree().syntax(); 58 let root = parse.tree().syntax().clone();
59 59
60 fn calc_binding_hash(file_id: FileId, text: &SmolStr, shadow_count: u32) -> u64 { 60 fn calc_binding_hash(file_id: FileId, text: &SmolStr, shadow_count: u32) -> u64 {
61 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 { 61 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
@@ -70,6 +70,7 @@ pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRa
70 } 70 }
71 71
72 // Visited nodes to handle highlighting priorities 72 // Visited nodes to handle highlighting priorities
73 // FIXME: retain only ranges here
73 let mut highlighted: FxHashSet<SyntaxElement> = FxHashSet::default(); 74 let mut highlighted: FxHashSet<SyntaxElement> = FxHashSet::default();
74 let mut bindings_shadow_count: FxHashMap<SmolStr, u32> = FxHashMap::default(); 75 let mut bindings_shadow_count: FxHashMap<SmolStr, u32> = FxHashMap::default();
75 76
@@ -84,14 +85,14 @@ pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRa
84 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => "string", 85 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => "string",
85 ATTR => "attribute", 86 ATTR => "attribute",
86 NAME_REF => { 87 NAME_REF => {
87 if let Some(name_ref) = node.as_node().and_then(ast::NameRef::cast) { 88 if let Some(name_ref) = node.as_node().cloned().and_then(ast::NameRef::cast) {
88 // FIXME: revisit this after #1340 89 // FIXME: revisit this after #1340
89 use crate::name_ref_kind::{classify_name_ref, NameRefKind::*}; 90 use crate::name_ref_kind::{classify_name_ref, NameRefKind::*};
90 use hir::{ImplItem, ModuleDef}; 91 use hir::{ImplItem, ModuleDef};
91 92
92 // FIXME: try to reuse the SourceAnalyzers 93 // FIXME: try to reuse the SourceAnalyzers
93 let analyzer = hir::SourceAnalyzer::new(db, file_id, name_ref.syntax(), None); 94 let analyzer = hir::SourceAnalyzer::new(db, file_id, name_ref.syntax(), None);
94 match classify_name_ref(db, &analyzer, name_ref) { 95 match classify_name_ref(db, &analyzer, &name_ref) {
95 Some(Method(_)) => "function", 96 Some(Method(_)) => "function",
96 Some(Macro(_)) => "macro", 97 Some(Macro(_)) => "macro",
97 Some(FieldAccess(_)) => "field", 98 Some(FieldAccess(_)) => "field",
@@ -113,13 +114,13 @@ pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRa
113 Some(Pat(ptr)) => { 114 Some(Pat(ptr)) => {
114 binding_hash = Some({ 115 binding_hash = Some({
115 let text = 116 let text =
116 ptr.syntax_node_ptr().to_node(root).text().to_smol_string(); 117 ptr.syntax_node_ptr().to_node(&root).text().to_smol_string();
117 let shadow_count = 118 let shadow_count =
118 bindings_shadow_count.entry(text.clone()).or_default(); 119 bindings_shadow_count.entry(text.clone()).or_default();
119 calc_binding_hash(file_id, &text, *shadow_count) 120 calc_binding_hash(file_id, &text, *shadow_count)
120 }); 121 });
121 122
122 if is_variable_mutable(db, &analyzer, ptr.to_node(root)) { 123 if is_variable_mutable(db, &analyzer, ptr.to_node(&root)) {
123 "variable.mut" 124 "variable.mut"
124 } else { 125 } else {
125 "variable" 126 "variable"
@@ -134,7 +135,7 @@ pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRa
134 } 135 }
135 } 136 }
136 NAME => { 137 NAME => {
137 if let Some(name) = node.as_node().and_then(ast::Name::cast) { 138 if let Some(name) = node.as_node().cloned().and_then(ast::Name::cast) {
138 let analyzer = hir::SourceAnalyzer::new(db, file_id, name.syntax(), None); 139 let analyzer = hir::SourceAnalyzer::new(db, file_id, name.syntax(), None);
139 if let Some(pat) = name.syntax().ancestors().find_map(ast::Pat::cast) { 140 if let Some(pat) = name.syntax().ancestors().find_map(ast::Pat::cast) {
140 binding_hash = Some({ 141 binding_hash = Some({
@@ -176,12 +177,11 @@ pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRa
176 k if is_control_keyword(k) => "keyword.control", 177 k if is_control_keyword(k) => "keyword.control",
177 k if k.is_keyword() => "keyword", 178 k if k.is_keyword() => "keyword",
178 _ => { 179 _ => {
179 // let analyzer = hir::SourceAnalyzer::new(db, file_id, name_ref.syntax(), None); 180 if let Some(macro_call) = node.as_node().cloned().and_then(ast::MacroCall::cast) {
180 if let Some(macro_call) = node.as_node().and_then(ast::MacroCall::cast) {
181 if let Some(path) = macro_call.path() { 181 if let Some(path) = macro_call.path() {
182 if let Some(segment) = path.segment() { 182 if let Some(segment) = path.segment() {
183 if let Some(name_ref) = segment.name_ref() { 183 if let Some(name_ref) = segment.name_ref() {
184 highlighted.insert(name_ref.syntax().into()); 184 highlighted.insert(name_ref.syntax().clone().into());
185 let range_start = name_ref.syntax().range().start(); 185 let range_start = name_ref.syntax().range().start();
186 let mut range_end = name_ref.syntax().range().end(); 186 let mut range_end = name_ref.syntax().range().end();
187 for sibling in path.syntax().siblings_with_tokens(Direction::Next) { 187 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
@@ -230,7 +230,8 @@ pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: boo
230 let mut buf = String::new(); 230 let mut buf = String::new();
231 buf.push_str(&STYLE); 231 buf.push_str(&STYLE);
232 buf.push_str("<pre><code>"); 232 buf.push_str("<pre><code>");
233 let tokens = parse.tree().syntax().descendants_with_tokens().filter_map(|it| it.as_token()); 233 let tokens =
234 parse.tree().syntax().descendants_with_tokens().filter_map(|it| it.as_token().cloned());
234 for token in tokens { 235 for token in tokens {
235 could_intersect.retain(|it| token.range().start() <= it.range.end()); 236 could_intersect.retain(|it| token.range().start() <= it.range.end());
236 while let Some(r) = ranges.get(frontier) { 237 while let Some(r) = ranges.get(frontier) {
diff --git a/crates/ra_ide_api/src/syntax_tree.rs b/crates/ra_ide_api/src/syntax_tree.rs
index b3e08c041..3d7373d02 100644
--- a/crates/ra_ide_api/src/syntax_tree.rs
+++ b/crates/ra_ide_api/src/syntax_tree.rs
@@ -18,7 +18,7 @@ pub(crate) fn syntax_tree(
18 let node = match algo::find_covering_element(parse.tree().syntax(), text_range) { 18 let node = match algo::find_covering_element(parse.tree().syntax(), text_range) {
19 SyntaxElement::Node(node) => node, 19 SyntaxElement::Node(node) => node,
20 SyntaxElement::Token(token) => { 20 SyntaxElement::Token(token) => {
21 if let Some(tree) = syntax_tree_for_string(token, text_range) { 21 if let Some(tree) = syntax_tree_for_string(&token, text_range) {
22 return tree; 22 return tree;
23 } 23 }
24 token.parent() 24 token.parent()
@@ -33,7 +33,7 @@ pub(crate) fn syntax_tree(
33 33
34/// Attempts parsing the selected contents of a string literal 34/// Attempts parsing the selected contents of a string literal
35/// as rust syntax and returns its syntax tree 35/// as rust syntax and returns its syntax tree
36fn syntax_tree_for_string(token: SyntaxToken, text_range: TextRange) -> Option<String> { 36fn syntax_tree_for_string(token: &SyntaxToken, text_range: TextRange) -> Option<String> {
37 // When the range is inside a string 37 // When the range is inside a string
38 // we'll attempt parsing it as rust syntax 38 // we'll attempt parsing it as rust syntax
39 // to provide the syntax tree of the contents of the string 39 // to provide the syntax tree of the contents of the string
@@ -43,7 +43,7 @@ fn syntax_tree_for_string(token: SyntaxToken, text_range: TextRange) -> Option<S
43 } 43 }
44} 44}
45 45
46fn syntax_tree_for_token(node: SyntaxToken, text_range: TextRange) -> Option<String> { 46fn syntax_tree_for_token(node: &SyntaxToken, text_range: TextRange) -> Option<String> {
47 // Range of the full node 47 // Range of the full node
48 let node_range = node.range(); 48 let node_range = node.range();
49 let text = node.text().to_string(); 49 let text = node.text().to_string();
diff --git a/crates/ra_ide_api/src/typing.rs b/crates/ra_ide_api/src/typing.rs
index 01eb32b2f..ad0ababcc 100644
--- a/crates/ra_ide_api/src/typing.rs
+++ b/crates/ra_ide_api/src/typing.rs
@@ -1,15 +1,16 @@
1use crate::{db::RootDatabase, SourceChange, SourceFileEdit};
2use ra_db::{FilePosition, SourceDatabase}; 1use ra_db::{FilePosition, SourceDatabase};
3use ra_fmt::leading_indent; 2use ra_fmt::leading_indent;
4use ra_syntax::{ 3use ra_syntax::{
5 algo::{find_node_at_offset, find_token_at_offset, TokenAtOffset}, 4 algo::{find_node_at_offset, find_token_at_offset, TokenAtOffset},
6 ast::{self, AstToken}, 5 ast::{self, AstToken},
7 AstNode, SourceFile, 6 AstNode, SmolStr, SourceFile,
8 SyntaxKind::*, 7 SyntaxKind::*,
9 SyntaxToken, TextRange, TextUnit, 8 SyntaxToken, TextRange, TextUnit,
10}; 9};
11use ra_text_edit::{TextEdit, TextEditBuilder}; 10use ra_text_edit::{TextEdit, TextEditBuilder};
12 11
12use crate::{db::RootDatabase, SourceChange, SourceFileEdit};
13
13pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> { 14pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
14 let parse = db.parse(position.file_id); 15 let parse = db.parse(position.file_id);
15 let file = parse.tree(); 16 let file = parse.tree();
@@ -43,15 +44,15 @@ pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<Sour
43 ) 44 )
44} 45}
45 46
46fn node_indent<'a>(file: &'a SourceFile, token: SyntaxToken) -> Option<&'a str> { 47fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
47 let ws = match find_token_at_offset(file.syntax(), token.range().start()) { 48 let ws = match find_token_at_offset(file.syntax(), token.range().start()) {
48 TokenAtOffset::Between(l, r) => { 49 TokenAtOffset::Between(l, r) => {
49 assert!(r == token); 50 assert!(r == *token);
50 l 51 l
51 } 52 }
52 TokenAtOffset::Single(n) => { 53 TokenAtOffset::Single(n) => {
53 assert!(n == token); 54 assert!(n == *token);
54 return Some(""); 55 return Some("".into());
55 } 56 }
56 TokenAtOffset::None => unreachable!(), 57 TokenAtOffset::None => unreachable!(),
57 }; 58 };
@@ -60,12 +61,12 @@ fn node_indent<'a>(file: &'a SourceFile, token: SyntaxToken) -> Option<&'a str>
60 } 61 }
61 let text = ws.text(); 62 let text = ws.text();
62 let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0); 63 let pos = text.rfind('\n').map(|it| it + 1).unwrap_or(0);
63 Some(&text[pos..]) 64 Some(text[pos..].into())
64} 65}
65 66
66pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<TextEdit> { 67pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<TextEdit> {
67 assert_eq!(file.syntax().text().char_at(eq_offset), Some('=')); 68 assert_eq!(file.syntax().text().char_at(eq_offset), Some('='));
68 let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?; 69 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?;
69 if let_stmt.has_semi() { 70 if let_stmt.has_semi() {
70 return None; 71 return None;
71 } 72 }
@@ -141,7 +142,7 @@ mod tests {
141 edit.insert(offset, "=".to_string()); 142 edit.insert(offset, "=".to_string());
142 let before = edit.finish().apply(&before); 143 let before = edit.finish().apply(&before);
143 let parse = SourceFile::parse(&before); 144 let parse = SourceFile::parse(&before);
144 if let Some(result) = on_eq_typed(parse.tree(), offset) { 145 if let Some(result) = on_eq_typed(&parse.tree(), offset) {
145 let actual = result.apply(&before); 146 let actual = result.apply(&before);
146 assert_eq_text!(after, &actual); 147 assert_eq_text!(after, &actual);
147 } else { 148 } else {
diff --git a/crates/ra_mbe/src/mbe_expander.rs b/crates/ra_mbe/src/mbe_expander.rs
index c7c06c7fd..f185aecb7 100644
--- a/crates/ra_mbe/src/mbe_expander.rs
+++ b/crates/ra_mbe/src/mbe_expander.rs
@@ -599,7 +599,8 @@ mod tests {
599 let macro_definition = 599 let macro_definition =
600 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); 600 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
601 601
602 let (definition_tt, _) = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap(); 602 let (definition_tt, _) =
603 ast_to_token_tree(&macro_definition.token_tree().unwrap()).unwrap();
603 crate::MacroRules::parse(&definition_tt).unwrap() 604 crate::MacroRules::parse(&definition_tt).unwrap()
604 } 605 }
605 606
@@ -611,7 +612,8 @@ mod tests {
611 let macro_invocation = 612 let macro_invocation =
612 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); 613 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
613 614
614 let (invocation_tt, _) = ast_to_token_tree(macro_invocation.token_tree().unwrap()).unwrap(); 615 let (invocation_tt, _) =
616 ast_to_token_tree(&macro_invocation.token_tree().unwrap()).unwrap();
615 617
616 expand_rule(&rules.rules[0], &invocation_tt) 618 expand_rule(&rules.rules[0], &invocation_tt)
617 } 619 }
diff --git a/crates/ra_mbe/src/mbe_parser.rs b/crates/ra_mbe/src/mbe_parser.rs
index cddb4a7b4..954b84d9d 100644
--- a/crates/ra_mbe/src/mbe_parser.rs
+++ b/crates/ra_mbe/src/mbe_parser.rs
@@ -179,7 +179,8 @@ mod tests {
179 let macro_definition = 179 let macro_definition =
180 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); 180 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
181 181
182 let (definition_tt, _) = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap(); 182 let (definition_tt, _) =
183 ast_to_token_tree(&macro_definition.token_tree().unwrap()).unwrap();
183 parse(&definition_tt) 184 parse(&definition_tt)
184 } 185 }
185 186
diff --git a/crates/ra_mbe/src/syntax_bridge.rs b/crates/ra_mbe/src/syntax_bridge.rs
index bfc351f81..64ed6a517 100644
--- a/crates/ra_mbe/src/syntax_bridge.rs
+++ b/crates/ra_mbe/src/syntax_bridge.rs
@@ -2,7 +2,7 @@ use crate::subtree_source::SubtreeTokenSource;
2use crate::ExpandError; 2use crate::ExpandError;
3use ra_parser::{ParseError, TreeSink}; 3use ra_parser::{ParseError, TreeSink};
4use ra_syntax::{ 4use ra_syntax::{
5 ast, AstNode, Parse, SmolStr, SyntaxElement, SyntaxKind, SyntaxKind::*, SyntaxNode, 5 ast, AstNode, AstToken, Parse, SmolStr, SyntaxElement, SyntaxKind, SyntaxKind::*, SyntaxNode,
6 SyntaxTreeBuilder, TextRange, TextUnit, T, 6 SyntaxTreeBuilder, TextRange, TextUnit, T,
7}; 7};
8use tt::buffer::{Cursor, TokenBuffer}; 8use tt::buffer::{Cursor, TokenBuffer};
@@ -116,8 +116,6 @@ impl TokenMap {
116/// and strips the ending `*/` 116/// and strips the ending `*/`
117/// And then quote the string, which is needed to convert to `tt::Literal` 117/// And then quote the string, which is needed to convert to `tt::Literal`
118fn doc_comment_text(comment: &ast::Comment) -> SmolStr { 118fn doc_comment_text(comment: &ast::Comment) -> SmolStr {
119 use ast::AstToken;
120
121 let prefix_len = comment.prefix().len(); 119 let prefix_len = comment.prefix().len();
122 let mut text = &comment.text()[prefix_len..]; 120 let mut text = &comment.text()[prefix_len..];
123 121
@@ -132,9 +130,8 @@ fn doc_comment_text(comment: &ast::Comment) -> SmolStr {
132 text.into() 130 text.into()
133} 131}
134 132
135fn convert_doc_comment<'a>(token: &ra_syntax::SyntaxToken<'a>) -> Option<Vec<tt::TokenTree>> { 133fn convert_doc_comment(token: &ra_syntax::SyntaxToken) -> Option<Vec<tt::TokenTree>> {
136 use ast::AstToken; 134 let comment = ast::Comment::cast(token.clone())?;
137 let comment = ast::Comment::cast(*token)?;
138 let doc = comment.kind().doc?; 135 let doc = comment.kind().doc?;
139 136
140 // Make `doc="\" Comments\"" 137 // Make `doc="\" Comments\""
@@ -245,7 +242,7 @@ fn convert_tt(
245 } 242 }
246 } 243 }
247 SyntaxElement::Node(node) => { 244 SyntaxElement::Node(node) => {
248 let child = convert_tt(token_map, global_offset, node)?.into(); 245 let child = convert_tt(token_map, global_offset, &node)?.into();
249 token_trees.push(child); 246 token_trees.push(child);
250 } 247 }
251 }; 248 };
diff --git a/crates/ra_mbe/src/tests.rs b/crates/ra_mbe/src/tests.rs
index 419b2c099..38a31109d 100644
--- a/crates/ra_mbe/src/tests.rs
+++ b/crates/ra_mbe/src/tests.rs
@@ -37,8 +37,8 @@ impl_froms!(TokenTree: Leaf, Subtree);
37 let macro_invocation = 37 let macro_invocation =
38 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); 38 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
39 39
40 let (definition_tt, _) = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap(); 40 let (definition_tt, _) = ast_to_token_tree(&macro_definition.token_tree().unwrap()).unwrap();
41 let (invocation_tt, _) = ast_to_token_tree(macro_invocation.token_tree().unwrap()).unwrap(); 41 let (invocation_tt, _) = ast_to_token_tree(&macro_invocation.token_tree().unwrap()).unwrap();
42 let rules = crate::MacroRules::parse(&definition_tt).unwrap(); 42 let rules = crate::MacroRules::parse(&definition_tt).unwrap();
43 let expansion = rules.expand(&invocation_tt).unwrap(); 43 let expansion = rules.expand(&invocation_tt).unwrap();
44 assert_eq!( 44 assert_eq!(
@@ -53,7 +53,7 @@ pub(crate) fn create_rules(macro_definition: &str) -> MacroRules {
53 let macro_definition = 53 let macro_definition =
54 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); 54 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
55 55
56 let (definition_tt, _) = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap(); 56 let (definition_tt, _) = ast_to_token_tree(&macro_definition.token_tree().unwrap()).unwrap();
57 crate::MacroRules::parse(&definition_tt).unwrap() 57 crate::MacroRules::parse(&definition_tt).unwrap()
58} 58}
59 59
@@ -62,34 +62,25 @@ pub(crate) fn expand(rules: &MacroRules, invocation: &str) -> tt::Subtree {
62 let macro_invocation = 62 let macro_invocation =
63 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); 63 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
64 64
65 let (invocation_tt, _) = ast_to_token_tree(macro_invocation.token_tree().unwrap()).unwrap(); 65 let (invocation_tt, _) = ast_to_token_tree(&macro_invocation.token_tree().unwrap()).unwrap();
66 66
67 rules.expand(&invocation_tt).unwrap() 67 rules.expand(&invocation_tt).unwrap()
68} 68}
69 69
70pub(crate) fn expand_to_items( 70pub(crate) fn expand_to_items(rules: &MacroRules, invocation: &str) -> ast::MacroItems {
71 rules: &MacroRules,
72 invocation: &str,
73) -> ra_syntax::TreeArc<ast::MacroItems> {
74 let expanded = expand(rules, invocation); 71 let expanded = expand(rules, invocation);
75 token_tree_to_macro_items(&expanded).unwrap().tree().to_owned() 72 token_tree_to_macro_items(&expanded).unwrap().tree()
76} 73}
77 74
78#[allow(unused)] 75#[allow(unused)]
79pub(crate) fn expand_to_stmts( 76pub(crate) fn expand_to_stmts(rules: &MacroRules, invocation: &str) -> ast::MacroStmts {
80 rules: &MacroRules,
81 invocation: &str,
82) -> ra_syntax::TreeArc<ast::MacroStmts> {
83 let expanded = expand(rules, invocation); 77 let expanded = expand(rules, invocation);
84 token_tree_to_macro_stmts(&expanded).unwrap().tree().to_owned() 78 token_tree_to_macro_stmts(&expanded).unwrap().tree()
85} 79}
86 80
87pub(crate) fn expand_to_expr( 81pub(crate) fn expand_to_expr(rules: &MacroRules, invocation: &str) -> ast::Expr {
88 rules: &MacroRules,
89 invocation: &str,
90) -> ra_syntax::TreeArc<ast::Expr> {
91 let expanded = expand(rules, invocation); 82 let expanded = expand(rules, invocation);
92 token_tree_to_expr(&expanded).unwrap().tree().to_owned() 83 token_tree_to_expr(&expanded).unwrap().tree()
93} 84}
94 85
95pub(crate) fn text_to_tokentree(text: &str) -> tt::Subtree { 86pub(crate) fn text_to_tokentree(text: &str) -> tt::Subtree {
@@ -97,7 +88,7 @@ pub(crate) fn text_to_tokentree(text: &str) -> tt::Subtree {
97 let wrapped = format!("wrap_macro!( {} )", text); 88 let wrapped = format!("wrap_macro!( {} )", text);
98 let wrapped = ast::SourceFile::parse(&wrapped); 89 let wrapped = ast::SourceFile::parse(&wrapped);
99 let wrapped = wrapped.tree().syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); 90 let wrapped = wrapped.tree().syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
100 let mut wrapped = ast_to_token_tree(wrapped).unwrap().0; 91 let mut wrapped = ast_to_token_tree(&wrapped).unwrap().0;
101 wrapped.delimiter = tt::Delimiter::None; 92 wrapped.delimiter = tt::Delimiter::None;
102 93
103 wrapped 94 wrapped
@@ -164,8 +155,8 @@ pub(crate) fn assert_expansion(
164 155
165 let (expanded_tree, expected_tree) = match kind { 156 let (expanded_tree, expected_tree) = match kind {
166 MacroKind::Items => { 157 MacroKind::Items => {
167 let expanded_tree = token_tree_to_macro_items(&expanded).unwrap().tree().to_owned(); 158 let expanded_tree = token_tree_to_macro_items(&expanded).unwrap().tree();
168 let expected_tree = token_tree_to_macro_items(&expected).unwrap().tree().to_owned(); 159 let expected_tree = token_tree_to_macro_items(&expected).unwrap().tree();
169 160
170 ( 161 (
171 debug_dump_ignore_spaces(expanded_tree.syntax()).trim().to_string(), 162 debug_dump_ignore_spaces(expanded_tree.syntax()).trim().to_string(),
@@ -174,8 +165,8 @@ pub(crate) fn assert_expansion(
174 } 165 }
175 166
176 MacroKind::Stmts => { 167 MacroKind::Stmts => {
177 let expanded_tree = token_tree_to_macro_stmts(&expanded).unwrap().tree().to_owned(); 168 let expanded_tree = token_tree_to_macro_stmts(&expanded).unwrap().tree();
178 let expected_tree = token_tree_to_macro_stmts(&expected).unwrap().tree().to_owned(); 169 let expected_tree = token_tree_to_macro_stmts(&expected).unwrap().tree();
179 170
180 ( 171 (
181 debug_dump_ignore_spaces(expanded_tree.syntax()).trim().to_string(), 172 debug_dump_ignore_spaces(expanded_tree.syntax()).trim().to_string(),
@@ -419,7 +410,7 @@ fn test_expand_to_item_list() {
419 ", 410 ",
420 ); 411 );
421 let expansion = expand(&rules, "structs!(Foo, Bar);"); 412 let expansion = expand(&rules, "structs!(Foo, Bar);");
422 let tree = token_tree_to_macro_items(&expansion).unwrap().tree().to_owned(); 413 let tree = token_tree_to_macro_items(&expansion).unwrap().tree();
423 assert_eq!( 414 assert_eq!(
424 tree.syntax().debug_dump().trim(), 415 tree.syntax().debug_dump().trim(),
425 r#" 416 r#"
@@ -537,7 +528,7 @@ fn test_tt_to_stmts() {
537 ); 528 );
538 529
539 let expanded = expand(&rules, "foo!{}"); 530 let expanded = expand(&rules, "foo!{}");
540 let stmts = token_tree_to_macro_stmts(&expanded).unwrap().tree().to_owned(); 531 let stmts = token_tree_to_macro_stmts(&expanded).unwrap().tree();
541 532
542 assert_eq!( 533 assert_eq!(
543 stmts.syntax().debug_dump().trim(), 534 stmts.syntax().debug_dump().trim(),
diff --git a/crates/ra_syntax/Cargo.toml b/crates/ra_syntax/Cargo.toml
index 37a91ea35..a5565de33 100644
--- a/crates/ra_syntax/Cargo.toml
+++ b/crates/ra_syntax/Cargo.toml
@@ -10,7 +10,7 @@ repository = "https://github.com/rust-analyzer/rust-analyzer"
10[dependencies] 10[dependencies]
11unicode-xid = "0.1.0" 11unicode-xid = "0.1.0"
12itertools = "0.8.0" 12itertools = "0.8.0"
13rowan = "0.5.0" 13rowan = "0.5.6"
14 14
15# ideally, `serde` should be enabled by `ra_lsp_server`, but we enable it here 15# ideally, `serde` should be enabled by `ra_lsp_server`, but we enable it here
16# to reduce number of compilations 16# to reduce number of compilations
diff --git a/crates/ra_syntax/src/algo.rs b/crates/ra_syntax/src/algo.rs
index fad8da132..e2de5e0e3 100644
--- a/crates/ra_syntax/src/algo.rs
+++ b/crates/ra_syntax/src/algo.rs
@@ -9,8 +9,8 @@ pub use rowan::TokenAtOffset;
9pub fn find_token_at_offset(node: &SyntaxNode, offset: TextUnit) -> TokenAtOffset<SyntaxToken> { 9pub fn find_token_at_offset(node: &SyntaxNode, offset: TextUnit) -> TokenAtOffset<SyntaxToken> {
10 match node.0.token_at_offset(offset) { 10 match node.0.token_at_offset(offset) {
11 TokenAtOffset::None => TokenAtOffset::None, 11 TokenAtOffset::None => TokenAtOffset::None,
12 TokenAtOffset::Single(n) => TokenAtOffset::Single(n.into()), 12 TokenAtOffset::Single(n) => TokenAtOffset::Single(SyntaxToken(n)),
13 TokenAtOffset::Between(l, r) => TokenAtOffset::Between(l.into(), r.into()), 13 TokenAtOffset::Between(l, r) => TokenAtOffset::Between(SyntaxToken(l), SyntaxToken(r)),
14 } 14 }
15} 15}
16 16
@@ -22,7 +22,7 @@ pub fn find_token_at_offset(node: &SyntaxNode, offset: TextUnit) -> TokenAtOffse
22pub fn ancestors_at_offset( 22pub fn ancestors_at_offset(
23 node: &SyntaxNode, 23 node: &SyntaxNode,
24 offset: TextUnit, 24 offset: TextUnit,
25) -> impl Iterator<Item = &SyntaxNode> { 25) -> impl Iterator<Item = SyntaxNode> {
26 find_token_at_offset(node, offset) 26 find_token_at_offset(node, offset)
27 .map(|token| token.parent().ancestors()) 27 .map(|token| token.parent().ancestors())
28 .kmerge_by(|node1, node2| node1.range().len() < node2.range().len()) 28 .kmerge_by(|node1, node2| node1.range().len() < node2.range().len())
@@ -37,7 +37,7 @@ pub fn ancestors_at_offset(
37/// ``` 37/// ```
38/// 38///
39/// then the shorter node will be silently preferred. 39/// then the shorter node will be silently preferred.
40pub fn find_node_at_offset<N: AstNode>(syntax: &SyntaxNode, offset: TextUnit) -> Option<&N> { 40pub fn find_node_at_offset<N: AstNode>(syntax: &SyntaxNode, offset: TextUnit) -> Option<N> {
41 ancestors_at_offset(syntax, offset).find_map(N::cast) 41 ancestors_at_offset(syntax, offset).find_map(N::cast)
42} 42}
43 43
@@ -59,5 +59,5 @@ pub fn non_trivia_sibling(element: SyntaxElement, direction: Direction) -> Optio
59} 59}
60 60
61pub fn find_covering_element(root: &SyntaxNode, range: TextRange) -> SyntaxElement { 61pub fn find_covering_element(root: &SyntaxNode, range: TextRange) -> SyntaxElement {
62 root.0.covering_node(range).into() 62 SyntaxElement::new(root.0.covering_node(range))
63} 63}
diff --git a/crates/ra_syntax/src/algo/visit.rs b/crates/ra_syntax/src/algo/visit.rs
index 81a99228f..87bd15cc0 100644
--- a/crates/ra_syntax/src/algo/visit.rs
+++ b/crates/ra_syntax/src/algo/visit.rs
@@ -16,7 +16,7 @@ pub trait Visitor<'a>: Sized {
16 fn visit<N, F>(self, f: F) -> Vis<Self, N, F> 16 fn visit<N, F>(self, f: F) -> Vis<Self, N, F>
17 where 17 where
18 N: AstNode + 'a, 18 N: AstNode + 'a,
19 F: FnOnce(&'a N) -> Self::Output, 19 F: FnOnce(N) -> Self::Output,
20 { 20 {
21 Vis { inner: self, f, ph: PhantomData } 21 Vis { inner: self, f, ph: PhantomData }
22 } 22 }
@@ -29,7 +29,7 @@ pub trait VisitorCtx<'a>: Sized {
29 fn visit<N, F>(self, f: F) -> VisCtx<Self, N, F> 29 fn visit<N, F>(self, f: F) -> VisCtx<Self, N, F>
30 where 30 where
31 N: AstNode + 'a, 31 N: AstNode + 'a,
32 F: FnOnce(&'a N, Self::Ctx) -> Self::Output, 32 F: FnOnce(N, Self::Ctx) -> Self::Output,
33 { 33 {
34 VisCtx { inner: self, f, ph: PhantomData } 34 VisCtx { inner: self, f, ph: PhantomData }
35 } 35 }
@@ -74,13 +74,13 @@ impl<'a, V, N, F> Visitor<'a> for Vis<V, N, F>
74where 74where
75 V: Visitor<'a>, 75 V: Visitor<'a>,
76 N: AstNode + 'a, 76 N: AstNode + 'a,
77 F: FnOnce(&'a N) -> <V as Visitor<'a>>::Output, 77 F: FnOnce(N) -> <V as Visitor<'a>>::Output,
78{ 78{
79 type Output = <V as Visitor<'a>>::Output; 79 type Output = <V as Visitor<'a>>::Output;
80 80
81 fn accept(self, node: &'a SyntaxNode) -> Option<Self::Output> { 81 fn accept(self, node: &'a SyntaxNode) -> Option<Self::Output> {
82 let Vis { inner, f, .. } = self; 82 let Vis { inner, f, .. } = self;
83 inner.accept(node).or_else(|| N::cast(node).map(f)) 83 inner.accept(node).or_else(|| N::cast(node.clone()).map(f))
84 } 84 }
85} 85}
86 86
@@ -95,14 +95,14 @@ impl<'a, V, N, F> VisitorCtx<'a> for VisCtx<V, N, F>
95where 95where
96 V: VisitorCtx<'a>, 96 V: VisitorCtx<'a>,
97 N: AstNode + 'a, 97 N: AstNode + 'a,
98 F: FnOnce(&'a N, <V as VisitorCtx<'a>>::Ctx) -> <V as VisitorCtx<'a>>::Output, 98 F: FnOnce(N, <V as VisitorCtx<'a>>::Ctx) -> <V as VisitorCtx<'a>>::Output,
99{ 99{
100 type Output = <V as VisitorCtx<'a>>::Output; 100 type Output = <V as VisitorCtx<'a>>::Output;
101 type Ctx = <V as VisitorCtx<'a>>::Ctx; 101 type Ctx = <V as VisitorCtx<'a>>::Ctx;
102 102
103 fn accept(self, node: &'a SyntaxNode) -> Result<Self::Output, Self::Ctx> { 103 fn accept(self, node: &'a SyntaxNode) -> Result<Self::Output, Self::Ctx> {
104 let VisCtx { inner, f, .. } = self; 104 let VisCtx { inner, f, .. } = self;
105 inner.accept(node).or_else(|ctx| match N::cast(node) { 105 inner.accept(node).or_else(|ctx| match N::cast(node.clone()) {
106 None => Err(ctx), 106 None => Err(ctx),
107 Some(node) => Ok(f(node, ctx)), 107 Some(node) => Ok(f(node, ctx)),
108 }) 108 })
diff --git a/crates/ra_syntax/src/ast.rs b/crates/ra_syntax/src/ast.rs
index 3dcf39f7e..ceb603c50 100644
--- a/crates/ra_syntax/src/ast.rs
+++ b/crates/ra_syntax/src/ast.rs
@@ -9,7 +9,7 @@ mod expr_extensions;
9use std::marker::PhantomData; 9use std::marker::PhantomData;
10 10
11use crate::{ 11use crate::{
12 syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken, TreeArc}, 12 syntax_node::{SyntaxNode, SyntaxNodeChildren, SyntaxToken},
13 SmolStr, 13 SmolStr,
14}; 14};
15 15
@@ -25,51 +25,49 @@ pub use self::{
25/// conversion itself has zero runtime cost: ast and syntax nodes have exactly 25/// conversion itself has zero runtime cost: ast and syntax nodes have exactly
26/// the same representation: a pointer to the tree root and a pointer to the 26/// the same representation: a pointer to the tree root and a pointer to the
27/// node itself. 27/// node itself.
28pub trait AstNode: 28pub trait AstNode: Clone {
29 rowan::TransparentNewType<Repr = rowan::SyntaxNode> + ToOwned<Owned = TreeArc<Self>> 29 fn cast(syntax: SyntaxNode) -> Option<Self>
30{
31 fn cast(syntax: &SyntaxNode) -> Option<&Self>
32 where 30 where
33 Self: Sized; 31 Self: Sized;
34 fn syntax(&self) -> &SyntaxNode; 32 fn syntax(&self) -> &SyntaxNode;
35} 33}
36 34
37/// Like `AstNode`, but wraps tokens rather than interior nodes. 35/// Like `AstNode`, but wraps tokens rather than interior nodes.
38pub trait AstToken<'a> { 36pub trait AstToken {
39 fn cast(token: SyntaxToken<'a>) -> Option<Self> 37 fn cast(token: SyntaxToken) -> Option<Self>
40 where 38 where
41 Self: Sized; 39 Self: Sized;
42 fn syntax(&self) -> SyntaxToken<'a>; 40 fn syntax(&self) -> &SyntaxToken;
43 fn text(&self) -> &'a SmolStr { 41 fn text(&self) -> &SmolStr {
44 self.syntax().text() 42 self.syntax().text()
45 } 43 }
46} 44}
47 45
48/// An iterator over `SyntaxNode` children of a particular AST type. 46/// An iterator over `SyntaxNode` children of a particular AST type.
49#[derive(Debug)] 47#[derive(Debug)]
50pub struct AstChildren<'a, N> { 48pub struct AstChildren<N> {
51 inner: SyntaxNodeChildren<'a>, 49 inner: SyntaxNodeChildren,
52 ph: PhantomData<N>, 50 ph: PhantomData<N>,
53} 51}
54 52
55impl<'a, N> AstChildren<'a, N> { 53impl<N> AstChildren<N> {
56 fn new(parent: &'a SyntaxNode) -> Self { 54 fn new(parent: &SyntaxNode) -> Self {
57 AstChildren { inner: parent.children(), ph: PhantomData } 55 AstChildren { inner: parent.children(), ph: PhantomData }
58 } 56 }
59} 57}
60 58
61impl<'a, N: AstNode + 'a> Iterator for AstChildren<'a, N> { 59impl<N: AstNode> Iterator for AstChildren<N> {
62 type Item = &'a N; 60 type Item = N;
63 fn next(&mut self) -> Option<&'a N> { 61 fn next(&mut self) -> Option<N> {
64 self.inner.by_ref().find_map(N::cast) 62 self.inner.by_ref().find_map(N::cast)
65 } 63 }
66} 64}
67 65
68fn child_opt<P: AstNode, C: AstNode>(parent: &P) -> Option<&C> { 66fn child_opt<P: AstNode + ?Sized, C: AstNode>(parent: &P) -> Option<C> {
69 children(parent).next() 67 children(parent).next()
70} 68}
71 69
72fn children<P: AstNode, C: AstNode>(parent: &P) -> AstChildren<C> { 70fn children<P: AstNode + ?Sized, C: AstNode>(parent: &P) -> AstChildren<C> {
73 AstChildren::new(parent.syntax()) 71 AstChildren::new(parent.syntax())
74} 72}
75 73
@@ -123,7 +121,7 @@ fn test_doc_comment_preserves_indents() {
123 121
124#[test] 122#[test]
125fn test_where_predicates() { 123fn test_where_predicates() {
126 fn assert_bound(text: &str, bound: Option<&TypeBound>) { 124 fn assert_bound(text: &str, bound: Option<TypeBound>) {
127 assert_eq!(text, bound.unwrap().syntax().text().to_string()); 125 assert_eq!(text, bound.unwrap().syntax().text().to_string());
128 } 126 }
129 127
diff --git a/crates/ra_syntax/src/ast/expr_extensions.rs b/crates/ra_syntax/src/ast/expr_extensions.rs
index 4355e3587..ca1773908 100644
--- a/crates/ra_syntax/src/ast/expr_extensions.rs
+++ b/crates/ra_syntax/src/ast/expr_extensions.rs
@@ -8,20 +8,20 @@ use crate::{
8}; 8};
9 9
10#[derive(Debug, Clone, PartialEq, Eq)] 10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum ElseBranch<'a> { 11pub enum ElseBranch {
12 Block(&'a ast::Block), 12 Block(ast::Block),
13 IfExpr(&'a ast::IfExpr), 13 IfExpr(ast::IfExpr),
14} 14}
15 15
16impl ast::IfExpr { 16impl ast::IfExpr {
17 pub fn then_branch(&self) -> Option<&ast::Block> { 17 pub fn then_branch(&self) -> Option<ast::Block> {
18 self.blocks().nth(0) 18 self.blocks().nth(0)
19 } 19 }
20 pub fn else_branch(&self) -> Option<ElseBranch> { 20 pub fn else_branch(&self) -> Option<ElseBranch> {
21 let res = match self.blocks().nth(1) { 21 let res = match self.blocks().nth(1) {
22 Some(block) => ElseBranch::Block(block), 22 Some(block) => ElseBranch::Block(block),
23 None => { 23 None => {
24 let elif: &ast::IfExpr = child_opt(self)?; 24 let elif: ast::IfExpr = child_opt(self)?;
25 ElseBranch::IfExpr(elif) 25 ElseBranch::IfExpr(elif)
26 } 26 }
27 }; 27 };
@@ -60,7 +60,7 @@ impl ast::PrefixExpr {
60 } 60 }
61 61
62 pub fn op_token(&self) -> Option<SyntaxToken> { 62 pub fn op_token(&self) -> Option<SyntaxToken> {
63 self.syntax().first_child_or_token()?.as_token() 63 self.syntax().first_child_or_token()?.as_token().cloned()
64 } 64 }
65} 65}
66 66
@@ -132,7 +132,7 @@ pub enum BinOp {
132 132
133impl ast::BinExpr { 133impl ast::BinExpr {
134 fn op_details(&self) -> Option<(SyntaxToken, BinOp)> { 134 fn op_details(&self) -> Option<(SyntaxToken, BinOp)> {
135 self.syntax().children_with_tokens().filter_map(|it| it.as_token()).find_map(|c| { 135 self.syntax().children_with_tokens().filter_map(|it| it.as_token().cloned()).find_map(|c| {
136 match c.kind() { 136 match c.kind() {
137 T![||] => Some((c, BinOp::BooleanOr)), 137 T![||] => Some((c, BinOp::BooleanOr)),
138 T![&&] => Some((c, BinOp::BooleanAnd)), 138 T![&&] => Some((c, BinOp::BooleanAnd)),
@@ -178,15 +178,15 @@ impl ast::BinExpr {
178 self.op_details().map(|t| t.0) 178 self.op_details().map(|t| t.0)
179 } 179 }
180 180
181 pub fn lhs(&self) -> Option<&ast::Expr> { 181 pub fn lhs(&self) -> Option<ast::Expr> {
182 children(self).nth(0) 182 children(self).nth(0)
183 } 183 }
184 184
185 pub fn rhs(&self) -> Option<&ast::Expr> { 185 pub fn rhs(&self) -> Option<ast::Expr> {
186 children(self).nth(1) 186 children(self).nth(1)
187 } 187 }
188 188
189 pub fn sub_exprs(&self) -> (Option<&ast::Expr>, Option<&ast::Expr>) { 189 pub fn sub_exprs(&self) -> (Option<ast::Expr>, Option<ast::Expr>) {
190 let mut children = children(self); 190 let mut children = children(self);
191 let first = children.next(); 191 let first = children.next();
192 let second = children.next(); 192 let second = children.next();
@@ -194,9 +194,9 @@ impl ast::BinExpr {
194 } 194 }
195} 195}
196 196
197pub enum ArrayExprKind<'a> { 197pub enum ArrayExprKind {
198 Repeat { initializer: Option<&'a ast::Expr>, repeat: Option<&'a ast::Expr> }, 198 Repeat { initializer: Option<ast::Expr>, repeat: Option<ast::Expr> },
199 ElementList(AstChildren<'a, ast::Expr>), 199 ElementList(AstChildren<ast::Expr>),
200} 200}
201 201
202impl ast::ArrayExpr { 202impl ast::ArrayExpr {
@@ -275,12 +275,12 @@ impl ast::Literal {
275#[test] 275#[test]
276fn test_literal_with_attr() { 276fn test_literal_with_attr() {
277 let parse = ast::SourceFile::parse(r#"const _: &str = { #[attr] "Hello" };"#); 277 let parse = ast::SourceFile::parse(r#"const _: &str = { #[attr] "Hello" };"#);
278 let lit = parse.tree.syntax().descendants().find_map(ast::Literal::cast).unwrap(); 278 let lit = parse.tree().syntax().descendants().find_map(ast::Literal::cast).unwrap();
279 assert_eq!(lit.token().text(), r#""Hello""#); 279 assert_eq!(lit.token().text(), r#""Hello""#);
280} 280}
281 281
282impl ast::NamedField { 282impl ast::NamedField {
283 pub fn parent_struct_lit(&self) -> &ast::StructLit { 283 pub fn parent_struct_lit(&self) -> ast::StructLit {
284 self.syntax().ancestors().find_map(ast::StructLit::cast).unwrap() 284 self.syntax().ancestors().find_map(ast::StructLit::cast).unwrap()
285 } 285 }
286} 286}
diff --git a/crates/ra_syntax/src/ast/extensions.rs b/crates/ra_syntax/src/ast/extensions.rs
index 72a30232d..5420f67ff 100644
--- a/crates/ra_syntax/src/ast/extensions.rs
+++ b/crates/ra_syntax/src/ast/extensions.rs
@@ -4,7 +4,7 @@
4use itertools::Itertools; 4use itertools::Itertools;
5 5
6use crate::{ 6use crate::{
7 ast::{self, child_opt, children, AstNode}, 7 ast::{self, child_opt, children, AstNode, SyntaxNode},
8 SmolStr, SyntaxElement, 8 SmolStr, SyntaxElement,
9 SyntaxKind::*, 9 SyntaxKind::*,
10 SyntaxToken, T, 10 SyntaxToken, T,
@@ -13,15 +13,20 @@ use ra_parser::SyntaxKind;
13 13
14impl ast::Name { 14impl ast::Name {
15 pub fn text(&self) -> &SmolStr { 15 pub fn text(&self) -> &SmolStr {
16 let ident = self.syntax().first_child_or_token().unwrap().as_token().unwrap(); 16 text_of_first_token(self.syntax())
17 ident.text()
18 } 17 }
19} 18}
20 19
21impl ast::NameRef { 20impl ast::NameRef {
22 pub fn text(&self) -> &SmolStr { 21 pub fn text(&self) -> &SmolStr {
23 let ident = self.syntax().first_child_or_token().unwrap().as_token().unwrap(); 22 text_of_first_token(self.syntax())
24 ident.text() 23 }
24}
25
26fn text_of_first_token(node: &SyntaxNode) -> &SmolStr {
27 match node.0.green().children().first() {
28 Some(rowan::GreenElement::Token(it)) => it.text(),
29 _ => panic!(),
25 } 30 }
26} 31}
27 32
@@ -50,10 +55,10 @@ impl ast::Attr {
50 } 55 }
51 } 56 }
52 57
53 pub fn as_call(&self) -> Option<(SmolStr, &ast::TokenTree)> { 58 pub fn as_call(&self) -> Option<(SmolStr, ast::TokenTree)> {
54 let tt = self.value()?; 59 let tt = self.value()?;
55 let (_bra, attr, args, _ket) = tt.syntax().children_with_tokens().collect_tuple()?; 60 let (_bra, attr, args, _ket) = tt.syntax().children_with_tokens().collect_tuple()?;
56 let args = ast::TokenTree::cast(args.as_node()?)?; 61 let args = ast::TokenTree::cast(args.as_node()?.clone())?;
57 if attr.kind() == IDENT { 62 if attr.kind() == IDENT {
58 Some((attr.as_token()?.text().clone(), args)) 63 Some((attr.as_token()?.text().clone(), args))
59 } else { 64 } else {
@@ -86,16 +91,16 @@ impl ast::Attr {
86 } 91 }
87} 92}
88 93
89#[derive(Debug, Clone, Copy, PartialEq, Eq)] 94#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum PathSegmentKind<'a> { 95pub enum PathSegmentKind {
91 Name(&'a ast::NameRef), 96 Name(ast::NameRef),
92 SelfKw, 97 SelfKw,
93 SuperKw, 98 SuperKw,
94 CrateKw, 99 CrateKw,
95} 100}
96 101
97impl ast::PathSegment { 102impl ast::PathSegment {
98 pub fn parent_path(&self) -> &ast::Path { 103 pub fn parent_path(&self) -> ast::Path {
99 self.syntax() 104 self.syntax()
100 .parent() 105 .parent()
101 .and_then(ast::Path::cast) 106 .and_then(ast::Path::cast)
@@ -125,7 +130,7 @@ impl ast::PathSegment {
125} 130}
126 131
127impl ast::Path { 132impl ast::Path {
128 pub fn parent_path(&self) -> Option<&ast::Path> { 133 pub fn parent_path(&self) -> Option<ast::Path> {
129 self.syntax().parent().and_then(ast::Path::cast) 134 self.syntax().parent().and_then(ast::Path::cast)
130 } 135 }
131} 136}
@@ -146,7 +151,7 @@ impl ast::UseTree {
146} 151}
147 152
148impl ast::UseTreeList { 153impl ast::UseTreeList {
149 pub fn parent_use_tree(&self) -> &ast::UseTree { 154 pub fn parent_use_tree(&self) -> ast::UseTree {
150 self.syntax() 155 self.syntax()
151 .parent() 156 .parent()
152 .and_then(ast::UseTree::cast) 157 .and_then(ast::UseTree::cast)
@@ -155,21 +160,21 @@ impl ast::UseTreeList {
155} 160}
156 161
157impl ast::ImplBlock { 162impl ast::ImplBlock {
158 pub fn target_type(&self) -> Option<&ast::TypeRef> { 163 pub fn target_type(&self) -> Option<ast::TypeRef> {
159 match self.target() { 164 match self.target() {
160 (Some(t), None) | (_, Some(t)) => Some(t), 165 (Some(t), None) | (_, Some(t)) => Some(t),
161 _ => None, 166 _ => None,
162 } 167 }
163 } 168 }
164 169
165 pub fn target_trait(&self) -> Option<&ast::TypeRef> { 170 pub fn target_trait(&self) -> Option<ast::TypeRef> {
166 match self.target() { 171 match self.target() {
167 (Some(t), Some(_)) => Some(t), 172 (Some(t), Some(_)) => Some(t),
168 _ => None, 173 _ => None,
169 } 174 }
170 } 175 }
171 176
172 fn target(&self) -> (Option<&ast::TypeRef>, Option<&ast::TypeRef>) { 177 fn target(&self) -> (Option<ast::TypeRef>, Option<ast::TypeRef>) {
173 let mut types = children(self); 178 let mut types = children(self);
174 let first = types.next(); 179 let first = types.next();
175 let second = types.next(); 180 let second = types.next();
@@ -182,13 +187,13 @@ impl ast::ImplBlock {
182} 187}
183 188
184#[derive(Debug, Clone, PartialEq, Eq)] 189#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum StructKind<'a> { 190pub enum StructKind {
186 Tuple(&'a ast::PosFieldDefList), 191 Tuple(ast::PosFieldDefList),
187 Named(&'a ast::NamedFieldDefList), 192 Named(ast::NamedFieldDefList),
188 Unit, 193 Unit,
189} 194}
190 195
191impl StructKind<'_> { 196impl StructKind {
192 fn from_node<N: AstNode>(node: &N) -> StructKind { 197 fn from_node<N: AstNode>(node: &N) -> StructKind {
193 if let Some(nfdl) = child_opt::<_, ast::NamedFieldDefList>(node) { 198 if let Some(nfdl) = child_opt::<_, ast::NamedFieldDefList>(node) {
194 StructKind::Named(nfdl) 199 StructKind::Named(nfdl)
@@ -218,7 +223,7 @@ impl ast::StructDef {
218} 223}
219 224
220impl ast::EnumVariant { 225impl ast::EnumVariant {
221 pub fn parent_enum(&self) -> &ast::EnumDef { 226 pub fn parent_enum(&self) -> ast::EnumDef {
222 self.syntax() 227 self.syntax()
223 .parent() 228 .parent()
224 .and_then(|it| it.parent()) 229 .and_then(|it| it.parent())
@@ -231,10 +236,10 @@ impl ast::EnumVariant {
231} 236}
232 237
233impl ast::FnDef { 238impl ast::FnDef {
234 pub fn semicolon_token(&self) -> Option<SyntaxToken<'_>> { 239 pub fn semicolon_token(&self) -> Option<SyntaxToken> {
235 self.syntax() 240 self.syntax()
236 .last_child_or_token() 241 .last_child_or_token()
237 .and_then(|it| it.as_token()) 242 .and_then(|it| it.as_token().cloned())
238 .filter(|it| it.kind() == T![;]) 243 .filter(|it| it.kind() == T![;])
239 } 244 }
240} 245}
@@ -258,9 +263,9 @@ impl ast::ExprStmt {
258} 263}
259 264
260#[derive(Debug, Clone, PartialEq, Eq)] 265#[derive(Debug, Clone, PartialEq, Eq)]
261pub enum FieldKind<'a> { 266pub enum FieldKind {
262 Name(&'a ast::NameRef), 267 Name(ast::NameRef),
263 Index(SyntaxToken<'a>), 268 Index(SyntaxToken),
264} 269}
265 270
266impl ast::FieldExpr { 271impl ast::FieldExpr {
@@ -271,6 +276,7 @@ impl ast::FieldExpr {
271 .find(|c| c.kind() == SyntaxKind::INT_NUMBER || c.kind() == SyntaxKind::FLOAT_NUMBER) 276 .find(|c| c.kind() == SyntaxKind::INT_NUMBER || c.kind() == SyntaxKind::FLOAT_NUMBER)
272 .as_ref() 277 .as_ref()
273 .and_then(SyntaxElement::as_token) 278 .and_then(SyntaxElement::as_token)
279 .cloned()
274 } 280 }
275 281
276 pub fn field_access(&self) -> Option<FieldKind> { 282 pub fn field_access(&self) -> Option<FieldKind> {
@@ -326,7 +332,7 @@ impl ast::SelfParam {
326 pub fn self_kw_token(&self) -> SyntaxToken { 332 pub fn self_kw_token(&self) -> SyntaxToken {
327 self.syntax() 333 self.syntax()
328 .children_with_tokens() 334 .children_with_tokens()
329 .filter_map(|it| it.as_token()) 335 .filter_map(|it| it.as_token().cloned())
330 .find(|it| it.kind() == T![self]) 336 .find(|it| it.kind() == T![self])
331 .expect("invalid tree: self param must have self") 337 .expect("invalid tree: self param must have self")
332 } 338 }
@@ -355,7 +361,7 @@ impl ast::LifetimeParam {
355 pub fn lifetime_token(&self) -> Option<SyntaxToken> { 361 pub fn lifetime_token(&self) -> Option<SyntaxToken> {
356 self.syntax() 362 self.syntax()
357 .children_with_tokens() 363 .children_with_tokens()
358 .filter_map(|it| it.as_token()) 364 .filter_map(|it| it.as_token().cloned())
359 .find(|it| it.kind() == LIFETIME) 365 .find(|it| it.kind() == LIFETIME)
360 } 366 }
361} 367}
@@ -364,7 +370,7 @@ impl ast::WherePred {
364 pub fn lifetime_token(&self) -> Option<SyntaxToken> { 370 pub fn lifetime_token(&self) -> Option<SyntaxToken> {
365 self.syntax() 371 self.syntax()
366 .children_with_tokens() 372 .children_with_tokens()
367 .filter_map(|it| it.as_token()) 373 .filter_map(|it| it.as_token().cloned())
368 .find(|it| it.kind() == LIFETIME) 374 .find(|it| it.kind() == LIFETIME)
369 } 375 }
370} 376}
diff --git a/crates/ra_syntax/src/ast/generated.rs b/crates/ra_syntax/src/ast/generated.rs
index 1d888e709..a1f320257 100644
--- a/crates/ra_syntax/src/ast/generated.rs
+++ b/crates/ra_syntax/src/ast/generated.rs
@@ -9,503 +9,365 @@
9 9
10#![cfg_attr(rustfmt, rustfmt_skip)] 10#![cfg_attr(rustfmt, rustfmt_skip)]
11 11
12use rowan::TransparentNewType;
13
14use crate::{ 12use crate::{
15 SyntaxNode, SyntaxKind::*, 13 SyntaxNode, SyntaxKind::*,
16 syntax_node::{TreeArc},
17 ast::{self, AstNode}, 14 ast::{self, AstNode},
18}; 15};
19 16
20// Alias 17// Alias
21#[derive(Debug, PartialEq, Eq, Hash)] 18#[derive(Debug, Clone, PartialEq, Eq, Hash)]
22#[repr(transparent)]
23pub struct Alias { 19pub struct Alias {
24 pub(crate) syntax: SyntaxNode, 20 pub(crate) syntax: SyntaxNode,
25} 21}
26unsafe impl TransparentNewType for Alias {
27 type Repr = rowan::SyntaxNode;
28}
29 22
30impl AstNode for Alias { 23impl AstNode for Alias {
31 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 24 fn cast(syntax: SyntaxNode) -> Option<Self> {
32 match syntax.kind() { 25 match syntax.kind() {
33 ALIAS => Some(Alias::from_repr(syntax.into_repr())), 26 ALIAS => Some(Alias { syntax }),
34 _ => None, 27 _ => None,
35 } 28 }
36 } 29 }
37 fn syntax(&self) -> &SyntaxNode { &self.syntax } 30 fn syntax(&self) -> &SyntaxNode { &self.syntax }
38} 31}
39 32
40impl ToOwned for Alias {
41 type Owned = TreeArc<Alias>;
42 fn to_owned(&self) -> TreeArc<Alias> { TreeArc::cast(self.syntax.to_owned()) }
43}
44
45 33
46impl ast::NameOwner for Alias {} 34impl ast::NameOwner for Alias {}
47impl Alias {} 35impl Alias {}
48 36
49// ArgList 37// ArgList
50#[derive(Debug, PartialEq, Eq, Hash)] 38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51#[repr(transparent)]
52pub struct ArgList { 39pub struct ArgList {
53 pub(crate) syntax: SyntaxNode, 40 pub(crate) syntax: SyntaxNode,
54} 41}
55unsafe impl TransparentNewType for ArgList {
56 type Repr = rowan::SyntaxNode;
57}
58 42
59impl AstNode for ArgList { 43impl AstNode for ArgList {
60 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 44 fn cast(syntax: SyntaxNode) -> Option<Self> {
61 match syntax.kind() { 45 match syntax.kind() {
62 ARG_LIST => Some(ArgList::from_repr(syntax.into_repr())), 46 ARG_LIST => Some(ArgList { syntax }),
63 _ => None, 47 _ => None,
64 } 48 }
65 } 49 }
66 fn syntax(&self) -> &SyntaxNode { &self.syntax } 50 fn syntax(&self) -> &SyntaxNode { &self.syntax }
67} 51}
68 52
69impl ToOwned for ArgList {
70 type Owned = TreeArc<ArgList>;
71 fn to_owned(&self) -> TreeArc<ArgList> { TreeArc::cast(self.syntax.to_owned()) }
72}
73
74 53
75impl ArgList { 54impl ArgList {
76 pub fn args(&self) -> impl Iterator<Item = &Expr> { 55 pub fn args(&self) -> impl Iterator<Item = Expr> {
77 super::children(self) 56 super::children(self)
78 } 57 }
79} 58}
80 59
81// ArrayExpr 60// ArrayExpr
82#[derive(Debug, PartialEq, Eq, Hash)] 61#[derive(Debug, Clone, PartialEq, Eq, Hash)]
83#[repr(transparent)]
84pub struct ArrayExpr { 62pub struct ArrayExpr {
85 pub(crate) syntax: SyntaxNode, 63 pub(crate) syntax: SyntaxNode,
86} 64}
87unsafe impl TransparentNewType for ArrayExpr {
88 type Repr = rowan::SyntaxNode;
89}
90 65
91impl AstNode for ArrayExpr { 66impl AstNode for ArrayExpr {
92 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 67 fn cast(syntax: SyntaxNode) -> Option<Self> {
93 match syntax.kind() { 68 match syntax.kind() {
94 ARRAY_EXPR => Some(ArrayExpr::from_repr(syntax.into_repr())), 69 ARRAY_EXPR => Some(ArrayExpr { syntax }),
95 _ => None, 70 _ => None,
96 } 71 }
97 } 72 }
98 fn syntax(&self) -> &SyntaxNode { &self.syntax } 73 fn syntax(&self) -> &SyntaxNode { &self.syntax }
99} 74}
100 75
101impl ToOwned for ArrayExpr {
102 type Owned = TreeArc<ArrayExpr>;
103 fn to_owned(&self) -> TreeArc<ArrayExpr> { TreeArc::cast(self.syntax.to_owned()) }
104}
105
106 76
107impl ArrayExpr { 77impl ArrayExpr {
108 pub fn exprs(&self) -> impl Iterator<Item = &Expr> { 78 pub fn exprs(&self) -> impl Iterator<Item = Expr> {
109 super::children(self) 79 super::children(self)
110 } 80 }
111} 81}
112 82
113// ArrayType 83// ArrayType
114#[derive(Debug, PartialEq, Eq, Hash)] 84#[derive(Debug, Clone, PartialEq, Eq, Hash)]
115#[repr(transparent)]
116pub struct ArrayType { 85pub struct ArrayType {
117 pub(crate) syntax: SyntaxNode, 86 pub(crate) syntax: SyntaxNode,
118} 87}
119unsafe impl TransparentNewType for ArrayType {
120 type Repr = rowan::SyntaxNode;
121}
122 88
123impl AstNode for ArrayType { 89impl AstNode for ArrayType {
124 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 90 fn cast(syntax: SyntaxNode) -> Option<Self> {
125 match syntax.kind() { 91 match syntax.kind() {
126 ARRAY_TYPE => Some(ArrayType::from_repr(syntax.into_repr())), 92 ARRAY_TYPE => Some(ArrayType { syntax }),
127 _ => None, 93 _ => None,
128 } 94 }
129 } 95 }
130 fn syntax(&self) -> &SyntaxNode { &self.syntax } 96 fn syntax(&self) -> &SyntaxNode { &self.syntax }
131} 97}
132 98
133impl ToOwned for ArrayType {
134 type Owned = TreeArc<ArrayType>;
135 fn to_owned(&self) -> TreeArc<ArrayType> { TreeArc::cast(self.syntax.to_owned()) }
136}
137
138 99
139impl ArrayType { 100impl ArrayType {
140 pub fn type_ref(&self) -> Option<&TypeRef> { 101 pub fn type_ref(&self) -> Option<TypeRef> {
141 super::child_opt(self) 102 super::child_opt(self)
142 } 103 }
143 104
144 pub fn expr(&self) -> Option<&Expr> { 105 pub fn expr(&self) -> Option<Expr> {
145 super::child_opt(self) 106 super::child_opt(self)
146 } 107 }
147} 108}
148 109
149// AssocTypeArg 110// AssocTypeArg
150#[derive(Debug, PartialEq, Eq, Hash)] 111#[derive(Debug, Clone, PartialEq, Eq, Hash)]
151#[repr(transparent)]
152pub struct AssocTypeArg { 112pub struct AssocTypeArg {
153 pub(crate) syntax: SyntaxNode, 113 pub(crate) syntax: SyntaxNode,
154} 114}
155unsafe impl TransparentNewType for AssocTypeArg {
156 type Repr = rowan::SyntaxNode;
157}
158 115
159impl AstNode for AssocTypeArg { 116impl AstNode for AssocTypeArg {
160 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 117 fn cast(syntax: SyntaxNode) -> Option<Self> {
161 match syntax.kind() { 118 match syntax.kind() {
162 ASSOC_TYPE_ARG => Some(AssocTypeArg::from_repr(syntax.into_repr())), 119 ASSOC_TYPE_ARG => Some(AssocTypeArg { syntax }),
163 _ => None, 120 _ => None,
164 } 121 }
165 } 122 }
166 fn syntax(&self) -> &SyntaxNode { &self.syntax } 123 fn syntax(&self) -> &SyntaxNode { &self.syntax }
167} 124}
168 125
169impl ToOwned for AssocTypeArg {
170 type Owned = TreeArc<AssocTypeArg>;
171 fn to_owned(&self) -> TreeArc<AssocTypeArg> { TreeArc::cast(self.syntax.to_owned()) }
172}
173
174 126
175impl AssocTypeArg { 127impl AssocTypeArg {
176 pub fn name_ref(&self) -> Option<&NameRef> { 128 pub fn name_ref(&self) -> Option<NameRef> {
177 super::child_opt(self) 129 super::child_opt(self)
178 } 130 }
179 131
180 pub fn type_ref(&self) -> Option<&TypeRef> { 132 pub fn type_ref(&self) -> Option<TypeRef> {
181 super::child_opt(self) 133 super::child_opt(self)
182 } 134 }
183} 135}
184 136
185// Attr 137// Attr
186#[derive(Debug, PartialEq, Eq, Hash)] 138#[derive(Debug, Clone, PartialEq, Eq, Hash)]
187#[repr(transparent)]
188pub struct Attr { 139pub struct Attr {
189 pub(crate) syntax: SyntaxNode, 140 pub(crate) syntax: SyntaxNode,
190} 141}
191unsafe impl TransparentNewType for Attr {
192 type Repr = rowan::SyntaxNode;
193}
194 142
195impl AstNode for Attr { 143impl AstNode for Attr {
196 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 144 fn cast(syntax: SyntaxNode) -> Option<Self> {
197 match syntax.kind() { 145 match syntax.kind() {
198 ATTR => Some(Attr::from_repr(syntax.into_repr())), 146 ATTR => Some(Attr { syntax }),
199 _ => None, 147 _ => None,
200 } 148 }
201 } 149 }
202 fn syntax(&self) -> &SyntaxNode { &self.syntax } 150 fn syntax(&self) -> &SyntaxNode { &self.syntax }
203} 151}
204 152
205impl ToOwned for Attr {
206 type Owned = TreeArc<Attr>;
207 fn to_owned(&self) -> TreeArc<Attr> { TreeArc::cast(self.syntax.to_owned()) }
208}
209
210 153
211impl Attr { 154impl Attr {
212 pub fn value(&self) -> Option<&TokenTree> { 155 pub fn value(&self) -> Option<TokenTree> {
213 super::child_opt(self) 156 super::child_opt(self)
214 } 157 }
215} 158}
216 159
217// BinExpr 160// BinExpr
218#[derive(Debug, PartialEq, Eq, Hash)] 161#[derive(Debug, Clone, PartialEq, Eq, Hash)]
219#[repr(transparent)]
220pub struct BinExpr { 162pub struct BinExpr {
221 pub(crate) syntax: SyntaxNode, 163 pub(crate) syntax: SyntaxNode,
222} 164}
223unsafe impl TransparentNewType for BinExpr {
224 type Repr = rowan::SyntaxNode;
225}
226 165
227impl AstNode for BinExpr { 166impl AstNode for BinExpr {
228 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 167 fn cast(syntax: SyntaxNode) -> Option<Self> {
229 match syntax.kind() { 168 match syntax.kind() {
230 BIN_EXPR => Some(BinExpr::from_repr(syntax.into_repr())), 169 BIN_EXPR => Some(BinExpr { syntax }),
231 _ => None, 170 _ => None,
232 } 171 }
233 } 172 }
234 fn syntax(&self) -> &SyntaxNode { &self.syntax } 173 fn syntax(&self) -> &SyntaxNode { &self.syntax }
235} 174}
236 175
237impl ToOwned for BinExpr {
238 type Owned = TreeArc<BinExpr>;
239 fn to_owned(&self) -> TreeArc<BinExpr> { TreeArc::cast(self.syntax.to_owned()) }
240}
241
242 176
243impl BinExpr {} 177impl BinExpr {}
244 178
245// BindPat 179// BindPat
246#[derive(Debug, PartialEq, Eq, Hash)] 180#[derive(Debug, Clone, PartialEq, Eq, Hash)]
247#[repr(transparent)]
248pub struct BindPat { 181pub struct BindPat {
249 pub(crate) syntax: SyntaxNode, 182 pub(crate) syntax: SyntaxNode,
250} 183}
251unsafe impl TransparentNewType for BindPat {
252 type Repr = rowan::SyntaxNode;
253}
254 184
255impl AstNode for BindPat { 185impl AstNode for BindPat {
256 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 186 fn cast(syntax: SyntaxNode) -> Option<Self> {
257 match syntax.kind() { 187 match syntax.kind() {
258 BIND_PAT => Some(BindPat::from_repr(syntax.into_repr())), 188 BIND_PAT => Some(BindPat { syntax }),
259 _ => None, 189 _ => None,
260 } 190 }
261 } 191 }
262 fn syntax(&self) -> &SyntaxNode { &self.syntax } 192 fn syntax(&self) -> &SyntaxNode { &self.syntax }
263} 193}
264 194
265impl ToOwned for BindPat {
266 type Owned = TreeArc<BindPat>;
267 fn to_owned(&self) -> TreeArc<BindPat> { TreeArc::cast(self.syntax.to_owned()) }
268}
269
270 195
271impl ast::NameOwner for BindPat {} 196impl ast::NameOwner for BindPat {}
272impl BindPat { 197impl BindPat {
273 pub fn pat(&self) -> Option<&Pat> { 198 pub fn pat(&self) -> Option<Pat> {
274 super::child_opt(self) 199 super::child_opt(self)
275 } 200 }
276} 201}
277 202
278// Block 203// Block
279#[derive(Debug, PartialEq, Eq, Hash)] 204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
280#[repr(transparent)]
281pub struct Block { 205pub struct Block {
282 pub(crate) syntax: SyntaxNode, 206 pub(crate) syntax: SyntaxNode,
283} 207}
284unsafe impl TransparentNewType for Block {
285 type Repr = rowan::SyntaxNode;
286}
287 208
288impl AstNode for Block { 209impl AstNode for Block {
289 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 210 fn cast(syntax: SyntaxNode) -> Option<Self> {
290 match syntax.kind() { 211 match syntax.kind() {
291 BLOCK => Some(Block::from_repr(syntax.into_repr())), 212 BLOCK => Some(Block { syntax }),
292 _ => None, 213 _ => None,
293 } 214 }
294 } 215 }
295 fn syntax(&self) -> &SyntaxNode { &self.syntax } 216 fn syntax(&self) -> &SyntaxNode { &self.syntax }
296} 217}
297 218
298impl ToOwned for Block {
299 type Owned = TreeArc<Block>;
300 fn to_owned(&self) -> TreeArc<Block> { TreeArc::cast(self.syntax.to_owned()) }
301}
302
303 219
304impl ast::AttrsOwner for Block {} 220impl ast::AttrsOwner for Block {}
305impl Block { 221impl Block {
306 pub fn statements(&self) -> impl Iterator<Item = &Stmt> { 222 pub fn statements(&self) -> impl Iterator<Item = Stmt> {
307 super::children(self) 223 super::children(self)
308 } 224 }
309 225
310 pub fn expr(&self) -> Option<&Expr> { 226 pub fn expr(&self) -> Option<Expr> {
311 super::child_opt(self) 227 super::child_opt(self)
312 } 228 }
313} 229}
314 230
315// BlockExpr 231// BlockExpr
316#[derive(Debug, PartialEq, Eq, Hash)] 232#[derive(Debug, Clone, PartialEq, Eq, Hash)]
317#[repr(transparent)]
318pub struct BlockExpr { 233pub struct BlockExpr {
319 pub(crate) syntax: SyntaxNode, 234 pub(crate) syntax: SyntaxNode,
320} 235}
321unsafe impl TransparentNewType for BlockExpr {
322 type Repr = rowan::SyntaxNode;
323}
324 236
325impl AstNode for BlockExpr { 237impl AstNode for BlockExpr {
326 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 238 fn cast(syntax: SyntaxNode) -> Option<Self> {
327 match syntax.kind() { 239 match syntax.kind() {
328 BLOCK_EXPR => Some(BlockExpr::from_repr(syntax.into_repr())), 240 BLOCK_EXPR => Some(BlockExpr { syntax }),
329 _ => None, 241 _ => None,
330 } 242 }
331 } 243 }
332 fn syntax(&self) -> &SyntaxNode { &self.syntax } 244 fn syntax(&self) -> &SyntaxNode { &self.syntax }
333} 245}
334 246
335impl ToOwned for BlockExpr {
336 type Owned = TreeArc<BlockExpr>;
337 fn to_owned(&self) -> TreeArc<BlockExpr> { TreeArc::cast(self.syntax.to_owned()) }
338}
339
340 247
341impl BlockExpr { 248impl BlockExpr {
342 pub fn block(&self) -> Option<&Block> { 249 pub fn block(&self) -> Option<Block> {
343 super::child_opt(self) 250 super::child_opt(self)
344 } 251 }
345} 252}
346 253
347// BreakExpr 254// BreakExpr
348#[derive(Debug, PartialEq, Eq, Hash)] 255#[derive(Debug, Clone, PartialEq, Eq, Hash)]
349#[repr(transparent)]
350pub struct BreakExpr { 256pub struct BreakExpr {
351 pub(crate) syntax: SyntaxNode, 257 pub(crate) syntax: SyntaxNode,
352} 258}
353unsafe impl TransparentNewType for BreakExpr {
354 type Repr = rowan::SyntaxNode;
355}
356 259
357impl AstNode for BreakExpr { 260impl AstNode for BreakExpr {
358 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 261 fn cast(syntax: SyntaxNode) -> Option<Self> {
359 match syntax.kind() { 262 match syntax.kind() {
360 BREAK_EXPR => Some(BreakExpr::from_repr(syntax.into_repr())), 263 BREAK_EXPR => Some(BreakExpr { syntax }),
361 _ => None, 264 _ => None,
362 } 265 }
363 } 266 }
364 fn syntax(&self) -> &SyntaxNode { &self.syntax } 267 fn syntax(&self) -> &SyntaxNode { &self.syntax }
365} 268}
366 269
367impl ToOwned for BreakExpr {
368 type Owned = TreeArc<BreakExpr>;
369 fn to_owned(&self) -> TreeArc<BreakExpr> { TreeArc::cast(self.syntax.to_owned()) }
370}
371
372 270
373impl BreakExpr { 271impl BreakExpr {
374 pub fn expr(&self) -> Option<&Expr> { 272 pub fn expr(&self) -> Option<Expr> {
375 super::child_opt(self) 273 super::child_opt(self)
376 } 274 }
377} 275}
378 276
379// CallExpr 277// CallExpr
380#[derive(Debug, PartialEq, Eq, Hash)] 278#[derive(Debug, Clone, PartialEq, Eq, Hash)]
381#[repr(transparent)]
382pub struct CallExpr { 279pub struct CallExpr {
383 pub(crate) syntax: SyntaxNode, 280 pub(crate) syntax: SyntaxNode,
384} 281}
385unsafe impl TransparentNewType for CallExpr {
386 type Repr = rowan::SyntaxNode;
387}
388 282
389impl AstNode for CallExpr { 283impl AstNode for CallExpr {
390 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 284 fn cast(syntax: SyntaxNode) -> Option<Self> {
391 match syntax.kind() { 285 match syntax.kind() {
392 CALL_EXPR => Some(CallExpr::from_repr(syntax.into_repr())), 286 CALL_EXPR => Some(CallExpr { syntax }),
393 _ => None, 287 _ => None,
394 } 288 }
395 } 289 }
396 fn syntax(&self) -> &SyntaxNode { &self.syntax } 290 fn syntax(&self) -> &SyntaxNode { &self.syntax }
397} 291}
398 292
399impl ToOwned for CallExpr {
400 type Owned = TreeArc<CallExpr>;
401 fn to_owned(&self) -> TreeArc<CallExpr> { TreeArc::cast(self.syntax.to_owned()) }
402}
403
404 293
405impl ast::ArgListOwner for CallExpr {} 294impl ast::ArgListOwner for CallExpr {}
406impl CallExpr { 295impl CallExpr {
407 pub fn expr(&self) -> Option<&Expr> { 296 pub fn expr(&self) -> Option<Expr> {
408 super::child_opt(self) 297 super::child_opt(self)
409 } 298 }
410} 299}
411 300
412// CastExpr 301// CastExpr
413#[derive(Debug, PartialEq, Eq, Hash)] 302#[derive(Debug, Clone, PartialEq, Eq, Hash)]
414#[repr(transparent)]
415pub struct CastExpr { 303pub struct CastExpr {
416 pub(crate) syntax: SyntaxNode, 304 pub(crate) syntax: SyntaxNode,
417} 305}
418unsafe impl TransparentNewType for CastExpr {
419 type Repr = rowan::SyntaxNode;
420}
421 306
422impl AstNode for CastExpr { 307impl AstNode for CastExpr {
423 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 308 fn cast(syntax: SyntaxNode) -> Option<Self> {
424 match syntax.kind() { 309 match syntax.kind() {
425 CAST_EXPR => Some(CastExpr::from_repr(syntax.into_repr())), 310 CAST_EXPR => Some(CastExpr { syntax }),
426 _ => None, 311 _ => None,
427 } 312 }
428 } 313 }
429 fn syntax(&self) -> &SyntaxNode { &self.syntax } 314 fn syntax(&self) -> &SyntaxNode { &self.syntax }
430} 315}
431 316
432impl ToOwned for CastExpr {
433 type Owned = TreeArc<CastExpr>;
434 fn to_owned(&self) -> TreeArc<CastExpr> { TreeArc::cast(self.syntax.to_owned()) }
435}
436
437 317
438impl CastExpr { 318impl CastExpr {
439 pub fn expr(&self) -> Option<&Expr> { 319 pub fn expr(&self) -> Option<Expr> {
440 super::child_opt(self) 320 super::child_opt(self)
441 } 321 }
442 322
443 pub fn type_ref(&self) -> Option<&TypeRef> { 323 pub fn type_ref(&self) -> Option<TypeRef> {
444 super::child_opt(self) 324 super::child_opt(self)
445 } 325 }
446} 326}
447 327
448// Condition 328// Condition
449#[derive(Debug, PartialEq, Eq, Hash)] 329#[derive(Debug, Clone, PartialEq, Eq, Hash)]
450#[repr(transparent)]
451pub struct Condition { 330pub struct Condition {
452 pub(crate) syntax: SyntaxNode, 331 pub(crate) syntax: SyntaxNode,
453} 332}
454unsafe impl TransparentNewType for Condition {
455 type Repr = rowan::SyntaxNode;
456}
457 333
458impl AstNode for Condition { 334impl AstNode for Condition {
459 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 335 fn cast(syntax: SyntaxNode) -> Option<Self> {
460 match syntax.kind() { 336 match syntax.kind() {
461 CONDITION => Some(Condition::from_repr(syntax.into_repr())), 337 CONDITION => Some(Condition { syntax }),
462 _ => None, 338 _ => None,
463 } 339 }
464 } 340 }
465 fn syntax(&self) -> &SyntaxNode { &self.syntax } 341 fn syntax(&self) -> &SyntaxNode { &self.syntax }
466} 342}
467 343
468impl ToOwned for Condition {
469 type Owned = TreeArc<Condition>;
470 fn to_owned(&self) -> TreeArc<Condition> { TreeArc::cast(self.syntax.to_owned()) }
471}
472
473 344
474impl Condition { 345impl Condition {
475 pub fn pat(&self) -> Option<&Pat> { 346 pub fn pat(&self) -> Option<Pat> {
476 super::child_opt(self) 347 super::child_opt(self)
477 } 348 }
478 349
479 pub fn expr(&self) -> Option<&Expr> { 350 pub fn expr(&self) -> Option<Expr> {
480 super::child_opt(self) 351 super::child_opt(self)
481 } 352 }
482} 353}
483 354
484// ConstDef 355// ConstDef
485#[derive(Debug, PartialEq, Eq, Hash)] 356#[derive(Debug, Clone, PartialEq, Eq, Hash)]
486#[repr(transparent)]
487pub struct ConstDef { 357pub struct ConstDef {
488 pub(crate) syntax: SyntaxNode, 358 pub(crate) syntax: SyntaxNode,
489} 359}
490unsafe impl TransparentNewType for ConstDef {
491 type Repr = rowan::SyntaxNode;
492}
493 360
494impl AstNode for ConstDef { 361impl AstNode for ConstDef {
495 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 362 fn cast(syntax: SyntaxNode) -> Option<Self> {
496 match syntax.kind() { 363 match syntax.kind() {
497 CONST_DEF => Some(ConstDef::from_repr(syntax.into_repr())), 364 CONST_DEF => Some(ConstDef { syntax }),
498 _ => None, 365 _ => None,
499 } 366 }
500 } 367 }
501 fn syntax(&self) -> &SyntaxNode { &self.syntax } 368 fn syntax(&self) -> &SyntaxNode { &self.syntax }
502} 369}
503 370
504impl ToOwned for ConstDef {
505 type Owned = TreeArc<ConstDef>;
506 fn to_owned(&self) -> TreeArc<ConstDef> { TreeArc::cast(self.syntax.to_owned()) }
507}
508
509 371
510impl ast::VisibilityOwner for ConstDef {} 372impl ast::VisibilityOwner for ConstDef {}
511impl ast::NameOwner for ConstDef {} 373impl ast::NameOwner for ConstDef {}
@@ -514,93 +376,66 @@ impl ast::AttrsOwner for ConstDef {}
514impl ast::DocCommentsOwner for ConstDef {} 376impl ast::DocCommentsOwner for ConstDef {}
515impl ast::TypeAscriptionOwner for ConstDef {} 377impl ast::TypeAscriptionOwner for ConstDef {}
516impl ConstDef { 378impl ConstDef {
517 pub fn body(&self) -> Option<&Expr> { 379 pub fn body(&self) -> Option<Expr> {
518 super::child_opt(self) 380 super::child_opt(self)
519 } 381 }
520} 382}
521 383
522// ContinueExpr 384// ContinueExpr
523#[derive(Debug, PartialEq, Eq, Hash)] 385#[derive(Debug, Clone, PartialEq, Eq, Hash)]
524#[repr(transparent)]
525pub struct ContinueExpr { 386pub struct ContinueExpr {
526 pub(crate) syntax: SyntaxNode, 387 pub(crate) syntax: SyntaxNode,
527} 388}
528unsafe impl TransparentNewType for ContinueExpr {
529 type Repr = rowan::SyntaxNode;
530}
531 389
532impl AstNode for ContinueExpr { 390impl AstNode for ContinueExpr {
533 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 391 fn cast(syntax: SyntaxNode) -> Option<Self> {
534 match syntax.kind() { 392 match syntax.kind() {
535 CONTINUE_EXPR => Some(ContinueExpr::from_repr(syntax.into_repr())), 393 CONTINUE_EXPR => Some(ContinueExpr { syntax }),
536 _ => None, 394 _ => None,
537 } 395 }
538 } 396 }
539 fn syntax(&self) -> &SyntaxNode { &self.syntax } 397 fn syntax(&self) -> &SyntaxNode { &self.syntax }
540} 398}
541 399
542impl ToOwned for ContinueExpr {
543 type Owned = TreeArc<ContinueExpr>;
544 fn to_owned(&self) -> TreeArc<ContinueExpr> { TreeArc::cast(self.syntax.to_owned()) }
545}
546
547 400
548impl ContinueExpr {} 401impl ContinueExpr {}
549 402
550// DynTraitType 403// DynTraitType
551#[derive(Debug, PartialEq, Eq, Hash)] 404#[derive(Debug, Clone, PartialEq, Eq, Hash)]
552#[repr(transparent)]
553pub struct DynTraitType { 405pub struct DynTraitType {
554 pub(crate) syntax: SyntaxNode, 406 pub(crate) syntax: SyntaxNode,
555} 407}
556unsafe impl TransparentNewType for DynTraitType {
557 type Repr = rowan::SyntaxNode;
558}
559 408
560impl AstNode for DynTraitType { 409impl AstNode for DynTraitType {
561 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 410 fn cast(syntax: SyntaxNode) -> Option<Self> {
562 match syntax.kind() { 411 match syntax.kind() {
563 DYN_TRAIT_TYPE => Some(DynTraitType::from_repr(syntax.into_repr())), 412 DYN_TRAIT_TYPE => Some(DynTraitType { syntax }),
564 _ => None, 413 _ => None,
565 } 414 }
566 } 415 }
567 fn syntax(&self) -> &SyntaxNode { &self.syntax } 416 fn syntax(&self) -> &SyntaxNode { &self.syntax }
568} 417}
569 418
570impl ToOwned for DynTraitType {
571 type Owned = TreeArc<DynTraitType>;
572 fn to_owned(&self) -> TreeArc<DynTraitType> { TreeArc::cast(self.syntax.to_owned()) }
573}
574
575 419
576impl ast::TypeBoundsOwner for DynTraitType {} 420impl ast::TypeBoundsOwner for DynTraitType {}
577impl DynTraitType {} 421impl DynTraitType {}
578 422
579// EnumDef 423// EnumDef
580#[derive(Debug, PartialEq, Eq, Hash)] 424#[derive(Debug, Clone, PartialEq, Eq, Hash)]
581#[repr(transparent)]
582pub struct EnumDef { 425pub struct EnumDef {
583 pub(crate) syntax: SyntaxNode, 426 pub(crate) syntax: SyntaxNode,
584} 427}
585unsafe impl TransparentNewType for EnumDef {
586 type Repr = rowan::SyntaxNode;
587}
588 428
589impl AstNode for EnumDef { 429impl AstNode for EnumDef {
590 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 430 fn cast(syntax: SyntaxNode) -> Option<Self> {
591 match syntax.kind() { 431 match syntax.kind() {
592 ENUM_DEF => Some(EnumDef::from_repr(syntax.into_repr())), 432 ENUM_DEF => Some(EnumDef { syntax }),
593 _ => None, 433 _ => None,
594 } 434 }
595 } 435 }
596 fn syntax(&self) -> &SyntaxNode { &self.syntax } 436 fn syntax(&self) -> &SyntaxNode { &self.syntax }
597} 437}
598 438
599impl ToOwned for EnumDef {
600 type Owned = TreeArc<EnumDef>;
601 fn to_owned(&self) -> TreeArc<EnumDef> { TreeArc::cast(self.syntax.to_owned()) }
602}
603
604 439
605impl ast::VisibilityOwner for EnumDef {} 440impl ast::VisibilityOwner for EnumDef {}
606impl ast::NameOwner for EnumDef {} 441impl ast::NameOwner for EnumDef {}
@@ -608,269 +443,247 @@ impl ast::TypeParamsOwner for EnumDef {}
608impl ast::AttrsOwner for EnumDef {} 443impl ast::AttrsOwner for EnumDef {}
609impl ast::DocCommentsOwner for EnumDef {} 444impl ast::DocCommentsOwner for EnumDef {}
610impl EnumDef { 445impl EnumDef {
611 pub fn variant_list(&self) -> Option<&EnumVariantList> { 446 pub fn variant_list(&self) -> Option<EnumVariantList> {
612 super::child_opt(self) 447 super::child_opt(self)
613 } 448 }
614} 449}
615 450
616// EnumVariant 451// EnumVariant
617#[derive(Debug, PartialEq, Eq, Hash)] 452#[derive(Debug, Clone, PartialEq, Eq, Hash)]
618#[repr(transparent)]
619pub struct EnumVariant { 453pub struct EnumVariant {
620 pub(crate) syntax: SyntaxNode, 454 pub(crate) syntax: SyntaxNode,
621} 455}
622unsafe impl TransparentNewType for EnumVariant {
623 type Repr = rowan::SyntaxNode;
624}
625 456
626impl AstNode for EnumVariant { 457impl AstNode for EnumVariant {
627 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 458 fn cast(syntax: SyntaxNode) -> Option<Self> {
628 match syntax.kind() { 459 match syntax.kind() {
629 ENUM_VARIANT => Some(EnumVariant::from_repr(syntax.into_repr())), 460 ENUM_VARIANT => Some(EnumVariant { syntax }),
630 _ => None, 461 _ => None,
631 } 462 }
632 } 463 }
633 fn syntax(&self) -> &SyntaxNode { &self.syntax } 464 fn syntax(&self) -> &SyntaxNode { &self.syntax }
634} 465}
635 466
636impl ToOwned for EnumVariant {
637 type Owned = TreeArc<EnumVariant>;
638 fn to_owned(&self) -> TreeArc<EnumVariant> { TreeArc::cast(self.syntax.to_owned()) }
639}
640
641 467
642impl ast::NameOwner for EnumVariant {} 468impl ast::NameOwner for EnumVariant {}
643impl ast::DocCommentsOwner for EnumVariant {} 469impl ast::DocCommentsOwner for EnumVariant {}
644impl ast::AttrsOwner for EnumVariant {} 470impl ast::AttrsOwner for EnumVariant {}
645impl EnumVariant { 471impl EnumVariant {
646 pub fn expr(&self) -> Option<&Expr> { 472 pub fn expr(&self) -> Option<Expr> {
647 super::child_opt(self) 473 super::child_opt(self)
648 } 474 }
649} 475}
650 476
651// EnumVariantList 477// EnumVariantList
652#[derive(Debug, PartialEq, Eq, Hash)] 478#[derive(Debug, Clone, PartialEq, Eq, Hash)]
653#[repr(transparent)]
654pub struct EnumVariantList { 479pub struct EnumVariantList {
655 pub(crate) syntax: SyntaxNode, 480 pub(crate) syntax: SyntaxNode,
656} 481}
657unsafe impl TransparentNewType for EnumVariantList {
658 type Repr = rowan::SyntaxNode;
659}
660 482
661impl AstNode for EnumVariantList { 483impl AstNode for EnumVariantList {
662 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 484 fn cast(syntax: SyntaxNode) -> Option<Self> {
663 match syntax.kind() { 485 match syntax.kind() {
664 ENUM_VARIANT_LIST => Some(EnumVariantList::from_repr(syntax.into_repr())), 486 ENUM_VARIANT_LIST => Some(EnumVariantList { syntax }),
665 _ => None, 487 _ => None,
666 } 488 }
667 } 489 }
668 fn syntax(&self) -> &SyntaxNode { &self.syntax } 490 fn syntax(&self) -> &SyntaxNode { &self.syntax }
669} 491}
670 492
671impl ToOwned for EnumVariantList {
672 type Owned = TreeArc<EnumVariantList>;
673 fn to_owned(&self) -> TreeArc<EnumVariantList> { TreeArc::cast(self.syntax.to_owned()) }
674}
675
676 493
677impl EnumVariantList { 494impl EnumVariantList {
678 pub fn variants(&self) -> impl Iterator<Item = &EnumVariant> { 495 pub fn variants(&self) -> impl Iterator<Item = EnumVariant> {
679 super::children(self) 496 super::children(self)
680 } 497 }
681} 498}
682 499
683// Expr 500// Expr
684#[derive(Debug, PartialEq, Eq, Hash)] 501#[derive(Debug, Clone, PartialEq, Eq, Hash)]
685#[repr(transparent)]
686pub struct Expr { 502pub struct Expr {
687 pub(crate) syntax: SyntaxNode, 503 pub(crate) syntax: SyntaxNode,
688} 504}
689unsafe impl TransparentNewType for Expr {
690 type Repr = rowan::SyntaxNode;
691}
692 505
693#[derive(Debug, Clone, Copy, PartialEq, Eq)] 506#[derive(Debug, Clone, PartialEq, Eq)]
694pub enum ExprKind<'a> { 507pub enum ExprKind {
695 TupleExpr(&'a TupleExpr), 508 TupleExpr(TupleExpr),
696 ArrayExpr(&'a ArrayExpr), 509 ArrayExpr(ArrayExpr),
697 ParenExpr(&'a ParenExpr), 510 ParenExpr(ParenExpr),
698 PathExpr(&'a PathExpr), 511 PathExpr(PathExpr),
699 LambdaExpr(&'a LambdaExpr), 512 LambdaExpr(LambdaExpr),
700 IfExpr(&'a IfExpr), 513 IfExpr(IfExpr),
701 LoopExpr(&'a LoopExpr), 514 LoopExpr(LoopExpr),
702 ForExpr(&'a ForExpr), 515 ForExpr(ForExpr),
703 WhileExpr(&'a WhileExpr), 516 WhileExpr(WhileExpr),
704 ContinueExpr(&'a ContinueExpr), 517 ContinueExpr(ContinueExpr),
705 BreakExpr(&'a BreakExpr), 518 BreakExpr(BreakExpr),
706 Label(&'a Label), 519 Label(Label),
707 BlockExpr(&'a BlockExpr), 520 BlockExpr(BlockExpr),
708 ReturnExpr(&'a ReturnExpr), 521 ReturnExpr(ReturnExpr),
709 MatchExpr(&'a MatchExpr), 522 MatchExpr(MatchExpr),
710 StructLit(&'a StructLit), 523 StructLit(StructLit),
711 CallExpr(&'a CallExpr), 524 CallExpr(CallExpr),
712 IndexExpr(&'a IndexExpr), 525 IndexExpr(IndexExpr),
713 MethodCallExpr(&'a MethodCallExpr), 526 MethodCallExpr(MethodCallExpr),
714 FieldExpr(&'a FieldExpr), 527 FieldExpr(FieldExpr),
715 TryExpr(&'a TryExpr), 528 TryExpr(TryExpr),
716 TryBlockExpr(&'a TryBlockExpr), 529 TryBlockExpr(TryBlockExpr),
717 CastExpr(&'a CastExpr), 530 CastExpr(CastExpr),
718 RefExpr(&'a RefExpr), 531 RefExpr(RefExpr),
719 PrefixExpr(&'a PrefixExpr), 532 PrefixExpr(PrefixExpr),
720 RangeExpr(&'a RangeExpr), 533 RangeExpr(RangeExpr),
721 BinExpr(&'a BinExpr), 534 BinExpr(BinExpr),
722 Literal(&'a Literal), 535 Literal(Literal),
723 MacroCall(&'a MacroCall), 536 MacroCall(MacroCall),
724} 537}
725impl<'a> From<&'a TupleExpr> for &'a Expr { 538impl From<TupleExpr> for Expr {
726 fn from(n: &'a TupleExpr) -> &'a Expr { 539 fn from(n: TupleExpr) -> Expr {
727 Expr::cast(&n.syntax).unwrap() 540 Expr::cast(n.syntax).unwrap()
728 } 541 }
729} 542}
730impl<'a> From<&'a ArrayExpr> for &'a Expr { 543impl From<ArrayExpr> for Expr {
731 fn from(n: &'a ArrayExpr) -> &'a Expr { 544 fn from(n: ArrayExpr) -> Expr {
732 Expr::cast(&n.syntax).unwrap() 545 Expr::cast(n.syntax).unwrap()
733 } 546 }
734} 547}
735impl<'a> From<&'a ParenExpr> for &'a Expr { 548impl From<ParenExpr> for Expr {
736 fn from(n: &'a ParenExpr) -> &'a Expr { 549 fn from(n: ParenExpr) -> Expr {
737 Expr::cast(&n.syntax).unwrap() 550 Expr::cast(n.syntax).unwrap()
738 } 551 }
739} 552}
740impl<'a> From<&'a PathExpr> for &'a Expr { 553impl From<PathExpr> for Expr {
741 fn from(n: &'a PathExpr) -> &'a Expr { 554 fn from(n: PathExpr) -> Expr {
742 Expr::cast(&n.syntax).unwrap() 555 Expr::cast(n.syntax).unwrap()
743 } 556 }
744} 557}
745impl<'a> From<&'a LambdaExpr> for &'a Expr { 558impl From<LambdaExpr> for Expr {
746 fn from(n: &'a LambdaExpr) -> &'a Expr { 559 fn from(n: LambdaExpr) -> Expr {
747 Expr::cast(&n.syntax).unwrap() 560 Expr::cast(n.syntax).unwrap()
748 } 561 }
749} 562}
750impl<'a> From<&'a IfExpr> for &'a Expr { 563impl From<IfExpr> for Expr {
751 fn from(n: &'a IfExpr) -> &'a Expr { 564 fn from(n: IfExpr) -> Expr {
752 Expr::cast(&n.syntax).unwrap() 565 Expr::cast(n.syntax).unwrap()
753 } 566 }
754} 567}
755impl<'a> From<&'a LoopExpr> for &'a Expr { 568impl From<LoopExpr> for Expr {
756 fn from(n: &'a LoopExpr) -> &'a Expr { 569 fn from(n: LoopExpr) -> Expr {
757 Expr::cast(&n.syntax).unwrap() 570 Expr::cast(n.syntax).unwrap()
758 } 571 }
759} 572}
760impl<'a> From<&'a ForExpr> for &'a Expr { 573impl From<ForExpr> for Expr {
761 fn from(n: &'a ForExpr) -> &'a Expr { 574 fn from(n: ForExpr) -> Expr {
762 Expr::cast(&n.syntax).unwrap() 575 Expr::cast(n.syntax).unwrap()
763 } 576 }
764} 577}
765impl<'a> From<&'a WhileExpr> for &'a Expr { 578impl From<WhileExpr> for Expr {
766 fn from(n: &'a WhileExpr) -> &'a Expr { 579 fn from(n: WhileExpr) -> Expr {
767 Expr::cast(&n.syntax).unwrap() 580 Expr::cast(n.syntax).unwrap()
768 } 581 }
769} 582}
770impl<'a> From<&'a ContinueExpr> for &'a Expr { 583impl From<ContinueExpr> for Expr {
771 fn from(n: &'a ContinueExpr) -> &'a Expr { 584 fn from(n: ContinueExpr) -> Expr {
772 Expr::cast(&n.syntax).unwrap() 585 Expr::cast(n.syntax).unwrap()
773 } 586 }
774} 587}
775impl<'a> From<&'a BreakExpr> for &'a Expr { 588impl From<BreakExpr> for Expr {
776 fn from(n: &'a BreakExpr) -> &'a Expr { 589 fn from(n: BreakExpr) -> Expr {
777 Expr::cast(&n.syntax).unwrap() 590 Expr::cast(n.syntax).unwrap()
778 } 591 }
779} 592}
780impl<'a> From<&'a Label> for &'a Expr { 593impl From<Label> for Expr {
781 fn from(n: &'a Label) -> &'a Expr { 594 fn from(n: Label) -> Expr {
782 Expr::cast(&n.syntax).unwrap() 595 Expr::cast(n.syntax).unwrap()
783 } 596 }
784} 597}
785impl<'a> From<&'a BlockExpr> for &'a Expr { 598impl From<BlockExpr> for Expr {
786 fn from(n: &'a BlockExpr) -> &'a Expr { 599 fn from(n: BlockExpr) -> Expr {
787 Expr::cast(&n.syntax).unwrap() 600 Expr::cast(n.syntax).unwrap()
788 } 601 }
789} 602}
790impl<'a> From<&'a ReturnExpr> for &'a Expr { 603impl From<ReturnExpr> for Expr {
791 fn from(n: &'a ReturnExpr) -> &'a Expr { 604 fn from(n: ReturnExpr) -> Expr {
792 Expr::cast(&n.syntax).unwrap() 605 Expr::cast(n.syntax).unwrap()
793 } 606 }
794} 607}
795impl<'a> From<&'a MatchExpr> for &'a Expr { 608impl From<MatchExpr> for Expr {
796 fn from(n: &'a MatchExpr) -> &'a Expr { 609 fn from(n: MatchExpr) -> Expr {
797 Expr::cast(&n.syntax).unwrap() 610 Expr::cast(n.syntax).unwrap()
798 } 611 }
799} 612}
800impl<'a> From<&'a StructLit> for &'a Expr { 613impl From<StructLit> for Expr {
801 fn from(n: &'a StructLit) -> &'a Expr { 614 fn from(n: StructLit) -> Expr {
802 Expr::cast(&n.syntax).unwrap() 615 Expr::cast(n.syntax).unwrap()
803 } 616 }
804} 617}
805impl<'a> From<&'a CallExpr> for &'a Expr { 618impl From<CallExpr> for Expr {
806 fn from(n: &'a CallExpr) -> &'a Expr { 619 fn from(n: CallExpr) -> Expr {
807 Expr::cast(&n.syntax).unwrap() 620 Expr::cast(n.syntax).unwrap()
808 } 621 }
809} 622}
810impl<'a> From<&'a IndexExpr> for &'a Expr { 623impl From<IndexExpr> for Expr {
811 fn from(n: &'a IndexExpr) -> &'a Expr { 624 fn from(n: IndexExpr) -> Expr {
812 Expr::cast(&n.syntax).unwrap() 625 Expr::cast(n.syntax).unwrap()
813 } 626 }
814} 627}
815impl<'a> From<&'a MethodCallExpr> for &'a Expr { 628impl From<MethodCallExpr> for Expr {
816 fn from(n: &'a MethodCallExpr) -> &'a Expr { 629 fn from(n: MethodCallExpr) -> Expr {
817 Expr::cast(&n.syntax).unwrap() 630 Expr::cast(n.syntax).unwrap()
818 } 631 }
819} 632}
820impl<'a> From<&'a FieldExpr> for &'a Expr { 633impl From<FieldExpr> for Expr {
821 fn from(n: &'a FieldExpr) -> &'a Expr { 634 fn from(n: FieldExpr) -> Expr {
822 Expr::cast(&n.syntax).unwrap() 635 Expr::cast(n.syntax).unwrap()
823 } 636 }
824} 637}
825impl<'a> From<&'a TryExpr> for &'a Expr { 638impl From<TryExpr> for Expr {
826 fn from(n: &'a TryExpr) -> &'a Expr { 639 fn from(n: TryExpr) -> Expr {
827 Expr::cast(&n.syntax).unwrap() 640 Expr::cast(n.syntax).unwrap()
828 } 641 }
829} 642}
830impl<'a> From<&'a TryBlockExpr> for &'a Expr { 643impl From<TryBlockExpr> for Expr {
831 fn from(n: &'a TryBlockExpr) -> &'a Expr { 644 fn from(n: TryBlockExpr) -> Expr {
832 Expr::cast(&n.syntax).unwrap() 645 Expr::cast(n.syntax).unwrap()
833 } 646 }
834} 647}
835impl<'a> From<&'a CastExpr> for &'a Expr { 648impl From<CastExpr> for Expr {
836 fn from(n: &'a CastExpr) -> &'a Expr { 649 fn from(n: CastExpr) -> Expr {
837 Expr::cast(&n.syntax).unwrap() 650 Expr::cast(n.syntax).unwrap()
838 } 651 }
839} 652}
840impl<'a> From<&'a RefExpr> for &'a Expr { 653impl From<RefExpr> for Expr {
841 fn from(n: &'a RefExpr) -> &'a Expr { 654 fn from(n: RefExpr) -> Expr {
842 Expr::cast(&n.syntax).unwrap() 655 Expr::cast(n.syntax).unwrap()
843 } 656 }
844} 657}
845impl<'a> From<&'a PrefixExpr> for &'a Expr { 658impl From<PrefixExpr> for Expr {
846 fn from(n: &'a PrefixExpr) -> &'a Expr { 659 fn from(n: PrefixExpr) -> Expr {
847 Expr::cast(&n.syntax).unwrap() 660 Expr::cast(n.syntax).unwrap()
848 } 661 }
849} 662}
850impl<'a> From<&'a RangeExpr> for &'a Expr { 663impl From<RangeExpr> for Expr {
851 fn from(n: &'a RangeExpr) -> &'a Expr { 664 fn from(n: RangeExpr) -> Expr {
852 Expr::cast(&n.syntax).unwrap() 665 Expr::cast(n.syntax).unwrap()
853 } 666 }
854} 667}
855impl<'a> From<&'a BinExpr> for &'a Expr { 668impl From<BinExpr> for Expr {
856 fn from(n: &'a BinExpr) -> &'a Expr { 669 fn from(n: BinExpr) -> Expr {
857 Expr::cast(&n.syntax).unwrap() 670 Expr::cast(n.syntax).unwrap()
858 } 671 }
859} 672}
860impl<'a> From<&'a Literal> for &'a Expr { 673impl From<Literal> for Expr {
861 fn from(n: &'a Literal) -> &'a Expr { 674 fn from(n: Literal) -> Expr {
862 Expr::cast(&n.syntax).unwrap() 675 Expr::cast(n.syntax).unwrap()
863 } 676 }
864} 677}
865impl<'a> From<&'a MacroCall> for &'a Expr { 678impl From<MacroCall> for Expr {
866 fn from(n: &'a MacroCall) -> &'a Expr { 679 fn from(n: MacroCall) -> Expr {
867 Expr::cast(&n.syntax).unwrap() 680 Expr::cast(n.syntax).unwrap()
868 } 681 }
869} 682}
870 683
871 684
872impl AstNode for Expr { 685impl AstNode for Expr {
873 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 686 fn cast(syntax: SyntaxNode) -> Option<Self> {
874 match syntax.kind() { 687 match syntax.kind() {
875 | TUPLE_EXPR 688 | TUPLE_EXPR
876 | ARRAY_EXPR 689 | ARRAY_EXPR
@@ -900,50 +713,45 @@ impl AstNode for Expr {
900 | RANGE_EXPR 713 | RANGE_EXPR
901 | BIN_EXPR 714 | BIN_EXPR
902 | LITERAL 715 | LITERAL
903 | MACRO_CALL => Some(Expr::from_repr(syntax.into_repr())), 716 | MACRO_CALL => Some(Expr { syntax }),
904 _ => None, 717 _ => None,
905 } 718 }
906 } 719 }
907 fn syntax(&self) -> &SyntaxNode { &self.syntax } 720 fn syntax(&self) -> &SyntaxNode { &self.syntax }
908} 721}
909 722
910impl ToOwned for Expr {
911 type Owned = TreeArc<Expr>;
912 fn to_owned(&self) -> TreeArc<Expr> { TreeArc::cast(self.syntax.to_owned()) }
913}
914
915impl Expr { 723impl Expr {
916 pub fn kind(&self) -> ExprKind { 724 pub fn kind(&self) -> ExprKind {
917 match self.syntax.kind() { 725 match self.syntax.kind() {
918 TUPLE_EXPR => ExprKind::TupleExpr(TupleExpr::cast(&self.syntax).unwrap()), 726 TUPLE_EXPR => ExprKind::TupleExpr(TupleExpr::cast(self.syntax.clone()).unwrap()),
919 ARRAY_EXPR => ExprKind::ArrayExpr(ArrayExpr::cast(&self.syntax).unwrap()), 727 ARRAY_EXPR => ExprKind::ArrayExpr(ArrayExpr::cast(self.syntax.clone()).unwrap()),
920 PAREN_EXPR => ExprKind::ParenExpr(ParenExpr::cast(&self.syntax).unwrap()), 728 PAREN_EXPR => ExprKind::ParenExpr(ParenExpr::cast(self.syntax.clone()).unwrap()),
921 PATH_EXPR => ExprKind::PathExpr(PathExpr::cast(&self.syntax).unwrap()), 729 PATH_EXPR => ExprKind::PathExpr(PathExpr::cast(self.syntax.clone()).unwrap()),
922 LAMBDA_EXPR => ExprKind::LambdaExpr(LambdaExpr::cast(&self.syntax).unwrap()), 730 LAMBDA_EXPR => ExprKind::LambdaExpr(LambdaExpr::cast(self.syntax.clone()).unwrap()),
923 IF_EXPR => ExprKind::IfExpr(IfExpr::cast(&self.syntax).unwrap()), 731 IF_EXPR => ExprKind::IfExpr(IfExpr::cast(self.syntax.clone()).unwrap()),
924 LOOP_EXPR => ExprKind::LoopExpr(LoopExpr::cast(&self.syntax).unwrap()), 732 LOOP_EXPR => ExprKind::LoopExpr(LoopExpr::cast(self.syntax.clone()).unwrap()),
925 FOR_EXPR => ExprKind::ForExpr(ForExpr::cast(&self.syntax).unwrap()), 733 FOR_EXPR => ExprKind::ForExpr(ForExpr::cast(self.syntax.clone()).unwrap()),
926 WHILE_EXPR => ExprKind::WhileExpr(WhileExpr::cast(&self.syntax).unwrap()), 734 WHILE_EXPR => ExprKind::WhileExpr(WhileExpr::cast(self.syntax.clone()).unwrap()),
927 CONTINUE_EXPR => ExprKind::ContinueExpr(ContinueExpr::cast(&self.syntax).unwrap()), 735 CONTINUE_EXPR => ExprKind::ContinueExpr(ContinueExpr::cast(self.syntax.clone()).unwrap()),
928 BREAK_EXPR => ExprKind::BreakExpr(BreakExpr::cast(&self.syntax).unwrap()), 736 BREAK_EXPR => ExprKind::BreakExpr(BreakExpr::cast(self.syntax.clone()).unwrap()),
929 LABEL => ExprKind::Label(Label::cast(&self.syntax).unwrap()), 737 LABEL => ExprKind::Label(Label::cast(self.syntax.clone()).unwrap()),
930 BLOCK_EXPR => ExprKind::BlockExpr(BlockExpr::cast(&self.syntax).unwrap()), 738 BLOCK_EXPR => ExprKind::BlockExpr(BlockExpr::cast(self.syntax.clone()).unwrap()),
931 RETURN_EXPR => ExprKind::ReturnExpr(ReturnExpr::cast(&self.syntax).unwrap()), 739 RETURN_EXPR => ExprKind::ReturnExpr(ReturnExpr::cast(self.syntax.clone()).unwrap()),
932 MATCH_EXPR => ExprKind::MatchExpr(MatchExpr::cast(&self.syntax).unwrap()), 740 MATCH_EXPR => ExprKind::MatchExpr(MatchExpr::cast(self.syntax.clone()).unwrap()),
933 STRUCT_LIT => ExprKind::StructLit(StructLit::cast(&self.syntax).unwrap()), 741 STRUCT_LIT => ExprKind::StructLit(StructLit::cast(self.syntax.clone()).unwrap()),
934 CALL_EXPR => ExprKind::CallExpr(CallExpr::cast(&self.syntax).unwrap()), 742 CALL_EXPR => ExprKind::CallExpr(CallExpr::cast(self.syntax.clone()).unwrap()),
935 INDEX_EXPR => ExprKind::IndexExpr(IndexExpr::cast(&self.syntax).unwrap()), 743 INDEX_EXPR => ExprKind::IndexExpr(IndexExpr::cast(self.syntax.clone()).unwrap()),
936 METHOD_CALL_EXPR => ExprKind::MethodCallExpr(MethodCallExpr::cast(&self.syntax).unwrap()), 744 METHOD_CALL_EXPR => ExprKind::MethodCallExpr(MethodCallExpr::cast(self.syntax.clone()).unwrap()),
937 FIELD_EXPR => ExprKind::FieldExpr(FieldExpr::cast(&self.syntax).unwrap()), 745 FIELD_EXPR => ExprKind::FieldExpr(FieldExpr::cast(self.syntax.clone()).unwrap()),
938 TRY_EXPR => ExprKind::TryExpr(TryExpr::cast(&self.syntax).unwrap()), 746 TRY_EXPR => ExprKind::TryExpr(TryExpr::cast(self.syntax.clone()).unwrap()),
939 TRY_BLOCK_EXPR => ExprKind::TryBlockExpr(TryBlockExpr::cast(&self.syntax).unwrap()), 747 TRY_BLOCK_EXPR => ExprKind::TryBlockExpr(TryBlockExpr::cast(self.syntax.clone()).unwrap()),
940 CAST_EXPR => ExprKind::CastExpr(CastExpr::cast(&self.syntax).unwrap()), 748 CAST_EXPR => ExprKind::CastExpr(CastExpr::cast(self.syntax.clone()).unwrap()),
941 REF_EXPR => ExprKind::RefExpr(RefExpr::cast(&self.syntax).unwrap()), 749 REF_EXPR => ExprKind::RefExpr(RefExpr::cast(self.syntax.clone()).unwrap()),
942 PREFIX_EXPR => ExprKind::PrefixExpr(PrefixExpr::cast(&self.syntax).unwrap()), 750 PREFIX_EXPR => ExprKind::PrefixExpr(PrefixExpr::cast(self.syntax.clone()).unwrap()),
943 RANGE_EXPR => ExprKind::RangeExpr(RangeExpr::cast(&self.syntax).unwrap()), 751 RANGE_EXPR => ExprKind::RangeExpr(RangeExpr::cast(self.syntax.clone()).unwrap()),
944 BIN_EXPR => ExprKind::BinExpr(BinExpr::cast(&self.syntax).unwrap()), 752 BIN_EXPR => ExprKind::BinExpr(BinExpr::cast(self.syntax.clone()).unwrap()),
945 LITERAL => ExprKind::Literal(Literal::cast(&self.syntax).unwrap()), 753 LITERAL => ExprKind::Literal(Literal::cast(self.syntax.clone()).unwrap()),
946 MACRO_CALL => ExprKind::MacroCall(MacroCall::cast(&self.syntax).unwrap()), 754 MACRO_CALL => ExprKind::MacroCall(MacroCall::cast(self.syntax.clone()).unwrap()),
947 _ => unreachable!(), 755 _ => unreachable!(),
948 } 756 }
949 } 757 }
@@ -952,203 +760,149 @@ impl Expr {
952impl Expr {} 760impl Expr {}
953 761
954// ExprStmt 762// ExprStmt
955#[derive(Debug, PartialEq, Eq, Hash)] 763#[derive(Debug, Clone, PartialEq, Eq, Hash)]
956#[repr(transparent)]
957pub struct ExprStmt { 764pub struct ExprStmt {
958 pub(crate) syntax: SyntaxNode, 765 pub(crate) syntax: SyntaxNode,
959} 766}
960unsafe impl TransparentNewType for ExprStmt {
961 type Repr = rowan::SyntaxNode;
962}
963 767
964impl AstNode for ExprStmt { 768impl AstNode for ExprStmt {
965 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 769 fn cast(syntax: SyntaxNode) -> Option<Self> {
966 match syntax.kind() { 770 match syntax.kind() {
967 EXPR_STMT => Some(ExprStmt::from_repr(syntax.into_repr())), 771 EXPR_STMT => Some(ExprStmt { syntax }),
968 _ => None, 772 _ => None,
969 } 773 }
970 } 774 }
971 fn syntax(&self) -> &SyntaxNode { &self.syntax } 775 fn syntax(&self) -> &SyntaxNode { &self.syntax }
972} 776}
973 777
974impl ToOwned for ExprStmt {
975 type Owned = TreeArc<ExprStmt>;
976 fn to_owned(&self) -> TreeArc<ExprStmt> { TreeArc::cast(self.syntax.to_owned()) }
977}
978
979 778
980impl ExprStmt { 779impl ExprStmt {
981 pub fn expr(&self) -> Option<&Expr> { 780 pub fn expr(&self) -> Option<Expr> {
982 super::child_opt(self) 781 super::child_opt(self)
983 } 782 }
984} 783}
985 784
986// ExternCrateItem 785// ExternCrateItem
987#[derive(Debug, PartialEq, Eq, Hash)] 786#[derive(Debug, Clone, PartialEq, Eq, Hash)]
988#[repr(transparent)]
989pub struct ExternCrateItem { 787pub struct ExternCrateItem {
990 pub(crate) syntax: SyntaxNode, 788 pub(crate) syntax: SyntaxNode,
991} 789}
992unsafe impl TransparentNewType for ExternCrateItem {
993 type Repr = rowan::SyntaxNode;
994}
995 790
996impl AstNode for ExternCrateItem { 791impl AstNode for ExternCrateItem {
997 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 792 fn cast(syntax: SyntaxNode) -> Option<Self> {
998 match syntax.kind() { 793 match syntax.kind() {
999 EXTERN_CRATE_ITEM => Some(ExternCrateItem::from_repr(syntax.into_repr())), 794 EXTERN_CRATE_ITEM => Some(ExternCrateItem { syntax }),
1000 _ => None, 795 _ => None,
1001 } 796 }
1002 } 797 }
1003 fn syntax(&self) -> &SyntaxNode { &self.syntax } 798 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1004} 799}
1005 800
1006impl ToOwned for ExternCrateItem {
1007 type Owned = TreeArc<ExternCrateItem>;
1008 fn to_owned(&self) -> TreeArc<ExternCrateItem> { TreeArc::cast(self.syntax.to_owned()) }
1009}
1010
1011 801
1012impl ExternCrateItem { 802impl ExternCrateItem {
1013 pub fn name_ref(&self) -> Option<&NameRef> { 803 pub fn name_ref(&self) -> Option<NameRef> {
1014 super::child_opt(self) 804 super::child_opt(self)
1015 } 805 }
1016 806
1017 pub fn alias(&self) -> Option<&Alias> { 807 pub fn alias(&self) -> Option<Alias> {
1018 super::child_opt(self) 808 super::child_opt(self)
1019 } 809 }
1020} 810}
1021 811
1022// FieldExpr 812// FieldExpr
1023#[derive(Debug, PartialEq, Eq, Hash)] 813#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1024#[repr(transparent)]
1025pub struct FieldExpr { 814pub struct FieldExpr {
1026 pub(crate) syntax: SyntaxNode, 815 pub(crate) syntax: SyntaxNode,
1027} 816}
1028unsafe impl TransparentNewType for FieldExpr {
1029 type Repr = rowan::SyntaxNode;
1030}
1031 817
1032impl AstNode for FieldExpr { 818impl AstNode for FieldExpr {
1033 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 819 fn cast(syntax: SyntaxNode) -> Option<Self> {
1034 match syntax.kind() { 820 match syntax.kind() {
1035 FIELD_EXPR => Some(FieldExpr::from_repr(syntax.into_repr())), 821 FIELD_EXPR => Some(FieldExpr { syntax }),
1036 _ => None, 822 _ => None,
1037 } 823 }
1038 } 824 }
1039 fn syntax(&self) -> &SyntaxNode { &self.syntax } 825 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1040} 826}
1041 827
1042impl ToOwned for FieldExpr {
1043 type Owned = TreeArc<FieldExpr>;
1044 fn to_owned(&self) -> TreeArc<FieldExpr> { TreeArc::cast(self.syntax.to_owned()) }
1045}
1046
1047 828
1048impl FieldExpr { 829impl FieldExpr {
1049 pub fn expr(&self) -> Option<&Expr> { 830 pub fn expr(&self) -> Option<Expr> {
1050 super::child_opt(self) 831 super::child_opt(self)
1051 } 832 }
1052 833
1053 pub fn name_ref(&self) -> Option<&NameRef> { 834 pub fn name_ref(&self) -> Option<NameRef> {
1054 super::child_opt(self) 835 super::child_opt(self)
1055 } 836 }
1056} 837}
1057 838
1058// FieldPat 839// FieldPat
1059#[derive(Debug, PartialEq, Eq, Hash)] 840#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1060#[repr(transparent)]
1061pub struct FieldPat { 841pub struct FieldPat {
1062 pub(crate) syntax: SyntaxNode, 842 pub(crate) syntax: SyntaxNode,
1063} 843}
1064unsafe impl TransparentNewType for FieldPat {
1065 type Repr = rowan::SyntaxNode;
1066}
1067 844
1068impl AstNode for FieldPat { 845impl AstNode for FieldPat {
1069 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 846 fn cast(syntax: SyntaxNode) -> Option<Self> {
1070 match syntax.kind() { 847 match syntax.kind() {
1071 FIELD_PAT => Some(FieldPat::from_repr(syntax.into_repr())), 848 FIELD_PAT => Some(FieldPat { syntax }),
1072 _ => None, 849 _ => None,
1073 } 850 }
1074 } 851 }
1075 fn syntax(&self) -> &SyntaxNode { &self.syntax } 852 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1076} 853}
1077 854
1078impl ToOwned for FieldPat {
1079 type Owned = TreeArc<FieldPat>;
1080 fn to_owned(&self) -> TreeArc<FieldPat> { TreeArc::cast(self.syntax.to_owned()) }
1081}
1082
1083 855
1084impl ast::NameOwner for FieldPat {} 856impl ast::NameOwner for FieldPat {}
1085impl FieldPat { 857impl FieldPat {
1086 pub fn pat(&self) -> Option<&Pat> { 858 pub fn pat(&self) -> Option<Pat> {
1087 super::child_opt(self) 859 super::child_opt(self)
1088 } 860 }
1089} 861}
1090 862
1091// FieldPatList 863// FieldPatList
1092#[derive(Debug, PartialEq, Eq, Hash)] 864#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1093#[repr(transparent)]
1094pub struct FieldPatList { 865pub struct FieldPatList {
1095 pub(crate) syntax: SyntaxNode, 866 pub(crate) syntax: SyntaxNode,
1096} 867}
1097unsafe impl TransparentNewType for FieldPatList {
1098 type Repr = rowan::SyntaxNode;
1099}
1100 868
1101impl AstNode for FieldPatList { 869impl AstNode for FieldPatList {
1102 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 870 fn cast(syntax: SyntaxNode) -> Option<Self> {
1103 match syntax.kind() { 871 match syntax.kind() {
1104 FIELD_PAT_LIST => Some(FieldPatList::from_repr(syntax.into_repr())), 872 FIELD_PAT_LIST => Some(FieldPatList { syntax }),
1105 _ => None, 873 _ => None,
1106 } 874 }
1107 } 875 }
1108 fn syntax(&self) -> &SyntaxNode { &self.syntax } 876 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1109} 877}
1110 878
1111impl ToOwned for FieldPatList {
1112 type Owned = TreeArc<FieldPatList>;
1113 fn to_owned(&self) -> TreeArc<FieldPatList> { TreeArc::cast(self.syntax.to_owned()) }
1114}
1115
1116 879
1117impl FieldPatList { 880impl FieldPatList {
1118 pub fn field_pats(&self) -> impl Iterator<Item = &FieldPat> { 881 pub fn field_pats(&self) -> impl Iterator<Item = FieldPat> {
1119 super::children(self) 882 super::children(self)
1120 } 883 }
1121 884
1122 pub fn bind_pats(&self) -> impl Iterator<Item = &BindPat> { 885 pub fn bind_pats(&self) -> impl Iterator<Item = BindPat> {
1123 super::children(self) 886 super::children(self)
1124 } 887 }
1125} 888}
1126 889
1127// FnDef 890// FnDef
1128#[derive(Debug, PartialEq, Eq, Hash)] 891#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1129#[repr(transparent)]
1130pub struct FnDef { 892pub struct FnDef {
1131 pub(crate) syntax: SyntaxNode, 893 pub(crate) syntax: SyntaxNode,
1132} 894}
1133unsafe impl TransparentNewType for FnDef {
1134 type Repr = rowan::SyntaxNode;
1135}
1136 895
1137impl AstNode for FnDef { 896impl AstNode for FnDef {
1138 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 897 fn cast(syntax: SyntaxNode) -> Option<Self> {
1139 match syntax.kind() { 898 match syntax.kind() {
1140 FN_DEF => Some(FnDef::from_repr(syntax.into_repr())), 899 FN_DEF => Some(FnDef { syntax }),
1141 _ => None, 900 _ => None,
1142 } 901 }
1143 } 902 }
1144 fn syntax(&self) -> &SyntaxNode { &self.syntax } 903 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1145} 904}
1146 905
1147impl ToOwned for FnDef {
1148 type Owned = TreeArc<FnDef>;
1149 fn to_owned(&self) -> TreeArc<FnDef> { TreeArc::cast(self.syntax.to_owned()) }
1150}
1151
1152 906
1153impl ast::VisibilityOwner for FnDef {} 907impl ast::VisibilityOwner for FnDef {}
1154impl ast::NameOwner for FnDef {} 908impl ast::NameOwner for FnDef {}
@@ -1156,246 +910,192 @@ impl ast::TypeParamsOwner for FnDef {}
1156impl ast::AttrsOwner for FnDef {} 910impl ast::AttrsOwner for FnDef {}
1157impl ast::DocCommentsOwner for FnDef {} 911impl ast::DocCommentsOwner for FnDef {}
1158impl FnDef { 912impl FnDef {
1159 pub fn param_list(&self) -> Option<&ParamList> { 913 pub fn param_list(&self) -> Option<ParamList> {
1160 super::child_opt(self) 914 super::child_opt(self)
1161 } 915 }
1162 916
1163 pub fn body(&self) -> Option<&Block> { 917 pub fn body(&self) -> Option<Block> {
1164 super::child_opt(self) 918 super::child_opt(self)
1165 } 919 }
1166 920
1167 pub fn ret_type(&self) -> Option<&RetType> { 921 pub fn ret_type(&self) -> Option<RetType> {
1168 super::child_opt(self) 922 super::child_opt(self)
1169 } 923 }
1170} 924}
1171 925
1172// FnPointerType 926// FnPointerType
1173#[derive(Debug, PartialEq, Eq, Hash)] 927#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1174#[repr(transparent)]
1175pub struct FnPointerType { 928pub struct FnPointerType {
1176 pub(crate) syntax: SyntaxNode, 929 pub(crate) syntax: SyntaxNode,
1177} 930}
1178unsafe impl TransparentNewType for FnPointerType {
1179 type Repr = rowan::SyntaxNode;
1180}
1181 931
1182impl AstNode for FnPointerType { 932impl AstNode for FnPointerType {
1183 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 933 fn cast(syntax: SyntaxNode) -> Option<Self> {
1184 match syntax.kind() { 934 match syntax.kind() {
1185 FN_POINTER_TYPE => Some(FnPointerType::from_repr(syntax.into_repr())), 935 FN_POINTER_TYPE => Some(FnPointerType { syntax }),
1186 _ => None, 936 _ => None,
1187 } 937 }
1188 } 938 }
1189 fn syntax(&self) -> &SyntaxNode { &self.syntax } 939 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1190} 940}
1191 941
1192impl ToOwned for FnPointerType {
1193 type Owned = TreeArc<FnPointerType>;
1194 fn to_owned(&self) -> TreeArc<FnPointerType> { TreeArc::cast(self.syntax.to_owned()) }
1195}
1196
1197 942
1198impl FnPointerType { 943impl FnPointerType {
1199 pub fn param_list(&self) -> Option<&ParamList> { 944 pub fn param_list(&self) -> Option<ParamList> {
1200 super::child_opt(self) 945 super::child_opt(self)
1201 } 946 }
1202 947
1203 pub fn ret_type(&self) -> Option<&RetType> { 948 pub fn ret_type(&self) -> Option<RetType> {
1204 super::child_opt(self) 949 super::child_opt(self)
1205 } 950 }
1206} 951}
1207 952
1208// ForExpr 953// ForExpr
1209#[derive(Debug, PartialEq, Eq, Hash)] 954#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1210#[repr(transparent)]
1211pub struct ForExpr { 955pub struct ForExpr {
1212 pub(crate) syntax: SyntaxNode, 956 pub(crate) syntax: SyntaxNode,
1213} 957}
1214unsafe impl TransparentNewType for ForExpr {
1215 type Repr = rowan::SyntaxNode;
1216}
1217 958
1218impl AstNode for ForExpr { 959impl AstNode for ForExpr {
1219 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 960 fn cast(syntax: SyntaxNode) -> Option<Self> {
1220 match syntax.kind() { 961 match syntax.kind() {
1221 FOR_EXPR => Some(ForExpr::from_repr(syntax.into_repr())), 962 FOR_EXPR => Some(ForExpr { syntax }),
1222 _ => None, 963 _ => None,
1223 } 964 }
1224 } 965 }
1225 fn syntax(&self) -> &SyntaxNode { &self.syntax } 966 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1226} 967}
1227 968
1228impl ToOwned for ForExpr {
1229 type Owned = TreeArc<ForExpr>;
1230 fn to_owned(&self) -> TreeArc<ForExpr> { TreeArc::cast(self.syntax.to_owned()) }
1231}
1232
1233 969
1234impl ast::LoopBodyOwner for ForExpr {} 970impl ast::LoopBodyOwner for ForExpr {}
1235impl ForExpr { 971impl ForExpr {
1236 pub fn pat(&self) -> Option<&Pat> { 972 pub fn pat(&self) -> Option<Pat> {
1237 super::child_opt(self) 973 super::child_opt(self)
1238 } 974 }
1239 975
1240 pub fn iterable(&self) -> Option<&Expr> { 976 pub fn iterable(&self) -> Option<Expr> {
1241 super::child_opt(self) 977 super::child_opt(self)
1242 } 978 }
1243} 979}
1244 980
1245// ForType 981// ForType
1246#[derive(Debug, PartialEq, Eq, Hash)] 982#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1247#[repr(transparent)]
1248pub struct ForType { 983pub struct ForType {
1249 pub(crate) syntax: SyntaxNode, 984 pub(crate) syntax: SyntaxNode,
1250} 985}
1251unsafe impl TransparentNewType for ForType {
1252 type Repr = rowan::SyntaxNode;
1253}
1254 986
1255impl AstNode for ForType { 987impl AstNode for ForType {
1256 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 988 fn cast(syntax: SyntaxNode) -> Option<Self> {
1257 match syntax.kind() { 989 match syntax.kind() {
1258 FOR_TYPE => Some(ForType::from_repr(syntax.into_repr())), 990 FOR_TYPE => Some(ForType { syntax }),
1259 _ => None, 991 _ => None,
1260 } 992 }
1261 } 993 }
1262 fn syntax(&self) -> &SyntaxNode { &self.syntax } 994 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1263} 995}
1264 996
1265impl ToOwned for ForType {
1266 type Owned = TreeArc<ForType>;
1267 fn to_owned(&self) -> TreeArc<ForType> { TreeArc::cast(self.syntax.to_owned()) }
1268}
1269
1270 997
1271impl ForType { 998impl ForType {
1272 pub fn type_ref(&self) -> Option<&TypeRef> { 999 pub fn type_ref(&self) -> Option<TypeRef> {
1273 super::child_opt(self) 1000 super::child_opt(self)
1274 } 1001 }
1275} 1002}
1276 1003
1277// IfExpr 1004// IfExpr
1278#[derive(Debug, PartialEq, Eq, Hash)] 1005#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1279#[repr(transparent)]
1280pub struct IfExpr { 1006pub struct IfExpr {
1281 pub(crate) syntax: SyntaxNode, 1007 pub(crate) syntax: SyntaxNode,
1282} 1008}
1283unsafe impl TransparentNewType for IfExpr {
1284 type Repr = rowan::SyntaxNode;
1285}
1286 1009
1287impl AstNode for IfExpr { 1010impl AstNode for IfExpr {
1288 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1011 fn cast(syntax: SyntaxNode) -> Option<Self> {
1289 match syntax.kind() { 1012 match syntax.kind() {
1290 IF_EXPR => Some(IfExpr::from_repr(syntax.into_repr())), 1013 IF_EXPR => Some(IfExpr { syntax }),
1291 _ => None, 1014 _ => None,
1292 } 1015 }
1293 } 1016 }
1294 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1017 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1295} 1018}
1296 1019
1297impl ToOwned for IfExpr {
1298 type Owned = TreeArc<IfExpr>;
1299 fn to_owned(&self) -> TreeArc<IfExpr> { TreeArc::cast(self.syntax.to_owned()) }
1300}
1301
1302 1020
1303impl IfExpr { 1021impl IfExpr {
1304 pub fn condition(&self) -> Option<&Condition> { 1022 pub fn condition(&self) -> Option<Condition> {
1305 super::child_opt(self) 1023 super::child_opt(self)
1306 } 1024 }
1307} 1025}
1308 1026
1309// ImplBlock 1027// ImplBlock
1310#[derive(Debug, PartialEq, Eq, Hash)] 1028#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1311#[repr(transparent)]
1312pub struct ImplBlock { 1029pub struct ImplBlock {
1313 pub(crate) syntax: SyntaxNode, 1030 pub(crate) syntax: SyntaxNode,
1314} 1031}
1315unsafe impl TransparentNewType for ImplBlock {
1316 type Repr = rowan::SyntaxNode;
1317}
1318 1032
1319impl AstNode for ImplBlock { 1033impl AstNode for ImplBlock {
1320 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1034 fn cast(syntax: SyntaxNode) -> Option<Self> {
1321 match syntax.kind() { 1035 match syntax.kind() {
1322 IMPL_BLOCK => Some(ImplBlock::from_repr(syntax.into_repr())), 1036 IMPL_BLOCK => Some(ImplBlock { syntax }),
1323 _ => None, 1037 _ => None,
1324 } 1038 }
1325 } 1039 }
1326 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1040 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1327} 1041}
1328 1042
1329impl ToOwned for ImplBlock {
1330 type Owned = TreeArc<ImplBlock>;
1331 fn to_owned(&self) -> TreeArc<ImplBlock> { TreeArc::cast(self.syntax.to_owned()) }
1332}
1333
1334 1043
1335impl ast::TypeParamsOwner for ImplBlock {} 1044impl ast::TypeParamsOwner for ImplBlock {}
1336impl ast::AttrsOwner for ImplBlock {} 1045impl ast::AttrsOwner for ImplBlock {}
1337impl ImplBlock { 1046impl ImplBlock {
1338 pub fn item_list(&self) -> Option<&ItemList> { 1047 pub fn item_list(&self) -> Option<ItemList> {
1339 super::child_opt(self) 1048 super::child_opt(self)
1340 } 1049 }
1341} 1050}
1342 1051
1343// ImplItem 1052// ImplItem
1344#[derive(Debug, PartialEq, Eq, Hash)] 1053#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1345#[repr(transparent)]
1346pub struct ImplItem { 1054pub struct ImplItem {
1347 pub(crate) syntax: SyntaxNode, 1055 pub(crate) syntax: SyntaxNode,
1348} 1056}
1349unsafe impl TransparentNewType for ImplItem {
1350 type Repr = rowan::SyntaxNode;
1351}
1352 1057
1353#[derive(Debug, Clone, Copy, PartialEq, Eq)] 1058#[derive(Debug, Clone, PartialEq, Eq)]
1354pub enum ImplItemKind<'a> { 1059pub enum ImplItemKind {
1355 FnDef(&'a FnDef), 1060 FnDef(FnDef),
1356 TypeAliasDef(&'a TypeAliasDef), 1061 TypeAliasDef(TypeAliasDef),
1357 ConstDef(&'a ConstDef), 1062 ConstDef(ConstDef),
1358} 1063}
1359impl<'a> From<&'a FnDef> for &'a ImplItem { 1064impl From<FnDef> for ImplItem {
1360 fn from(n: &'a FnDef) -> &'a ImplItem { 1065 fn from(n: FnDef) -> ImplItem {
1361 ImplItem::cast(&n.syntax).unwrap() 1066 ImplItem::cast(n.syntax).unwrap()
1362 } 1067 }
1363} 1068}
1364impl<'a> From<&'a TypeAliasDef> for &'a ImplItem { 1069impl From<TypeAliasDef> for ImplItem {
1365 fn from(n: &'a TypeAliasDef) -> &'a ImplItem { 1070 fn from(n: TypeAliasDef) -> ImplItem {
1366 ImplItem::cast(&n.syntax).unwrap() 1071 ImplItem::cast(n.syntax).unwrap()
1367 } 1072 }
1368} 1073}
1369impl<'a> From<&'a ConstDef> for &'a ImplItem { 1074impl From<ConstDef> for ImplItem {
1370 fn from(n: &'a ConstDef) -> &'a ImplItem { 1075 fn from(n: ConstDef) -> ImplItem {
1371 ImplItem::cast(&n.syntax).unwrap() 1076 ImplItem::cast(n.syntax).unwrap()
1372 } 1077 }
1373} 1078}
1374 1079
1375 1080
1376impl AstNode for ImplItem { 1081impl AstNode for ImplItem {
1377 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1082 fn cast(syntax: SyntaxNode) -> Option<Self> {
1378 match syntax.kind() { 1083 match syntax.kind() {
1379 | FN_DEF 1084 | FN_DEF
1380 | TYPE_ALIAS_DEF 1085 | TYPE_ALIAS_DEF
1381 | CONST_DEF => Some(ImplItem::from_repr(syntax.into_repr())), 1086 | CONST_DEF => Some(ImplItem { syntax }),
1382 _ => None, 1087 _ => None,
1383 } 1088 }
1384 } 1089 }
1385 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1090 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1386} 1091}
1387 1092
1388impl ToOwned for ImplItem {
1389 type Owned = TreeArc<ImplItem>;
1390 fn to_owned(&self) -> TreeArc<ImplItem> { TreeArc::cast(self.syntax.to_owned()) }
1391}
1392
1393impl ImplItem { 1093impl ImplItem {
1394 pub fn kind(&self) -> ImplItemKind { 1094 pub fn kind(&self) -> ImplItemKind {
1395 match self.syntax.kind() { 1095 match self.syntax.kind() {
1396 FN_DEF => ImplItemKind::FnDef(FnDef::cast(&self.syntax).unwrap()), 1096 FN_DEF => ImplItemKind::FnDef(FnDef::cast(self.syntax.clone()).unwrap()),
1397 TYPE_ALIAS_DEF => ImplItemKind::TypeAliasDef(TypeAliasDef::cast(&self.syntax).unwrap()), 1097 TYPE_ALIAS_DEF => ImplItemKind::TypeAliasDef(TypeAliasDef::cast(self.syntax.clone()).unwrap()),
1398 CONST_DEF => ImplItemKind::ConstDef(ConstDef::cast(&self.syntax).unwrap()), 1098 CONST_DEF => ImplItemKind::ConstDef(ConstDef::cast(self.syntax.clone()).unwrap()),
1399 _ => unreachable!(), 1099 _ => unreachable!(),
1400 } 1100 }
1401 } 1101 }
@@ -1404,750 +1104,566 @@ impl ImplItem {
1404impl ImplItem {} 1104impl ImplItem {}
1405 1105
1406// ImplTraitType 1106// ImplTraitType
1407#[derive(Debug, PartialEq, Eq, Hash)] 1107#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1408#[repr(transparent)]
1409pub struct ImplTraitType { 1108pub struct ImplTraitType {
1410 pub(crate) syntax: SyntaxNode, 1109 pub(crate) syntax: SyntaxNode,
1411} 1110}
1412unsafe impl TransparentNewType for ImplTraitType {
1413 type Repr = rowan::SyntaxNode;
1414}
1415 1111
1416impl AstNode for ImplTraitType { 1112impl AstNode for ImplTraitType {
1417 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1113 fn cast(syntax: SyntaxNode) -> Option<Self> {
1418 match syntax.kind() { 1114 match syntax.kind() {
1419 IMPL_TRAIT_TYPE => Some(ImplTraitType::from_repr(syntax.into_repr())), 1115 IMPL_TRAIT_TYPE => Some(ImplTraitType { syntax }),
1420 _ => None, 1116 _ => None,
1421 } 1117 }
1422 } 1118 }
1423 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1119 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1424} 1120}
1425 1121
1426impl ToOwned for ImplTraitType {
1427 type Owned = TreeArc<ImplTraitType>;
1428 fn to_owned(&self) -> TreeArc<ImplTraitType> { TreeArc::cast(self.syntax.to_owned()) }
1429}
1430
1431 1122
1432impl ast::TypeBoundsOwner for ImplTraitType {} 1123impl ast::TypeBoundsOwner for ImplTraitType {}
1433impl ImplTraitType {} 1124impl ImplTraitType {}
1434 1125
1435// IndexExpr 1126// IndexExpr
1436#[derive(Debug, PartialEq, Eq, Hash)] 1127#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1437#[repr(transparent)]
1438pub struct IndexExpr { 1128pub struct IndexExpr {
1439 pub(crate) syntax: SyntaxNode, 1129 pub(crate) syntax: SyntaxNode,
1440} 1130}
1441unsafe impl TransparentNewType for IndexExpr {
1442 type Repr = rowan::SyntaxNode;
1443}
1444 1131
1445impl AstNode for IndexExpr { 1132impl AstNode for IndexExpr {
1446 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1133 fn cast(syntax: SyntaxNode) -> Option<Self> {
1447 match syntax.kind() { 1134 match syntax.kind() {
1448 INDEX_EXPR => Some(IndexExpr::from_repr(syntax.into_repr())), 1135 INDEX_EXPR => Some(IndexExpr { syntax }),
1449 _ => None, 1136 _ => None,
1450 } 1137 }
1451 } 1138 }
1452 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1139 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1453} 1140}
1454 1141
1455impl ToOwned for IndexExpr {
1456 type Owned = TreeArc<IndexExpr>;
1457 fn to_owned(&self) -> TreeArc<IndexExpr> { TreeArc::cast(self.syntax.to_owned()) }
1458}
1459
1460 1142
1461impl IndexExpr {} 1143impl IndexExpr {}
1462 1144
1463// ItemList 1145// ItemList
1464#[derive(Debug, PartialEq, Eq, Hash)] 1146#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1465#[repr(transparent)]
1466pub struct ItemList { 1147pub struct ItemList {
1467 pub(crate) syntax: SyntaxNode, 1148 pub(crate) syntax: SyntaxNode,
1468} 1149}
1469unsafe impl TransparentNewType for ItemList {
1470 type Repr = rowan::SyntaxNode;
1471}
1472 1150
1473impl AstNode for ItemList { 1151impl AstNode for ItemList {
1474 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1152 fn cast(syntax: SyntaxNode) -> Option<Self> {
1475 match syntax.kind() { 1153 match syntax.kind() {
1476 ITEM_LIST => Some(ItemList::from_repr(syntax.into_repr())), 1154 ITEM_LIST => Some(ItemList { syntax }),
1477 _ => None, 1155 _ => None,
1478 } 1156 }
1479 } 1157 }
1480 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1158 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1481} 1159}
1482 1160
1483impl ToOwned for ItemList {
1484 type Owned = TreeArc<ItemList>;
1485 fn to_owned(&self) -> TreeArc<ItemList> { TreeArc::cast(self.syntax.to_owned()) }
1486}
1487
1488 1161
1489impl ast::FnDefOwner for ItemList {} 1162impl ast::FnDefOwner for ItemList {}
1490impl ast::ModuleItemOwner for ItemList {} 1163impl ast::ModuleItemOwner for ItemList {}
1491impl ItemList { 1164impl ItemList {
1492 pub fn impl_items(&self) -> impl Iterator<Item = &ImplItem> { 1165 pub fn impl_items(&self) -> impl Iterator<Item = ImplItem> {
1493 super::children(self) 1166 super::children(self)
1494 } 1167 }
1495} 1168}
1496 1169
1497// Label 1170// Label
1498#[derive(Debug, PartialEq, Eq, Hash)] 1171#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1499#[repr(transparent)]
1500pub struct Label { 1172pub struct Label {
1501 pub(crate) syntax: SyntaxNode, 1173 pub(crate) syntax: SyntaxNode,
1502} 1174}
1503unsafe impl TransparentNewType for Label {
1504 type Repr = rowan::SyntaxNode;
1505}
1506 1175
1507impl AstNode for Label { 1176impl AstNode for Label {
1508 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1177 fn cast(syntax: SyntaxNode) -> Option<Self> {
1509 match syntax.kind() { 1178 match syntax.kind() {
1510 LABEL => Some(Label::from_repr(syntax.into_repr())), 1179 LABEL => Some(Label { syntax }),
1511 _ => None, 1180 _ => None,
1512 } 1181 }
1513 } 1182 }
1514 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1183 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1515} 1184}
1516 1185
1517impl ToOwned for Label {
1518 type Owned = TreeArc<Label>;
1519 fn to_owned(&self) -> TreeArc<Label> { TreeArc::cast(self.syntax.to_owned()) }
1520}
1521
1522 1186
1523impl Label {} 1187impl Label {}
1524 1188
1525// LambdaExpr 1189// LambdaExpr
1526#[derive(Debug, PartialEq, Eq, Hash)] 1190#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1527#[repr(transparent)]
1528pub struct LambdaExpr { 1191pub struct LambdaExpr {
1529 pub(crate) syntax: SyntaxNode, 1192 pub(crate) syntax: SyntaxNode,
1530} 1193}
1531unsafe impl TransparentNewType for LambdaExpr {
1532 type Repr = rowan::SyntaxNode;
1533}
1534 1194
1535impl AstNode for LambdaExpr { 1195impl AstNode for LambdaExpr {
1536 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1196 fn cast(syntax: SyntaxNode) -> Option<Self> {
1537 match syntax.kind() { 1197 match syntax.kind() {
1538 LAMBDA_EXPR => Some(LambdaExpr::from_repr(syntax.into_repr())), 1198 LAMBDA_EXPR => Some(LambdaExpr { syntax }),
1539 _ => None, 1199 _ => None,
1540 } 1200 }
1541 } 1201 }
1542 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1202 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1543} 1203}
1544 1204
1545impl ToOwned for LambdaExpr {
1546 type Owned = TreeArc<LambdaExpr>;
1547 fn to_owned(&self) -> TreeArc<LambdaExpr> { TreeArc::cast(self.syntax.to_owned()) }
1548}
1549
1550 1205
1551impl LambdaExpr { 1206impl LambdaExpr {
1552 pub fn param_list(&self) -> Option<&ParamList> { 1207 pub fn param_list(&self) -> Option<ParamList> {
1553 super::child_opt(self) 1208 super::child_opt(self)
1554 } 1209 }
1555 1210
1556 pub fn body(&self) -> Option<&Expr> { 1211 pub fn body(&self) -> Option<Expr> {
1557 super::child_opt(self) 1212 super::child_opt(self)
1558 } 1213 }
1559} 1214}
1560 1215
1561// LetStmt 1216// LetStmt
1562#[derive(Debug, PartialEq, Eq, Hash)] 1217#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1563#[repr(transparent)]
1564pub struct LetStmt { 1218pub struct LetStmt {
1565 pub(crate) syntax: SyntaxNode, 1219 pub(crate) syntax: SyntaxNode,
1566} 1220}
1567unsafe impl TransparentNewType for LetStmt {
1568 type Repr = rowan::SyntaxNode;
1569}
1570 1221
1571impl AstNode for LetStmt { 1222impl AstNode for LetStmt {
1572 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1223 fn cast(syntax: SyntaxNode) -> Option<Self> {
1573 match syntax.kind() { 1224 match syntax.kind() {
1574 LET_STMT => Some(LetStmt::from_repr(syntax.into_repr())), 1225 LET_STMT => Some(LetStmt { syntax }),
1575 _ => None, 1226 _ => None,
1576 } 1227 }
1577 } 1228 }
1578 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1229 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1579} 1230}
1580 1231
1581impl ToOwned for LetStmt {
1582 type Owned = TreeArc<LetStmt>;
1583 fn to_owned(&self) -> TreeArc<LetStmt> { TreeArc::cast(self.syntax.to_owned()) }
1584}
1585
1586 1232
1587impl ast::TypeAscriptionOwner for LetStmt {} 1233impl ast::TypeAscriptionOwner for LetStmt {}
1588impl LetStmt { 1234impl LetStmt {
1589 pub fn pat(&self) -> Option<&Pat> { 1235 pub fn pat(&self) -> Option<Pat> {
1590 super::child_opt(self) 1236 super::child_opt(self)
1591 } 1237 }
1592 1238
1593 pub fn initializer(&self) -> Option<&Expr> { 1239 pub fn initializer(&self) -> Option<Expr> {
1594 super::child_opt(self) 1240 super::child_opt(self)
1595 } 1241 }
1596} 1242}
1597 1243
1598// LifetimeArg 1244// LifetimeArg
1599#[derive(Debug, PartialEq, Eq, Hash)] 1245#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1600#[repr(transparent)]
1601pub struct LifetimeArg { 1246pub struct LifetimeArg {
1602 pub(crate) syntax: SyntaxNode, 1247 pub(crate) syntax: SyntaxNode,
1603} 1248}
1604unsafe impl TransparentNewType for LifetimeArg {
1605 type Repr = rowan::SyntaxNode;
1606}
1607 1249
1608impl AstNode for LifetimeArg { 1250impl AstNode for LifetimeArg {
1609 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1251 fn cast(syntax: SyntaxNode) -> Option<Self> {
1610 match syntax.kind() { 1252 match syntax.kind() {
1611 LIFETIME_ARG => Some(LifetimeArg::from_repr(syntax.into_repr())), 1253 LIFETIME_ARG => Some(LifetimeArg { syntax }),
1612 _ => None, 1254 _ => None,
1613 } 1255 }
1614 } 1256 }
1615 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1257 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1616} 1258}
1617 1259
1618impl ToOwned for LifetimeArg {
1619 type Owned = TreeArc<LifetimeArg>;
1620 fn to_owned(&self) -> TreeArc<LifetimeArg> { TreeArc::cast(self.syntax.to_owned()) }
1621}
1622
1623 1260
1624impl LifetimeArg {} 1261impl LifetimeArg {}
1625 1262
1626// LifetimeParam 1263// LifetimeParam
1627#[derive(Debug, PartialEq, Eq, Hash)] 1264#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1628#[repr(transparent)]
1629pub struct LifetimeParam { 1265pub struct LifetimeParam {
1630 pub(crate) syntax: SyntaxNode, 1266 pub(crate) syntax: SyntaxNode,
1631} 1267}
1632unsafe impl TransparentNewType for LifetimeParam {
1633 type Repr = rowan::SyntaxNode;
1634}
1635 1268
1636impl AstNode for LifetimeParam { 1269impl AstNode for LifetimeParam {
1637 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1270 fn cast(syntax: SyntaxNode) -> Option<Self> {
1638 match syntax.kind() { 1271 match syntax.kind() {
1639 LIFETIME_PARAM => Some(LifetimeParam::from_repr(syntax.into_repr())), 1272 LIFETIME_PARAM => Some(LifetimeParam { syntax }),
1640 _ => None, 1273 _ => None,
1641 } 1274 }
1642 } 1275 }
1643 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1276 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1644} 1277}
1645 1278
1646impl ToOwned for LifetimeParam {
1647 type Owned = TreeArc<LifetimeParam>;
1648 fn to_owned(&self) -> TreeArc<LifetimeParam> { TreeArc::cast(self.syntax.to_owned()) }
1649}
1650
1651 1279
1652impl ast::AttrsOwner for LifetimeParam {} 1280impl ast::AttrsOwner for LifetimeParam {}
1653impl LifetimeParam {} 1281impl LifetimeParam {}
1654 1282
1655// Literal 1283// Literal
1656#[derive(Debug, PartialEq, Eq, Hash)] 1284#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1657#[repr(transparent)]
1658pub struct Literal { 1285pub struct Literal {
1659 pub(crate) syntax: SyntaxNode, 1286 pub(crate) syntax: SyntaxNode,
1660} 1287}
1661unsafe impl TransparentNewType for Literal {
1662 type Repr = rowan::SyntaxNode;
1663}
1664 1288
1665impl AstNode for Literal { 1289impl AstNode for Literal {
1666 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1290 fn cast(syntax: SyntaxNode) -> Option<Self> {
1667 match syntax.kind() { 1291 match syntax.kind() {
1668 LITERAL => Some(Literal::from_repr(syntax.into_repr())), 1292 LITERAL => Some(Literal { syntax }),
1669 _ => None, 1293 _ => None,
1670 } 1294 }
1671 } 1295 }
1672 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1296 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1673} 1297}
1674 1298
1675impl ToOwned for Literal {
1676 type Owned = TreeArc<Literal>;
1677 fn to_owned(&self) -> TreeArc<Literal> { TreeArc::cast(self.syntax.to_owned()) }
1678}
1679
1680 1299
1681impl Literal {} 1300impl Literal {}
1682 1301
1683// LiteralPat 1302// LiteralPat
1684#[derive(Debug, PartialEq, Eq, Hash)] 1303#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1685#[repr(transparent)]
1686pub struct LiteralPat { 1304pub struct LiteralPat {
1687 pub(crate) syntax: SyntaxNode, 1305 pub(crate) syntax: SyntaxNode,
1688} 1306}
1689unsafe impl TransparentNewType for LiteralPat {
1690 type Repr = rowan::SyntaxNode;
1691}
1692 1307
1693impl AstNode for LiteralPat { 1308impl AstNode for LiteralPat {
1694 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1309 fn cast(syntax: SyntaxNode) -> Option<Self> {
1695 match syntax.kind() { 1310 match syntax.kind() {
1696 LITERAL_PAT => Some(LiteralPat::from_repr(syntax.into_repr())), 1311 LITERAL_PAT => Some(LiteralPat { syntax }),
1697 _ => None, 1312 _ => None,
1698 } 1313 }
1699 } 1314 }
1700 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1315 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1701} 1316}
1702 1317
1703impl ToOwned for LiteralPat {
1704 type Owned = TreeArc<LiteralPat>;
1705 fn to_owned(&self) -> TreeArc<LiteralPat> { TreeArc::cast(self.syntax.to_owned()) }
1706}
1707
1708 1318
1709impl LiteralPat { 1319impl LiteralPat {
1710 pub fn literal(&self) -> Option<&Literal> { 1320 pub fn literal(&self) -> Option<Literal> {
1711 super::child_opt(self) 1321 super::child_opt(self)
1712 } 1322 }
1713} 1323}
1714 1324
1715// LoopExpr 1325// LoopExpr
1716#[derive(Debug, PartialEq, Eq, Hash)] 1326#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1717#[repr(transparent)]
1718pub struct LoopExpr { 1327pub struct LoopExpr {
1719 pub(crate) syntax: SyntaxNode, 1328 pub(crate) syntax: SyntaxNode,
1720} 1329}
1721unsafe impl TransparentNewType for LoopExpr {
1722 type Repr = rowan::SyntaxNode;
1723}
1724 1330
1725impl AstNode for LoopExpr { 1331impl AstNode for LoopExpr {
1726 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1332 fn cast(syntax: SyntaxNode) -> Option<Self> {
1727 match syntax.kind() { 1333 match syntax.kind() {
1728 LOOP_EXPR => Some(LoopExpr::from_repr(syntax.into_repr())), 1334 LOOP_EXPR => Some(LoopExpr { syntax }),
1729 _ => None, 1335 _ => None,
1730 } 1336 }
1731 } 1337 }
1732 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1338 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1733} 1339}
1734 1340
1735impl ToOwned for LoopExpr {
1736 type Owned = TreeArc<LoopExpr>;
1737 fn to_owned(&self) -> TreeArc<LoopExpr> { TreeArc::cast(self.syntax.to_owned()) }
1738}
1739
1740 1341
1741impl ast::LoopBodyOwner for LoopExpr {} 1342impl ast::LoopBodyOwner for LoopExpr {}
1742impl LoopExpr {} 1343impl LoopExpr {}
1743 1344
1744// MacroCall 1345// MacroCall
1745#[derive(Debug, PartialEq, Eq, Hash)] 1346#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1746#[repr(transparent)]
1747pub struct MacroCall { 1347pub struct MacroCall {
1748 pub(crate) syntax: SyntaxNode, 1348 pub(crate) syntax: SyntaxNode,
1749} 1349}
1750unsafe impl TransparentNewType for MacroCall {
1751 type Repr = rowan::SyntaxNode;
1752}
1753 1350
1754impl AstNode for MacroCall { 1351impl AstNode for MacroCall {
1755 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1352 fn cast(syntax: SyntaxNode) -> Option<Self> {
1756 match syntax.kind() { 1353 match syntax.kind() {
1757 MACRO_CALL => Some(MacroCall::from_repr(syntax.into_repr())), 1354 MACRO_CALL => Some(MacroCall { syntax }),
1758 _ => None, 1355 _ => None,
1759 } 1356 }
1760 } 1357 }
1761 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1358 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1762} 1359}
1763 1360
1764impl ToOwned for MacroCall {
1765 type Owned = TreeArc<MacroCall>;
1766 fn to_owned(&self) -> TreeArc<MacroCall> { TreeArc::cast(self.syntax.to_owned()) }
1767}
1768
1769 1361
1770impl ast::NameOwner for MacroCall {} 1362impl ast::NameOwner for MacroCall {}
1771impl ast::AttrsOwner for MacroCall {} 1363impl ast::AttrsOwner for MacroCall {}
1772impl ast::DocCommentsOwner for MacroCall {} 1364impl ast::DocCommentsOwner for MacroCall {}
1773impl MacroCall { 1365impl MacroCall {
1774 pub fn token_tree(&self) -> Option<&TokenTree> { 1366 pub fn token_tree(&self) -> Option<TokenTree> {
1775 super::child_opt(self) 1367 super::child_opt(self)
1776 } 1368 }
1777 1369
1778 pub fn path(&self) -> Option<&Path> { 1370 pub fn path(&self) -> Option<Path> {
1779 super::child_opt(self) 1371 super::child_opt(self)
1780 } 1372 }
1781} 1373}
1782 1374
1783// MacroItems 1375// MacroItems
1784#[derive(Debug, PartialEq, Eq, Hash)] 1376#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1785#[repr(transparent)]
1786pub struct MacroItems { 1377pub struct MacroItems {
1787 pub(crate) syntax: SyntaxNode, 1378 pub(crate) syntax: SyntaxNode,
1788} 1379}
1789unsafe impl TransparentNewType for MacroItems {
1790 type Repr = rowan::SyntaxNode;
1791}
1792 1380
1793impl AstNode for MacroItems { 1381impl AstNode for MacroItems {
1794 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1382 fn cast(syntax: SyntaxNode) -> Option<Self> {
1795 match syntax.kind() { 1383 match syntax.kind() {
1796 MACRO_ITEMS => Some(MacroItems::from_repr(syntax.into_repr())), 1384 MACRO_ITEMS => Some(MacroItems { syntax }),
1797 _ => None, 1385 _ => None,
1798 } 1386 }
1799 } 1387 }
1800 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1388 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1801} 1389}
1802 1390
1803impl ToOwned for MacroItems {
1804 type Owned = TreeArc<MacroItems>;
1805 fn to_owned(&self) -> TreeArc<MacroItems> { TreeArc::cast(self.syntax.to_owned()) }
1806}
1807
1808 1391
1809impl ast::ModuleItemOwner for MacroItems {} 1392impl ast::ModuleItemOwner for MacroItems {}
1810impl ast::FnDefOwner for MacroItems {} 1393impl ast::FnDefOwner for MacroItems {}
1811impl MacroItems {} 1394impl MacroItems {}
1812 1395
1813// MacroStmts 1396// MacroStmts
1814#[derive(Debug, PartialEq, Eq, Hash)] 1397#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1815#[repr(transparent)]
1816pub struct MacroStmts { 1398pub struct MacroStmts {
1817 pub(crate) syntax: SyntaxNode, 1399 pub(crate) syntax: SyntaxNode,
1818} 1400}
1819unsafe impl TransparentNewType for MacroStmts {
1820 type Repr = rowan::SyntaxNode;
1821}
1822 1401
1823impl AstNode for MacroStmts { 1402impl AstNode for MacroStmts {
1824 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1403 fn cast(syntax: SyntaxNode) -> Option<Self> {
1825 match syntax.kind() { 1404 match syntax.kind() {
1826 MACRO_STMTS => Some(MacroStmts::from_repr(syntax.into_repr())), 1405 MACRO_STMTS => Some(MacroStmts { syntax }),
1827 _ => None, 1406 _ => None,
1828 } 1407 }
1829 } 1408 }
1830 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1409 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1831} 1410}
1832 1411
1833impl ToOwned for MacroStmts {
1834 type Owned = TreeArc<MacroStmts>;
1835 fn to_owned(&self) -> TreeArc<MacroStmts> { TreeArc::cast(self.syntax.to_owned()) }
1836}
1837
1838 1412
1839impl MacroStmts { 1413impl MacroStmts {
1840 pub fn statements(&self) -> impl Iterator<Item = &Stmt> { 1414 pub fn statements(&self) -> impl Iterator<Item = Stmt> {
1841 super::children(self) 1415 super::children(self)
1842 } 1416 }
1843 1417
1844 pub fn expr(&self) -> Option<&Expr> { 1418 pub fn expr(&self) -> Option<Expr> {
1845 super::child_opt(self) 1419 super::child_opt(self)
1846 } 1420 }
1847} 1421}
1848 1422
1849// MatchArm 1423// MatchArm
1850#[derive(Debug, PartialEq, Eq, Hash)] 1424#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1851#[repr(transparent)]
1852pub struct MatchArm { 1425pub struct MatchArm {
1853 pub(crate) syntax: SyntaxNode, 1426 pub(crate) syntax: SyntaxNode,
1854} 1427}
1855unsafe impl TransparentNewType for MatchArm {
1856 type Repr = rowan::SyntaxNode;
1857}
1858 1428
1859impl AstNode for MatchArm { 1429impl AstNode for MatchArm {
1860 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1430 fn cast(syntax: SyntaxNode) -> Option<Self> {
1861 match syntax.kind() { 1431 match syntax.kind() {
1862 MATCH_ARM => Some(MatchArm::from_repr(syntax.into_repr())), 1432 MATCH_ARM => Some(MatchArm { syntax }),
1863 _ => None, 1433 _ => None,
1864 } 1434 }
1865 } 1435 }
1866 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1436 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1867} 1437}
1868 1438
1869impl ToOwned for MatchArm {
1870 type Owned = TreeArc<MatchArm>;
1871 fn to_owned(&self) -> TreeArc<MatchArm> { TreeArc::cast(self.syntax.to_owned()) }
1872}
1873
1874 1439
1875impl ast::AttrsOwner for MatchArm {} 1440impl ast::AttrsOwner for MatchArm {}
1876impl MatchArm { 1441impl MatchArm {
1877 pub fn pats(&self) -> impl Iterator<Item = &Pat> { 1442 pub fn pats(&self) -> impl Iterator<Item = Pat> {
1878 super::children(self) 1443 super::children(self)
1879 } 1444 }
1880 1445
1881 pub fn guard(&self) -> Option<&MatchGuard> { 1446 pub fn guard(&self) -> Option<MatchGuard> {
1882 super::child_opt(self) 1447 super::child_opt(self)
1883 } 1448 }
1884 1449
1885 pub fn expr(&self) -> Option<&Expr> { 1450 pub fn expr(&self) -> Option<Expr> {
1886 super::child_opt(self) 1451 super::child_opt(self)
1887 } 1452 }
1888} 1453}
1889 1454
1890// MatchArmList 1455// MatchArmList
1891#[derive(Debug, PartialEq, Eq, Hash)] 1456#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1892#[repr(transparent)]
1893pub struct MatchArmList { 1457pub struct MatchArmList {
1894 pub(crate) syntax: SyntaxNode, 1458 pub(crate) syntax: SyntaxNode,
1895} 1459}
1896unsafe impl TransparentNewType for MatchArmList {
1897 type Repr = rowan::SyntaxNode;
1898}
1899 1460
1900impl AstNode for MatchArmList { 1461impl AstNode for MatchArmList {
1901 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1462 fn cast(syntax: SyntaxNode) -> Option<Self> {
1902 match syntax.kind() { 1463 match syntax.kind() {
1903 MATCH_ARM_LIST => Some(MatchArmList::from_repr(syntax.into_repr())), 1464 MATCH_ARM_LIST => Some(MatchArmList { syntax }),
1904 _ => None, 1465 _ => None,
1905 } 1466 }
1906 } 1467 }
1907 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1468 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1908} 1469}
1909 1470
1910impl ToOwned for MatchArmList {
1911 type Owned = TreeArc<MatchArmList>;
1912 fn to_owned(&self) -> TreeArc<MatchArmList> { TreeArc::cast(self.syntax.to_owned()) }
1913}
1914
1915 1471
1916impl ast::AttrsOwner for MatchArmList {} 1472impl ast::AttrsOwner for MatchArmList {}
1917impl MatchArmList { 1473impl MatchArmList {
1918 pub fn arms(&self) -> impl Iterator<Item = &MatchArm> { 1474 pub fn arms(&self) -> impl Iterator<Item = MatchArm> {
1919 super::children(self) 1475 super::children(self)
1920 } 1476 }
1921} 1477}
1922 1478
1923// MatchExpr 1479// MatchExpr
1924#[derive(Debug, PartialEq, Eq, Hash)] 1480#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1925#[repr(transparent)]
1926pub struct MatchExpr { 1481pub struct MatchExpr {
1927 pub(crate) syntax: SyntaxNode, 1482 pub(crate) syntax: SyntaxNode,
1928} 1483}
1929unsafe impl TransparentNewType for MatchExpr {
1930 type Repr = rowan::SyntaxNode;
1931}
1932 1484
1933impl AstNode for MatchExpr { 1485impl AstNode for MatchExpr {
1934 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1486 fn cast(syntax: SyntaxNode) -> Option<Self> {
1935 match syntax.kind() { 1487 match syntax.kind() {
1936 MATCH_EXPR => Some(MatchExpr::from_repr(syntax.into_repr())), 1488 MATCH_EXPR => Some(MatchExpr { syntax }),
1937 _ => None, 1489 _ => None,
1938 } 1490 }
1939 } 1491 }
1940 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1492 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1941} 1493}
1942 1494
1943impl ToOwned for MatchExpr {
1944 type Owned = TreeArc<MatchExpr>;
1945 fn to_owned(&self) -> TreeArc<MatchExpr> { TreeArc::cast(self.syntax.to_owned()) }
1946}
1947
1948 1495
1949impl MatchExpr { 1496impl MatchExpr {
1950 pub fn expr(&self) -> Option<&Expr> { 1497 pub fn expr(&self) -> Option<Expr> {
1951 super::child_opt(self) 1498 super::child_opt(self)
1952 } 1499 }
1953 1500
1954 pub fn match_arm_list(&self) -> Option<&MatchArmList> { 1501 pub fn match_arm_list(&self) -> Option<MatchArmList> {
1955 super::child_opt(self) 1502 super::child_opt(self)
1956 } 1503 }
1957} 1504}
1958 1505
1959// MatchGuard 1506// MatchGuard
1960#[derive(Debug, PartialEq, Eq, Hash)] 1507#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1961#[repr(transparent)]
1962pub struct MatchGuard { 1508pub struct MatchGuard {
1963 pub(crate) syntax: SyntaxNode, 1509 pub(crate) syntax: SyntaxNode,
1964} 1510}
1965unsafe impl TransparentNewType for MatchGuard {
1966 type Repr = rowan::SyntaxNode;
1967}
1968 1511
1969impl AstNode for MatchGuard { 1512impl AstNode for MatchGuard {
1970 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1513 fn cast(syntax: SyntaxNode) -> Option<Self> {
1971 match syntax.kind() { 1514 match syntax.kind() {
1972 MATCH_GUARD => Some(MatchGuard::from_repr(syntax.into_repr())), 1515 MATCH_GUARD => Some(MatchGuard { syntax }),
1973 _ => None, 1516 _ => None,
1974 } 1517 }
1975 } 1518 }
1976 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1519 fn syntax(&self) -> &SyntaxNode { &self.syntax }
1977} 1520}
1978 1521
1979impl ToOwned for MatchGuard {
1980 type Owned = TreeArc<MatchGuard>;
1981 fn to_owned(&self) -> TreeArc<MatchGuard> { TreeArc::cast(self.syntax.to_owned()) }
1982}
1983
1984 1522
1985impl MatchGuard { 1523impl MatchGuard {
1986 pub fn expr(&self) -> Option<&Expr> { 1524 pub fn expr(&self) -> Option<Expr> {
1987 super::child_opt(self) 1525 super::child_opt(self)
1988 } 1526 }
1989} 1527}
1990 1528
1991// MethodCallExpr 1529// MethodCallExpr
1992#[derive(Debug, PartialEq, Eq, Hash)] 1530#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1993#[repr(transparent)]
1994pub struct MethodCallExpr { 1531pub struct MethodCallExpr {
1995 pub(crate) syntax: SyntaxNode, 1532 pub(crate) syntax: SyntaxNode,
1996} 1533}
1997unsafe impl TransparentNewType for MethodCallExpr {
1998 type Repr = rowan::SyntaxNode;
1999}
2000 1534
2001impl AstNode for MethodCallExpr { 1535impl AstNode for MethodCallExpr {
2002 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1536 fn cast(syntax: SyntaxNode) -> Option<Self> {
2003 match syntax.kind() { 1537 match syntax.kind() {
2004 METHOD_CALL_EXPR => Some(MethodCallExpr::from_repr(syntax.into_repr())), 1538 METHOD_CALL_EXPR => Some(MethodCallExpr { syntax }),
2005 _ => None, 1539 _ => None,
2006 } 1540 }
2007 } 1541 }
2008 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1542 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2009} 1543}
2010 1544
2011impl ToOwned for MethodCallExpr {
2012 type Owned = TreeArc<MethodCallExpr>;
2013 fn to_owned(&self) -> TreeArc<MethodCallExpr> { TreeArc::cast(self.syntax.to_owned()) }
2014}
2015
2016 1545
2017impl ast::ArgListOwner for MethodCallExpr {} 1546impl ast::ArgListOwner for MethodCallExpr {}
2018impl MethodCallExpr { 1547impl MethodCallExpr {
2019 pub fn expr(&self) -> Option<&Expr> { 1548 pub fn expr(&self) -> Option<Expr> {
2020 super::child_opt(self) 1549 super::child_opt(self)
2021 } 1550 }
2022 1551
2023 pub fn name_ref(&self) -> Option<&NameRef> { 1552 pub fn name_ref(&self) -> Option<NameRef> {
2024 super::child_opt(self) 1553 super::child_opt(self)
2025 } 1554 }
2026 1555
2027 pub fn type_arg_list(&self) -> Option<&TypeArgList> { 1556 pub fn type_arg_list(&self) -> Option<TypeArgList> {
2028 super::child_opt(self) 1557 super::child_opt(self)
2029 } 1558 }
2030} 1559}
2031 1560
2032// Module 1561// Module
2033#[derive(Debug, PartialEq, Eq, Hash)] 1562#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2034#[repr(transparent)]
2035pub struct Module { 1563pub struct Module {
2036 pub(crate) syntax: SyntaxNode, 1564 pub(crate) syntax: SyntaxNode,
2037} 1565}
2038unsafe impl TransparentNewType for Module {
2039 type Repr = rowan::SyntaxNode;
2040}
2041 1566
2042impl AstNode for Module { 1567impl AstNode for Module {
2043 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1568 fn cast(syntax: SyntaxNode) -> Option<Self> {
2044 match syntax.kind() { 1569 match syntax.kind() {
2045 MODULE => Some(Module::from_repr(syntax.into_repr())), 1570 MODULE => Some(Module { syntax }),
2046 _ => None, 1571 _ => None,
2047 } 1572 }
2048 } 1573 }
2049 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1574 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2050} 1575}
2051 1576
2052impl ToOwned for Module {
2053 type Owned = TreeArc<Module>;
2054 fn to_owned(&self) -> TreeArc<Module> { TreeArc::cast(self.syntax.to_owned()) }
2055}
2056
2057 1577
2058impl ast::VisibilityOwner for Module {} 1578impl ast::VisibilityOwner for Module {}
2059impl ast::NameOwner for Module {} 1579impl ast::NameOwner for Module {}
2060impl ast::AttrsOwner for Module {} 1580impl ast::AttrsOwner for Module {}
2061impl ast::DocCommentsOwner for Module {} 1581impl ast::DocCommentsOwner for Module {}
2062impl Module { 1582impl Module {
2063 pub fn item_list(&self) -> Option<&ItemList> { 1583 pub fn item_list(&self) -> Option<ItemList> {
2064 super::child_opt(self) 1584 super::child_opt(self)
2065 } 1585 }
2066} 1586}
2067 1587
2068// ModuleItem 1588// ModuleItem
2069#[derive(Debug, PartialEq, Eq, Hash)] 1589#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2070#[repr(transparent)]
2071pub struct ModuleItem { 1590pub struct ModuleItem {
2072 pub(crate) syntax: SyntaxNode, 1591 pub(crate) syntax: SyntaxNode,
2073} 1592}
2074unsafe impl TransparentNewType for ModuleItem {
2075 type Repr = rowan::SyntaxNode;
2076}
2077 1593
2078#[derive(Debug, Clone, Copy, PartialEq, Eq)] 1594#[derive(Debug, Clone, PartialEq, Eq)]
2079pub enum ModuleItemKind<'a> { 1595pub enum ModuleItemKind {
2080 StructDef(&'a StructDef), 1596 StructDef(StructDef),
2081 EnumDef(&'a EnumDef), 1597 EnumDef(EnumDef),
2082 FnDef(&'a FnDef), 1598 FnDef(FnDef),
2083 TraitDef(&'a TraitDef), 1599 TraitDef(TraitDef),
2084 TypeAliasDef(&'a TypeAliasDef), 1600 TypeAliasDef(TypeAliasDef),
2085 ImplBlock(&'a ImplBlock), 1601 ImplBlock(ImplBlock),
2086 UseItem(&'a UseItem), 1602 UseItem(UseItem),
2087 ExternCrateItem(&'a ExternCrateItem), 1603 ExternCrateItem(ExternCrateItem),
2088 ConstDef(&'a ConstDef), 1604 ConstDef(ConstDef),
2089 StaticDef(&'a StaticDef), 1605 StaticDef(StaticDef),
2090 Module(&'a Module), 1606 Module(Module),
2091} 1607}
2092impl<'a> From<&'a StructDef> for &'a ModuleItem { 1608impl From<StructDef> for ModuleItem {
2093 fn from(n: &'a StructDef) -> &'a ModuleItem { 1609 fn from(n: StructDef) -> ModuleItem {
2094 ModuleItem::cast(&n.syntax).unwrap() 1610 ModuleItem::cast(n.syntax).unwrap()
2095 } 1611 }
2096} 1612}
2097impl<'a> From<&'a EnumDef> for &'a ModuleItem { 1613impl From<EnumDef> for ModuleItem {
2098 fn from(n: &'a EnumDef) -> &'a ModuleItem { 1614 fn from(n: EnumDef) -> ModuleItem {
2099 ModuleItem::cast(&n.syntax).unwrap() 1615 ModuleItem::cast(n.syntax).unwrap()
2100 } 1616 }
2101} 1617}
2102impl<'a> From<&'a FnDef> for &'a ModuleItem { 1618impl From<FnDef> for ModuleItem {
2103 fn from(n: &'a FnDef) -> &'a ModuleItem { 1619 fn from(n: FnDef) -> ModuleItem {
2104 ModuleItem::cast(&n.syntax).unwrap() 1620 ModuleItem::cast(n.syntax).unwrap()
2105 } 1621 }
2106} 1622}
2107impl<'a> From<&'a TraitDef> for &'a ModuleItem { 1623impl From<TraitDef> for ModuleItem {
2108 fn from(n: &'a TraitDef) -> &'a ModuleItem { 1624 fn from(n: TraitDef) -> ModuleItem {
2109 ModuleItem::cast(&n.syntax).unwrap() 1625 ModuleItem::cast(n.syntax).unwrap()
2110 } 1626 }
2111} 1627}
2112impl<'a> From<&'a TypeAliasDef> for &'a ModuleItem { 1628impl From<TypeAliasDef> for ModuleItem {
2113 fn from(n: &'a TypeAliasDef) -> &'a ModuleItem { 1629 fn from(n: TypeAliasDef) -> ModuleItem {
2114 ModuleItem::cast(&n.syntax).unwrap() 1630 ModuleItem::cast(n.syntax).unwrap()
2115 } 1631 }
2116} 1632}
2117impl<'a> From<&'a ImplBlock> for &'a ModuleItem { 1633impl From<ImplBlock> for ModuleItem {
2118 fn from(n: &'a ImplBlock) -> &'a ModuleItem { 1634 fn from(n: ImplBlock) -> ModuleItem {
2119 ModuleItem::cast(&n.syntax).unwrap() 1635 ModuleItem::cast(n.syntax).unwrap()
2120 } 1636 }
2121} 1637}
2122impl<'a> From<&'a UseItem> for &'a ModuleItem { 1638impl From<UseItem> for ModuleItem {
2123 fn from(n: &'a UseItem) -> &'a ModuleItem { 1639 fn from(n: UseItem) -> ModuleItem {
2124 ModuleItem::cast(&n.syntax).unwrap() 1640 ModuleItem::cast(n.syntax).unwrap()
2125 } 1641 }
2126} 1642}
2127impl<'a> From<&'a ExternCrateItem> for &'a ModuleItem { 1643impl From<ExternCrateItem> for ModuleItem {
2128 fn from(n: &'a ExternCrateItem) -> &'a ModuleItem { 1644 fn from(n: ExternCrateItem) -> ModuleItem {
2129 ModuleItem::cast(&n.syntax).unwrap() 1645 ModuleItem::cast(n.syntax).unwrap()
2130 } 1646 }
2131} 1647}
2132impl<'a> From<&'a ConstDef> for &'a ModuleItem { 1648impl From<ConstDef> for ModuleItem {
2133 fn from(n: &'a ConstDef) -> &'a ModuleItem { 1649 fn from(n: ConstDef) -> ModuleItem {
2134 ModuleItem::cast(&n.syntax).unwrap() 1650 ModuleItem::cast(n.syntax).unwrap()
2135 } 1651 }
2136} 1652}
2137impl<'a> From<&'a StaticDef> for &'a ModuleItem { 1653impl From<StaticDef> for ModuleItem {
2138 fn from(n: &'a StaticDef) -> &'a ModuleItem { 1654 fn from(n: StaticDef) -> ModuleItem {
2139 ModuleItem::cast(&n.syntax).unwrap() 1655 ModuleItem::cast(n.syntax).unwrap()
2140 } 1656 }
2141} 1657}
2142impl<'a> From<&'a Module> for &'a ModuleItem { 1658impl From<Module> for ModuleItem {
2143 fn from(n: &'a Module) -> &'a ModuleItem { 1659 fn from(n: Module) -> ModuleItem {
2144 ModuleItem::cast(&n.syntax).unwrap() 1660 ModuleItem::cast(n.syntax).unwrap()
2145 } 1661 }
2146} 1662}
2147 1663
2148 1664
2149impl AstNode for ModuleItem { 1665impl AstNode for ModuleItem {
2150 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1666 fn cast(syntax: SyntaxNode) -> Option<Self> {
2151 match syntax.kind() { 1667 match syntax.kind() {
2152 | STRUCT_DEF 1668 | STRUCT_DEF
2153 | ENUM_DEF 1669 | ENUM_DEF
@@ -2159,32 +1675,27 @@ impl AstNode for ModuleItem {
2159 | EXTERN_CRATE_ITEM 1675 | EXTERN_CRATE_ITEM
2160 | CONST_DEF 1676 | CONST_DEF
2161 | STATIC_DEF 1677 | STATIC_DEF
2162 | MODULE => Some(ModuleItem::from_repr(syntax.into_repr())), 1678 | MODULE => Some(ModuleItem { syntax }),
2163 _ => None, 1679 _ => None,
2164 } 1680 }
2165 } 1681 }
2166 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1682 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2167} 1683}
2168 1684
2169impl ToOwned for ModuleItem {
2170 type Owned = TreeArc<ModuleItem>;
2171 fn to_owned(&self) -> TreeArc<ModuleItem> { TreeArc::cast(self.syntax.to_owned()) }
2172}
2173
2174impl ModuleItem { 1685impl ModuleItem {
2175 pub fn kind(&self) -> ModuleItemKind { 1686 pub fn kind(&self) -> ModuleItemKind {
2176 match self.syntax.kind() { 1687 match self.syntax.kind() {
2177 STRUCT_DEF => ModuleItemKind::StructDef(StructDef::cast(&self.syntax).unwrap()), 1688 STRUCT_DEF => ModuleItemKind::StructDef(StructDef::cast(self.syntax.clone()).unwrap()),
2178 ENUM_DEF => ModuleItemKind::EnumDef(EnumDef::cast(&self.syntax).unwrap()), 1689 ENUM_DEF => ModuleItemKind::EnumDef(EnumDef::cast(self.syntax.clone()).unwrap()),
2179 FN_DEF => ModuleItemKind::FnDef(FnDef::cast(&self.syntax).unwrap()), 1690 FN_DEF => ModuleItemKind::FnDef(FnDef::cast(self.syntax.clone()).unwrap()),
2180 TRAIT_DEF => ModuleItemKind::TraitDef(TraitDef::cast(&self.syntax).unwrap()), 1691 TRAIT_DEF => ModuleItemKind::TraitDef(TraitDef::cast(self.syntax.clone()).unwrap()),
2181 TYPE_ALIAS_DEF => ModuleItemKind::TypeAliasDef(TypeAliasDef::cast(&self.syntax).unwrap()), 1692 TYPE_ALIAS_DEF => ModuleItemKind::TypeAliasDef(TypeAliasDef::cast(self.syntax.clone()).unwrap()),
2182 IMPL_BLOCK => ModuleItemKind::ImplBlock(ImplBlock::cast(&self.syntax).unwrap()), 1693 IMPL_BLOCK => ModuleItemKind::ImplBlock(ImplBlock::cast(self.syntax.clone()).unwrap()),
2183 USE_ITEM => ModuleItemKind::UseItem(UseItem::cast(&self.syntax).unwrap()), 1694 USE_ITEM => ModuleItemKind::UseItem(UseItem::cast(self.syntax.clone()).unwrap()),
2184 EXTERN_CRATE_ITEM => ModuleItemKind::ExternCrateItem(ExternCrateItem::cast(&self.syntax).unwrap()), 1695 EXTERN_CRATE_ITEM => ModuleItemKind::ExternCrateItem(ExternCrateItem::cast(self.syntax.clone()).unwrap()),
2185 CONST_DEF => ModuleItemKind::ConstDef(ConstDef::cast(&self.syntax).unwrap()), 1696 CONST_DEF => ModuleItemKind::ConstDef(ConstDef::cast(self.syntax.clone()).unwrap()),
2186 STATIC_DEF => ModuleItemKind::StaticDef(StaticDef::cast(&self.syntax).unwrap()), 1697 STATIC_DEF => ModuleItemKind::StaticDef(StaticDef::cast(self.syntax.clone()).unwrap()),
2187 MODULE => ModuleItemKind::Module(Module::cast(&self.syntax).unwrap()), 1698 MODULE => ModuleItemKind::Module(Module::cast(self.syntax.clone()).unwrap()),
2188 _ => unreachable!(), 1699 _ => unreachable!(),
2189 } 1700 }
2190 } 1701 }
@@ -2193,122 +1704,86 @@ impl ModuleItem {
2193impl ModuleItem {} 1704impl ModuleItem {}
2194 1705
2195// Name 1706// Name
2196#[derive(Debug, PartialEq, Eq, Hash)] 1707#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2197#[repr(transparent)]
2198pub struct Name { 1708pub struct Name {
2199 pub(crate) syntax: SyntaxNode, 1709 pub(crate) syntax: SyntaxNode,
2200} 1710}
2201unsafe impl TransparentNewType for Name {
2202 type Repr = rowan::SyntaxNode;
2203}
2204 1711
2205impl AstNode for Name { 1712impl AstNode for Name {
2206 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1713 fn cast(syntax: SyntaxNode) -> Option<Self> {
2207 match syntax.kind() { 1714 match syntax.kind() {
2208 NAME => Some(Name::from_repr(syntax.into_repr())), 1715 NAME => Some(Name { syntax }),
2209 _ => None, 1716 _ => None,
2210 } 1717 }
2211 } 1718 }
2212 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1719 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2213} 1720}
2214 1721
2215impl ToOwned for Name {
2216 type Owned = TreeArc<Name>;
2217 fn to_owned(&self) -> TreeArc<Name> { TreeArc::cast(self.syntax.to_owned()) }
2218}
2219
2220 1722
2221impl Name {} 1723impl Name {}
2222 1724
2223// NameRef 1725// NameRef
2224#[derive(Debug, PartialEq, Eq, Hash)] 1726#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2225#[repr(transparent)]
2226pub struct NameRef { 1727pub struct NameRef {
2227 pub(crate) syntax: SyntaxNode, 1728 pub(crate) syntax: SyntaxNode,
2228} 1729}
2229unsafe impl TransparentNewType for NameRef {
2230 type Repr = rowan::SyntaxNode;
2231}
2232 1730
2233impl AstNode for NameRef { 1731impl AstNode for NameRef {
2234 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1732 fn cast(syntax: SyntaxNode) -> Option<Self> {
2235 match syntax.kind() { 1733 match syntax.kind() {
2236 NAME_REF => Some(NameRef::from_repr(syntax.into_repr())), 1734 NAME_REF => Some(NameRef { syntax }),
2237 _ => None, 1735 _ => None,
2238 } 1736 }
2239 } 1737 }
2240 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1738 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2241} 1739}
2242 1740
2243impl ToOwned for NameRef {
2244 type Owned = TreeArc<NameRef>;
2245 fn to_owned(&self) -> TreeArc<NameRef> { TreeArc::cast(self.syntax.to_owned()) }
2246}
2247
2248 1741
2249impl NameRef {} 1742impl NameRef {}
2250 1743
2251// NamedField 1744// NamedField
2252#[derive(Debug, PartialEq, Eq, Hash)] 1745#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2253#[repr(transparent)]
2254pub struct NamedField { 1746pub struct NamedField {
2255 pub(crate) syntax: SyntaxNode, 1747 pub(crate) syntax: SyntaxNode,
2256} 1748}
2257unsafe impl TransparentNewType for NamedField {
2258 type Repr = rowan::SyntaxNode;
2259}
2260 1749
2261impl AstNode for NamedField { 1750impl AstNode for NamedField {
2262 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1751 fn cast(syntax: SyntaxNode) -> Option<Self> {
2263 match syntax.kind() { 1752 match syntax.kind() {
2264 NAMED_FIELD => Some(NamedField::from_repr(syntax.into_repr())), 1753 NAMED_FIELD => Some(NamedField { syntax }),
2265 _ => None, 1754 _ => None,
2266 } 1755 }
2267 } 1756 }
2268 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1757 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2269} 1758}
2270 1759
2271impl ToOwned for NamedField {
2272 type Owned = TreeArc<NamedField>;
2273 fn to_owned(&self) -> TreeArc<NamedField> { TreeArc::cast(self.syntax.to_owned()) }
2274}
2275
2276 1760
2277impl NamedField { 1761impl NamedField {
2278 pub fn name_ref(&self) -> Option<&NameRef> { 1762 pub fn name_ref(&self) -> Option<NameRef> {
2279 super::child_opt(self) 1763 super::child_opt(self)
2280 } 1764 }
2281 1765
2282 pub fn expr(&self) -> Option<&Expr> { 1766 pub fn expr(&self) -> Option<Expr> {
2283 super::child_opt(self) 1767 super::child_opt(self)
2284 } 1768 }
2285} 1769}
2286 1770
2287// NamedFieldDef 1771// NamedFieldDef
2288#[derive(Debug, PartialEq, Eq, Hash)] 1772#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2289#[repr(transparent)]
2290pub struct NamedFieldDef { 1773pub struct NamedFieldDef {
2291 pub(crate) syntax: SyntaxNode, 1774 pub(crate) syntax: SyntaxNode,
2292} 1775}
2293unsafe impl TransparentNewType for NamedFieldDef {
2294 type Repr = rowan::SyntaxNode;
2295}
2296 1776
2297impl AstNode for NamedFieldDef { 1777impl AstNode for NamedFieldDef {
2298 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1778 fn cast(syntax: SyntaxNode) -> Option<Self> {
2299 match syntax.kind() { 1779 match syntax.kind() {
2300 NAMED_FIELD_DEF => Some(NamedFieldDef::from_repr(syntax.into_repr())), 1780 NAMED_FIELD_DEF => Some(NamedFieldDef { syntax }),
2301 _ => None, 1781 _ => None,
2302 } 1782 }
2303 } 1783 }
2304 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1784 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2305} 1785}
2306 1786
2307impl ToOwned for NamedFieldDef {
2308 type Owned = TreeArc<NamedFieldDef>;
2309 fn to_owned(&self) -> TreeArc<NamedFieldDef> { TreeArc::cast(self.syntax.to_owned()) }
2310}
2311
2312 1787
2313impl ast::VisibilityOwner for NamedFieldDef {} 1788impl ast::VisibilityOwner for NamedFieldDef {}
2314impl ast::NameOwner for NamedFieldDef {} 1789impl ast::NameOwner for NamedFieldDef {}
@@ -2318,149 +1793,113 @@ impl ast::TypeAscriptionOwner for NamedFieldDef {}
2318impl NamedFieldDef {} 1793impl NamedFieldDef {}
2319 1794
2320// NamedFieldDefList 1795// NamedFieldDefList
2321#[derive(Debug, PartialEq, Eq, Hash)] 1796#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2322#[repr(transparent)]
2323pub struct NamedFieldDefList { 1797pub struct NamedFieldDefList {
2324 pub(crate) syntax: SyntaxNode, 1798 pub(crate) syntax: SyntaxNode,
2325} 1799}
2326unsafe impl TransparentNewType for NamedFieldDefList {
2327 type Repr = rowan::SyntaxNode;
2328}
2329 1800
2330impl AstNode for NamedFieldDefList { 1801impl AstNode for NamedFieldDefList {
2331 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1802 fn cast(syntax: SyntaxNode) -> Option<Self> {
2332 match syntax.kind() { 1803 match syntax.kind() {
2333 NAMED_FIELD_DEF_LIST => Some(NamedFieldDefList::from_repr(syntax.into_repr())), 1804 NAMED_FIELD_DEF_LIST => Some(NamedFieldDefList { syntax }),
2334 _ => None, 1805 _ => None,
2335 } 1806 }
2336 } 1807 }
2337 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1808 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2338} 1809}
2339 1810
2340impl ToOwned for NamedFieldDefList {
2341 type Owned = TreeArc<NamedFieldDefList>;
2342 fn to_owned(&self) -> TreeArc<NamedFieldDefList> { TreeArc::cast(self.syntax.to_owned()) }
2343}
2344
2345 1811
2346impl NamedFieldDefList { 1812impl NamedFieldDefList {
2347 pub fn fields(&self) -> impl Iterator<Item = &NamedFieldDef> { 1813 pub fn fields(&self) -> impl Iterator<Item = NamedFieldDef> {
2348 super::children(self) 1814 super::children(self)
2349 } 1815 }
2350} 1816}
2351 1817
2352// NamedFieldList 1818// NamedFieldList
2353#[derive(Debug, PartialEq, Eq, Hash)] 1819#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2354#[repr(transparent)]
2355pub struct NamedFieldList { 1820pub struct NamedFieldList {
2356 pub(crate) syntax: SyntaxNode, 1821 pub(crate) syntax: SyntaxNode,
2357} 1822}
2358unsafe impl TransparentNewType for NamedFieldList {
2359 type Repr = rowan::SyntaxNode;
2360}
2361 1823
2362impl AstNode for NamedFieldList { 1824impl AstNode for NamedFieldList {
2363 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1825 fn cast(syntax: SyntaxNode) -> Option<Self> {
2364 match syntax.kind() { 1826 match syntax.kind() {
2365 NAMED_FIELD_LIST => Some(NamedFieldList::from_repr(syntax.into_repr())), 1827 NAMED_FIELD_LIST => Some(NamedFieldList { syntax }),
2366 _ => None, 1828 _ => None,
2367 } 1829 }
2368 } 1830 }
2369 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1831 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2370} 1832}
2371 1833
2372impl ToOwned for NamedFieldList {
2373 type Owned = TreeArc<NamedFieldList>;
2374 fn to_owned(&self) -> TreeArc<NamedFieldList> { TreeArc::cast(self.syntax.to_owned()) }
2375}
2376
2377 1834
2378impl NamedFieldList { 1835impl NamedFieldList {
2379 pub fn fields(&self) -> impl Iterator<Item = &NamedField> { 1836 pub fn fields(&self) -> impl Iterator<Item = NamedField> {
2380 super::children(self) 1837 super::children(self)
2381 } 1838 }
2382 1839
2383 pub fn spread(&self) -> Option<&Expr> { 1840 pub fn spread(&self) -> Option<Expr> {
2384 super::child_opt(self) 1841 super::child_opt(self)
2385 } 1842 }
2386} 1843}
2387 1844
2388// NeverType 1845// NeverType
2389#[derive(Debug, PartialEq, Eq, Hash)] 1846#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2390#[repr(transparent)]
2391pub struct NeverType { 1847pub struct NeverType {
2392 pub(crate) syntax: SyntaxNode, 1848 pub(crate) syntax: SyntaxNode,
2393} 1849}
2394unsafe impl TransparentNewType for NeverType {
2395 type Repr = rowan::SyntaxNode;
2396}
2397 1850
2398impl AstNode for NeverType { 1851impl AstNode for NeverType {
2399 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1852 fn cast(syntax: SyntaxNode) -> Option<Self> {
2400 match syntax.kind() { 1853 match syntax.kind() {
2401 NEVER_TYPE => Some(NeverType::from_repr(syntax.into_repr())), 1854 NEVER_TYPE => Some(NeverType { syntax }),
2402 _ => None, 1855 _ => None,
2403 } 1856 }
2404 } 1857 }
2405 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1858 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2406} 1859}
2407 1860
2408impl ToOwned for NeverType {
2409 type Owned = TreeArc<NeverType>;
2410 fn to_owned(&self) -> TreeArc<NeverType> { TreeArc::cast(self.syntax.to_owned()) }
2411}
2412
2413 1861
2414impl NeverType {} 1862impl NeverType {}
2415 1863
2416// NominalDef 1864// NominalDef
2417#[derive(Debug, PartialEq, Eq, Hash)] 1865#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2418#[repr(transparent)]
2419pub struct NominalDef { 1866pub struct NominalDef {
2420 pub(crate) syntax: SyntaxNode, 1867 pub(crate) syntax: SyntaxNode,
2421} 1868}
2422unsafe impl TransparentNewType for NominalDef {
2423 type Repr = rowan::SyntaxNode;
2424}
2425 1869
2426#[derive(Debug, Clone, Copy, PartialEq, Eq)] 1870#[derive(Debug, Clone, PartialEq, Eq)]
2427pub enum NominalDefKind<'a> { 1871pub enum NominalDefKind {
2428 StructDef(&'a StructDef), 1872 StructDef(StructDef),
2429 EnumDef(&'a EnumDef), 1873 EnumDef(EnumDef),
2430} 1874}
2431impl<'a> From<&'a StructDef> for &'a NominalDef { 1875impl From<StructDef> for NominalDef {
2432 fn from(n: &'a StructDef) -> &'a NominalDef { 1876 fn from(n: StructDef) -> NominalDef {
2433 NominalDef::cast(&n.syntax).unwrap() 1877 NominalDef::cast(n.syntax).unwrap()
2434 } 1878 }
2435} 1879}
2436impl<'a> From<&'a EnumDef> for &'a NominalDef { 1880impl From<EnumDef> for NominalDef {
2437 fn from(n: &'a EnumDef) -> &'a NominalDef { 1881 fn from(n: EnumDef) -> NominalDef {
2438 NominalDef::cast(&n.syntax).unwrap() 1882 NominalDef::cast(n.syntax).unwrap()
2439 } 1883 }
2440} 1884}
2441 1885
2442 1886
2443impl AstNode for NominalDef { 1887impl AstNode for NominalDef {
2444 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1888 fn cast(syntax: SyntaxNode) -> Option<Self> {
2445 match syntax.kind() { 1889 match syntax.kind() {
2446 | STRUCT_DEF 1890 | STRUCT_DEF
2447 | ENUM_DEF => Some(NominalDef::from_repr(syntax.into_repr())), 1891 | ENUM_DEF => Some(NominalDef { syntax }),
2448 _ => None, 1892 _ => None,
2449 } 1893 }
2450 } 1894 }
2451 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1895 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2452} 1896}
2453 1897
2454impl ToOwned for NominalDef {
2455 type Owned = TreeArc<NominalDef>;
2456 fn to_owned(&self) -> TreeArc<NominalDef> { TreeArc::cast(self.syntax.to_owned()) }
2457}
2458
2459impl NominalDef { 1898impl NominalDef {
2460 pub fn kind(&self) -> NominalDefKind { 1899 pub fn kind(&self) -> NominalDefKind {
2461 match self.syntax.kind() { 1900 match self.syntax.kind() {
2462 STRUCT_DEF => NominalDefKind::StructDef(StructDef::cast(&self.syntax).unwrap()), 1901 STRUCT_DEF => NominalDefKind::StructDef(StructDef::cast(self.syntax.clone()).unwrap()),
2463 ENUM_DEF => NominalDefKind::EnumDef(EnumDef::cast(&self.syntax).unwrap()), 1902 ENUM_DEF => NominalDefKind::EnumDef(EnumDef::cast(self.syntax.clone()).unwrap()),
2464 _ => unreachable!(), 1903 _ => unreachable!(),
2465 } 1904 }
2466 } 1905 }
@@ -2472,215 +1911,175 @@ impl ast::AttrsOwner for NominalDef {}
2472impl NominalDef {} 1911impl NominalDef {}
2473 1912
2474// Param 1913// Param
2475#[derive(Debug, PartialEq, Eq, Hash)] 1914#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2476#[repr(transparent)]
2477pub struct Param { 1915pub struct Param {
2478 pub(crate) syntax: SyntaxNode, 1916 pub(crate) syntax: SyntaxNode,
2479} 1917}
2480unsafe impl TransparentNewType for Param {
2481 type Repr = rowan::SyntaxNode;
2482}
2483 1918
2484impl AstNode for Param { 1919impl AstNode for Param {
2485 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1920 fn cast(syntax: SyntaxNode) -> Option<Self> {
2486 match syntax.kind() { 1921 match syntax.kind() {
2487 PARAM => Some(Param::from_repr(syntax.into_repr())), 1922 PARAM => Some(Param { syntax }),
2488 _ => None, 1923 _ => None,
2489 } 1924 }
2490 } 1925 }
2491 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1926 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2492} 1927}
2493 1928
2494impl ToOwned for Param {
2495 type Owned = TreeArc<Param>;
2496 fn to_owned(&self) -> TreeArc<Param> { TreeArc::cast(self.syntax.to_owned()) }
2497}
2498
2499 1929
2500impl ast::TypeAscriptionOwner for Param {} 1930impl ast::TypeAscriptionOwner for Param {}
2501impl Param { 1931impl Param {
2502 pub fn pat(&self) -> Option<&Pat> { 1932 pub fn pat(&self) -> Option<Pat> {
2503 super::child_opt(self) 1933 super::child_opt(self)
2504 } 1934 }
2505} 1935}
2506 1936
2507// ParamList 1937// ParamList
2508#[derive(Debug, PartialEq, Eq, Hash)] 1938#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2509#[repr(transparent)]
2510pub struct ParamList { 1939pub struct ParamList {
2511 pub(crate) syntax: SyntaxNode, 1940 pub(crate) syntax: SyntaxNode,
2512} 1941}
2513unsafe impl TransparentNewType for ParamList {
2514 type Repr = rowan::SyntaxNode;
2515}
2516 1942
2517impl AstNode for ParamList { 1943impl AstNode for ParamList {
2518 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1944 fn cast(syntax: SyntaxNode) -> Option<Self> {
2519 match syntax.kind() { 1945 match syntax.kind() {
2520 PARAM_LIST => Some(ParamList::from_repr(syntax.into_repr())), 1946 PARAM_LIST => Some(ParamList { syntax }),
2521 _ => None, 1947 _ => None,
2522 } 1948 }
2523 } 1949 }
2524 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1950 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2525} 1951}
2526 1952
2527impl ToOwned for ParamList {
2528 type Owned = TreeArc<ParamList>;
2529 fn to_owned(&self) -> TreeArc<ParamList> { TreeArc::cast(self.syntax.to_owned()) }
2530}
2531
2532 1953
2533impl ParamList { 1954impl ParamList {
2534 pub fn params(&self) -> impl Iterator<Item = &Param> { 1955 pub fn params(&self) -> impl Iterator<Item = Param> {
2535 super::children(self) 1956 super::children(self)
2536 } 1957 }
2537 1958
2538 pub fn self_param(&self) -> Option<&SelfParam> { 1959 pub fn self_param(&self) -> Option<SelfParam> {
2539 super::child_opt(self) 1960 super::child_opt(self)
2540 } 1961 }
2541} 1962}
2542 1963
2543// ParenExpr 1964// ParenExpr
2544#[derive(Debug, PartialEq, Eq, Hash)] 1965#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2545#[repr(transparent)]
2546pub struct ParenExpr { 1966pub struct ParenExpr {
2547 pub(crate) syntax: SyntaxNode, 1967 pub(crate) syntax: SyntaxNode,
2548} 1968}
2549unsafe impl TransparentNewType for ParenExpr {
2550 type Repr = rowan::SyntaxNode;
2551}
2552 1969
2553impl AstNode for ParenExpr { 1970impl AstNode for ParenExpr {
2554 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1971 fn cast(syntax: SyntaxNode) -> Option<Self> {
2555 match syntax.kind() { 1972 match syntax.kind() {
2556 PAREN_EXPR => Some(ParenExpr::from_repr(syntax.into_repr())), 1973 PAREN_EXPR => Some(ParenExpr { syntax }),
2557 _ => None, 1974 _ => None,
2558 } 1975 }
2559 } 1976 }
2560 fn syntax(&self) -> &SyntaxNode { &self.syntax } 1977 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2561} 1978}
2562 1979
2563impl ToOwned for ParenExpr {
2564 type Owned = TreeArc<ParenExpr>;
2565 fn to_owned(&self) -> TreeArc<ParenExpr> { TreeArc::cast(self.syntax.to_owned()) }
2566}
2567
2568 1980
2569impl ParenExpr { 1981impl ParenExpr {
2570 pub fn expr(&self) -> Option<&Expr> { 1982 pub fn expr(&self) -> Option<Expr> {
2571 super::child_opt(self) 1983 super::child_opt(self)
2572 } 1984 }
2573} 1985}
2574 1986
2575// ParenType 1987// ParenType
2576#[derive(Debug, PartialEq, Eq, Hash)] 1988#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2577#[repr(transparent)]
2578pub struct ParenType { 1989pub struct ParenType {
2579 pub(crate) syntax: SyntaxNode, 1990 pub(crate) syntax: SyntaxNode,
2580} 1991}
2581unsafe impl TransparentNewType for ParenType {
2582 type Repr = rowan::SyntaxNode;
2583}
2584 1992
2585impl AstNode for ParenType { 1993impl AstNode for ParenType {
2586 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 1994 fn cast(syntax: SyntaxNode) -> Option<Self> {
2587 match syntax.kind() { 1995 match syntax.kind() {
2588 PAREN_TYPE => Some(ParenType::from_repr(syntax.into_repr())), 1996 PAREN_TYPE => Some(ParenType { syntax }),
2589 _ => None, 1997 _ => None,
2590 } 1998 }
2591 } 1999 }
2592 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2000 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2593} 2001}
2594 2002
2595impl ToOwned for ParenType {
2596 type Owned = TreeArc<ParenType>;
2597 fn to_owned(&self) -> TreeArc<ParenType> { TreeArc::cast(self.syntax.to_owned()) }
2598}
2599
2600 2003
2601impl ParenType { 2004impl ParenType {
2602 pub fn type_ref(&self) -> Option<&TypeRef> { 2005 pub fn type_ref(&self) -> Option<TypeRef> {
2603 super::child_opt(self) 2006 super::child_opt(self)
2604 } 2007 }
2605} 2008}
2606 2009
2607// Pat 2010// Pat
2608#[derive(Debug, PartialEq, Eq, Hash)] 2011#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2609#[repr(transparent)]
2610pub struct Pat { 2012pub struct Pat {
2611 pub(crate) syntax: SyntaxNode, 2013 pub(crate) syntax: SyntaxNode,
2612} 2014}
2613unsafe impl TransparentNewType for Pat {
2614 type Repr = rowan::SyntaxNode;
2615}
2616 2015
2617#[derive(Debug, Clone, Copy, PartialEq, Eq)] 2016#[derive(Debug, Clone, PartialEq, Eq)]
2618pub enum PatKind<'a> { 2017pub enum PatKind {
2619 RefPat(&'a RefPat), 2018 RefPat(RefPat),
2620 BindPat(&'a BindPat), 2019 BindPat(BindPat),
2621 PlaceholderPat(&'a PlaceholderPat), 2020 PlaceholderPat(PlaceholderPat),
2622 PathPat(&'a PathPat), 2021 PathPat(PathPat),
2623 StructPat(&'a StructPat), 2022 StructPat(StructPat),
2624 TupleStructPat(&'a TupleStructPat), 2023 TupleStructPat(TupleStructPat),
2625 TuplePat(&'a TuplePat), 2024 TuplePat(TuplePat),
2626 SlicePat(&'a SlicePat), 2025 SlicePat(SlicePat),
2627 RangePat(&'a RangePat), 2026 RangePat(RangePat),
2628 LiteralPat(&'a LiteralPat), 2027 LiteralPat(LiteralPat),
2629} 2028}
2630impl<'a> From<&'a RefPat> for &'a Pat { 2029impl From<RefPat> for Pat {
2631 fn from(n: &'a RefPat) -> &'a Pat { 2030 fn from(n: RefPat) -> Pat {
2632 Pat::cast(&n.syntax).unwrap() 2031 Pat::cast(n.syntax).unwrap()
2633 } 2032 }
2634} 2033}
2635impl<'a> From<&'a BindPat> for &'a Pat { 2034impl From<BindPat> for Pat {
2636 fn from(n: &'a BindPat) -> &'a Pat { 2035 fn from(n: BindPat) -> Pat {
2637 Pat::cast(&n.syntax).unwrap() 2036 Pat::cast(n.syntax).unwrap()
2638 } 2037 }
2639} 2038}
2640impl<'a> From<&'a PlaceholderPat> for &'a Pat { 2039impl From<PlaceholderPat> for Pat {
2641 fn from(n: &'a PlaceholderPat) -> &'a Pat { 2040 fn from(n: PlaceholderPat) -> Pat {
2642 Pat::cast(&n.syntax).unwrap() 2041 Pat::cast(n.syntax).unwrap()
2643 } 2042 }
2644} 2043}
2645impl<'a> From<&'a PathPat> for &'a Pat { 2044impl From<PathPat> for Pat {
2646 fn from(n: &'a PathPat) -> &'a Pat { 2045 fn from(n: PathPat) -> Pat {
2647 Pat::cast(&n.syntax).unwrap() 2046 Pat::cast(n.syntax).unwrap()
2648 } 2047 }
2649} 2048}
2650impl<'a> From<&'a StructPat> for &'a Pat { 2049impl From<StructPat> for Pat {
2651 fn from(n: &'a StructPat) -> &'a Pat { 2050 fn from(n: StructPat) -> Pat {
2652 Pat::cast(&n.syntax).unwrap() 2051 Pat::cast(n.syntax).unwrap()
2653 } 2052 }
2654} 2053}
2655impl<'a> From<&'a TupleStructPat> for &'a Pat { 2054impl From<TupleStructPat> for Pat {
2656 fn from(n: &'a TupleStructPat) -> &'a Pat { 2055 fn from(n: TupleStructPat) -> Pat {
2657 Pat::cast(&n.syntax).unwrap() 2056 Pat::cast(n.syntax).unwrap()
2658 } 2057 }
2659} 2058}
2660impl<'a> From<&'a TuplePat> for &'a Pat { 2059impl From<TuplePat> for Pat {
2661 fn from(n: &'a TuplePat) -> &'a Pat { 2060 fn from(n: TuplePat) -> Pat {
2662 Pat::cast(&n.syntax).unwrap() 2061 Pat::cast(n.syntax).unwrap()
2663 } 2062 }
2664} 2063}
2665impl<'a> From<&'a SlicePat> for &'a Pat { 2064impl From<SlicePat> for Pat {
2666 fn from(n: &'a SlicePat) -> &'a Pat { 2065 fn from(n: SlicePat) -> Pat {
2667 Pat::cast(&n.syntax).unwrap() 2066 Pat::cast(n.syntax).unwrap()
2668 } 2067 }
2669} 2068}
2670impl<'a> From<&'a RangePat> for &'a Pat { 2069impl From<RangePat> for Pat {
2671 fn from(n: &'a RangePat) -> &'a Pat { 2070 fn from(n: RangePat) -> Pat {
2672 Pat::cast(&n.syntax).unwrap() 2071 Pat::cast(n.syntax).unwrap()
2673 } 2072 }
2674} 2073}
2675impl<'a> From<&'a LiteralPat> for &'a Pat { 2074impl From<LiteralPat> for Pat {
2676 fn from(n: &'a LiteralPat) -> &'a Pat { 2075 fn from(n: LiteralPat) -> Pat {
2677 Pat::cast(&n.syntax).unwrap() 2076 Pat::cast(n.syntax).unwrap()
2678 } 2077 }
2679} 2078}
2680 2079
2681 2080
2682impl AstNode for Pat { 2081impl AstNode for Pat {
2683 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2082 fn cast(syntax: SyntaxNode) -> Option<Self> {
2684 match syntax.kind() { 2083 match syntax.kind() {
2685 | REF_PAT 2084 | REF_PAT
2686 | BIND_PAT 2085 | BIND_PAT
@@ -2691,31 +2090,26 @@ impl AstNode for Pat {
2691 | TUPLE_PAT 2090 | TUPLE_PAT
2692 | SLICE_PAT 2091 | SLICE_PAT
2693 | RANGE_PAT 2092 | RANGE_PAT
2694 | LITERAL_PAT => Some(Pat::from_repr(syntax.into_repr())), 2093 | LITERAL_PAT => Some(Pat { syntax }),
2695 _ => None, 2094 _ => None,
2696 } 2095 }
2697 } 2096 }
2698 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2097 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2699} 2098}
2700 2099
2701impl ToOwned for Pat {
2702 type Owned = TreeArc<Pat>;
2703 fn to_owned(&self) -> TreeArc<Pat> { TreeArc::cast(self.syntax.to_owned()) }
2704}
2705
2706impl Pat { 2100impl Pat {
2707 pub fn kind(&self) -> PatKind { 2101 pub fn kind(&self) -> PatKind {
2708 match self.syntax.kind() { 2102 match self.syntax.kind() {
2709 REF_PAT => PatKind::RefPat(RefPat::cast(&self.syntax).unwrap()), 2103 REF_PAT => PatKind::RefPat(RefPat::cast(self.syntax.clone()).unwrap()),
2710 BIND_PAT => PatKind::BindPat(BindPat::cast(&self.syntax).unwrap()), 2104 BIND_PAT => PatKind::BindPat(BindPat::cast(self.syntax.clone()).unwrap()),
2711 PLACEHOLDER_PAT => PatKind::PlaceholderPat(PlaceholderPat::cast(&self.syntax).unwrap()), 2105 PLACEHOLDER_PAT => PatKind::PlaceholderPat(PlaceholderPat::cast(self.syntax.clone()).unwrap()),
2712 PATH_PAT => PatKind::PathPat(PathPat::cast(&self.syntax).unwrap()), 2106 PATH_PAT => PatKind::PathPat(PathPat::cast(self.syntax.clone()).unwrap()),
2713 STRUCT_PAT => PatKind::StructPat(StructPat::cast(&self.syntax).unwrap()), 2107 STRUCT_PAT => PatKind::StructPat(StructPat::cast(self.syntax.clone()).unwrap()),
2714 TUPLE_STRUCT_PAT => PatKind::TupleStructPat(TupleStructPat::cast(&self.syntax).unwrap()), 2108 TUPLE_STRUCT_PAT => PatKind::TupleStructPat(TupleStructPat::cast(self.syntax.clone()).unwrap()),
2715 TUPLE_PAT => PatKind::TuplePat(TuplePat::cast(&self.syntax).unwrap()), 2109 TUPLE_PAT => PatKind::TuplePat(TuplePat::cast(self.syntax.clone()).unwrap()),
2716 SLICE_PAT => PatKind::SlicePat(SlicePat::cast(&self.syntax).unwrap()), 2110 SLICE_PAT => PatKind::SlicePat(SlicePat::cast(self.syntax.clone()).unwrap()),
2717 RANGE_PAT => PatKind::RangePat(RangePat::cast(&self.syntax).unwrap()), 2111 RANGE_PAT => PatKind::RangePat(RangePat::cast(self.syntax.clone()).unwrap()),
2718 LITERAL_PAT => PatKind::LiteralPat(LiteralPat::cast(&self.syntax).unwrap()), 2112 LITERAL_PAT => PatKind::LiteralPat(LiteralPat::cast(self.syntax.clone()).unwrap()),
2719 _ => unreachable!(), 2113 _ => unreachable!(),
2720 } 2114 }
2721 } 2115 }
@@ -2724,723 +2118,516 @@ impl Pat {
2724impl Pat {} 2118impl Pat {}
2725 2119
2726// Path 2120// Path
2727#[derive(Debug, PartialEq, Eq, Hash)] 2121#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2728#[repr(transparent)]
2729pub struct Path { 2122pub struct Path {
2730 pub(crate) syntax: SyntaxNode, 2123 pub(crate) syntax: SyntaxNode,
2731} 2124}
2732unsafe impl TransparentNewType for Path {
2733 type Repr = rowan::SyntaxNode;
2734}
2735 2125
2736impl AstNode for Path { 2126impl AstNode for Path {
2737 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2127 fn cast(syntax: SyntaxNode) -> Option<Self> {
2738 match syntax.kind() { 2128 match syntax.kind() {
2739 PATH => Some(Path::from_repr(syntax.into_repr())), 2129 PATH => Some(Path { syntax }),
2740 _ => None, 2130 _ => None,
2741 } 2131 }
2742 } 2132 }
2743 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2133 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2744} 2134}
2745 2135
2746impl ToOwned for Path {
2747 type Owned = TreeArc<Path>;
2748 fn to_owned(&self) -> TreeArc<Path> { TreeArc::cast(self.syntax.to_owned()) }
2749}
2750
2751 2136
2752impl Path { 2137impl Path {
2753 pub fn segment(&self) -> Option<&PathSegment> { 2138 pub fn segment(&self) -> Option<PathSegment> {
2754 super::child_opt(self) 2139 super::child_opt(self)
2755 } 2140 }
2756 2141
2757 pub fn qualifier(&self) -> Option<&Path> { 2142 pub fn qualifier(&self) -> Option<Path> {
2758 super::child_opt(self) 2143 super::child_opt(self)
2759 } 2144 }
2760} 2145}
2761 2146
2762// PathExpr 2147// PathExpr
2763#[derive(Debug, PartialEq, Eq, Hash)] 2148#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2764#[repr(transparent)]
2765pub struct PathExpr { 2149pub struct PathExpr {
2766 pub(crate) syntax: SyntaxNode, 2150 pub(crate) syntax: SyntaxNode,
2767} 2151}
2768unsafe impl TransparentNewType for PathExpr {
2769 type Repr = rowan::SyntaxNode;
2770}
2771 2152
2772impl AstNode for PathExpr { 2153impl AstNode for PathExpr {
2773 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2154 fn cast(syntax: SyntaxNode) -> Option<Self> {
2774 match syntax.kind() { 2155 match syntax.kind() {
2775 PATH_EXPR => Some(PathExpr::from_repr(syntax.into_repr())), 2156 PATH_EXPR => Some(PathExpr { syntax }),
2776 _ => None, 2157 _ => None,
2777 } 2158 }
2778 } 2159 }
2779 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2160 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2780} 2161}
2781 2162
2782impl ToOwned for PathExpr {
2783 type Owned = TreeArc<PathExpr>;
2784 fn to_owned(&self) -> TreeArc<PathExpr> { TreeArc::cast(self.syntax.to_owned()) }
2785}
2786
2787 2163
2788impl PathExpr { 2164impl PathExpr {
2789 pub fn path(&self) -> Option<&Path> { 2165 pub fn path(&self) -> Option<Path> {
2790 super::child_opt(self) 2166 super::child_opt(self)
2791 } 2167 }
2792} 2168}
2793 2169
2794// PathPat 2170// PathPat
2795#[derive(Debug, PartialEq, Eq, Hash)] 2171#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2796#[repr(transparent)]
2797pub struct PathPat { 2172pub struct PathPat {
2798 pub(crate) syntax: SyntaxNode, 2173 pub(crate) syntax: SyntaxNode,
2799} 2174}
2800unsafe impl TransparentNewType for PathPat {
2801 type Repr = rowan::SyntaxNode;
2802}
2803 2175
2804impl AstNode for PathPat { 2176impl AstNode for PathPat {
2805 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2177 fn cast(syntax: SyntaxNode) -> Option<Self> {
2806 match syntax.kind() { 2178 match syntax.kind() {
2807 PATH_PAT => Some(PathPat::from_repr(syntax.into_repr())), 2179 PATH_PAT => Some(PathPat { syntax }),
2808 _ => None, 2180 _ => None,
2809 } 2181 }
2810 } 2182 }
2811 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2183 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2812} 2184}
2813 2185
2814impl ToOwned for PathPat {
2815 type Owned = TreeArc<PathPat>;
2816 fn to_owned(&self) -> TreeArc<PathPat> { TreeArc::cast(self.syntax.to_owned()) }
2817}
2818
2819 2186
2820impl PathPat { 2187impl PathPat {
2821 pub fn path(&self) -> Option<&Path> { 2188 pub fn path(&self) -> Option<Path> {
2822 super::child_opt(self) 2189 super::child_opt(self)
2823 } 2190 }
2824} 2191}
2825 2192
2826// PathSegment 2193// PathSegment
2827#[derive(Debug, PartialEq, Eq, Hash)] 2194#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2828#[repr(transparent)]
2829pub struct PathSegment { 2195pub struct PathSegment {
2830 pub(crate) syntax: SyntaxNode, 2196 pub(crate) syntax: SyntaxNode,
2831} 2197}
2832unsafe impl TransparentNewType for PathSegment {
2833 type Repr = rowan::SyntaxNode;
2834}
2835 2198
2836impl AstNode for PathSegment { 2199impl AstNode for PathSegment {
2837 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2200 fn cast(syntax: SyntaxNode) -> Option<Self> {
2838 match syntax.kind() { 2201 match syntax.kind() {
2839 PATH_SEGMENT => Some(PathSegment::from_repr(syntax.into_repr())), 2202 PATH_SEGMENT => Some(PathSegment { syntax }),
2840 _ => None, 2203 _ => None,
2841 } 2204 }
2842 } 2205 }
2843 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2206 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2844} 2207}
2845 2208
2846impl ToOwned for PathSegment {
2847 type Owned = TreeArc<PathSegment>;
2848 fn to_owned(&self) -> TreeArc<PathSegment> { TreeArc::cast(self.syntax.to_owned()) }
2849}
2850
2851 2209
2852impl PathSegment { 2210impl PathSegment {
2853 pub fn name_ref(&self) -> Option<&NameRef> { 2211 pub fn name_ref(&self) -> Option<NameRef> {
2854 super::child_opt(self) 2212 super::child_opt(self)
2855 } 2213 }
2856 2214
2857 pub fn type_arg_list(&self) -> Option<&TypeArgList> { 2215 pub fn type_arg_list(&self) -> Option<TypeArgList> {
2858 super::child_opt(self) 2216 super::child_opt(self)
2859 } 2217 }
2860} 2218}
2861 2219
2862// PathType 2220// PathType
2863#[derive(Debug, PartialEq, Eq, Hash)] 2221#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2864#[repr(transparent)]
2865pub struct PathType { 2222pub struct PathType {
2866 pub(crate) syntax: SyntaxNode, 2223 pub(crate) syntax: SyntaxNode,
2867} 2224}
2868unsafe impl TransparentNewType for PathType {
2869 type Repr = rowan::SyntaxNode;
2870}
2871 2225
2872impl AstNode for PathType { 2226impl AstNode for PathType {
2873 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2227 fn cast(syntax: SyntaxNode) -> Option<Self> {
2874 match syntax.kind() { 2228 match syntax.kind() {
2875 PATH_TYPE => Some(PathType::from_repr(syntax.into_repr())), 2229 PATH_TYPE => Some(PathType { syntax }),
2876 _ => None, 2230 _ => None,
2877 } 2231 }
2878 } 2232 }
2879 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2233 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2880} 2234}
2881 2235
2882impl ToOwned for PathType {
2883 type Owned = TreeArc<PathType>;
2884 fn to_owned(&self) -> TreeArc<PathType> { TreeArc::cast(self.syntax.to_owned()) }
2885}
2886
2887 2236
2888impl PathType { 2237impl PathType {
2889 pub fn path(&self) -> Option<&Path> { 2238 pub fn path(&self) -> Option<Path> {
2890 super::child_opt(self) 2239 super::child_opt(self)
2891 } 2240 }
2892} 2241}
2893 2242
2894// PlaceholderPat 2243// PlaceholderPat
2895#[derive(Debug, PartialEq, Eq, Hash)] 2244#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2896#[repr(transparent)]
2897pub struct PlaceholderPat { 2245pub struct PlaceholderPat {
2898 pub(crate) syntax: SyntaxNode, 2246 pub(crate) syntax: SyntaxNode,
2899} 2247}
2900unsafe impl TransparentNewType for PlaceholderPat {
2901 type Repr = rowan::SyntaxNode;
2902}
2903 2248
2904impl AstNode for PlaceholderPat { 2249impl AstNode for PlaceholderPat {
2905 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2250 fn cast(syntax: SyntaxNode) -> Option<Self> {
2906 match syntax.kind() { 2251 match syntax.kind() {
2907 PLACEHOLDER_PAT => Some(PlaceholderPat::from_repr(syntax.into_repr())), 2252 PLACEHOLDER_PAT => Some(PlaceholderPat { syntax }),
2908 _ => None, 2253 _ => None,
2909 } 2254 }
2910 } 2255 }
2911 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2256 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2912} 2257}
2913 2258
2914impl ToOwned for PlaceholderPat {
2915 type Owned = TreeArc<PlaceholderPat>;
2916 fn to_owned(&self) -> TreeArc<PlaceholderPat> { TreeArc::cast(self.syntax.to_owned()) }
2917}
2918
2919 2259
2920impl PlaceholderPat {} 2260impl PlaceholderPat {}
2921 2261
2922// PlaceholderType 2262// PlaceholderType
2923#[derive(Debug, PartialEq, Eq, Hash)] 2263#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2924#[repr(transparent)]
2925pub struct PlaceholderType { 2264pub struct PlaceholderType {
2926 pub(crate) syntax: SyntaxNode, 2265 pub(crate) syntax: SyntaxNode,
2927} 2266}
2928unsafe impl TransparentNewType for PlaceholderType {
2929 type Repr = rowan::SyntaxNode;
2930}
2931 2267
2932impl AstNode for PlaceholderType { 2268impl AstNode for PlaceholderType {
2933 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2269 fn cast(syntax: SyntaxNode) -> Option<Self> {
2934 match syntax.kind() { 2270 match syntax.kind() {
2935 PLACEHOLDER_TYPE => Some(PlaceholderType::from_repr(syntax.into_repr())), 2271 PLACEHOLDER_TYPE => Some(PlaceholderType { syntax }),
2936 _ => None, 2272 _ => None,
2937 } 2273 }
2938 } 2274 }
2939 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2275 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2940} 2276}
2941 2277
2942impl ToOwned for PlaceholderType {
2943 type Owned = TreeArc<PlaceholderType>;
2944 fn to_owned(&self) -> TreeArc<PlaceholderType> { TreeArc::cast(self.syntax.to_owned()) }
2945}
2946
2947 2278
2948impl PlaceholderType {} 2279impl PlaceholderType {}
2949 2280
2950// PointerType 2281// PointerType
2951#[derive(Debug, PartialEq, Eq, Hash)] 2282#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2952#[repr(transparent)]
2953pub struct PointerType { 2283pub struct PointerType {
2954 pub(crate) syntax: SyntaxNode, 2284 pub(crate) syntax: SyntaxNode,
2955} 2285}
2956unsafe impl TransparentNewType for PointerType {
2957 type Repr = rowan::SyntaxNode;
2958}
2959 2286
2960impl AstNode for PointerType { 2287impl AstNode for PointerType {
2961 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2288 fn cast(syntax: SyntaxNode) -> Option<Self> {
2962 match syntax.kind() { 2289 match syntax.kind() {
2963 POINTER_TYPE => Some(PointerType::from_repr(syntax.into_repr())), 2290 POINTER_TYPE => Some(PointerType { syntax }),
2964 _ => None, 2291 _ => None,
2965 } 2292 }
2966 } 2293 }
2967 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2294 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2968} 2295}
2969 2296
2970impl ToOwned for PointerType {
2971 type Owned = TreeArc<PointerType>;
2972 fn to_owned(&self) -> TreeArc<PointerType> { TreeArc::cast(self.syntax.to_owned()) }
2973}
2974
2975 2297
2976impl PointerType { 2298impl PointerType {
2977 pub fn type_ref(&self) -> Option<&TypeRef> { 2299 pub fn type_ref(&self) -> Option<TypeRef> {
2978 super::child_opt(self) 2300 super::child_opt(self)
2979 } 2301 }
2980} 2302}
2981 2303
2982// PosFieldDef 2304// PosFieldDef
2983#[derive(Debug, PartialEq, Eq, Hash)] 2305#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2984#[repr(transparent)]
2985pub struct PosFieldDef { 2306pub struct PosFieldDef {
2986 pub(crate) syntax: SyntaxNode, 2307 pub(crate) syntax: SyntaxNode,
2987} 2308}
2988unsafe impl TransparentNewType for PosFieldDef {
2989 type Repr = rowan::SyntaxNode;
2990}
2991 2309
2992impl AstNode for PosFieldDef { 2310impl AstNode for PosFieldDef {
2993 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2311 fn cast(syntax: SyntaxNode) -> Option<Self> {
2994 match syntax.kind() { 2312 match syntax.kind() {
2995 POS_FIELD_DEF => Some(PosFieldDef::from_repr(syntax.into_repr())), 2313 POS_FIELD_DEF => Some(PosFieldDef { syntax }),
2996 _ => None, 2314 _ => None,
2997 } 2315 }
2998 } 2316 }
2999 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2317 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3000} 2318}
3001 2319
3002impl ToOwned for PosFieldDef {
3003 type Owned = TreeArc<PosFieldDef>;
3004 fn to_owned(&self) -> TreeArc<PosFieldDef> { TreeArc::cast(self.syntax.to_owned()) }
3005}
3006
3007 2320
3008impl ast::VisibilityOwner for PosFieldDef {} 2321impl ast::VisibilityOwner for PosFieldDef {}
3009impl ast::AttrsOwner for PosFieldDef {} 2322impl ast::AttrsOwner for PosFieldDef {}
3010impl PosFieldDef { 2323impl PosFieldDef {
3011 pub fn type_ref(&self) -> Option<&TypeRef> { 2324 pub fn type_ref(&self) -> Option<TypeRef> {
3012 super::child_opt(self) 2325 super::child_opt(self)
3013 } 2326 }
3014} 2327}
3015 2328
3016// PosFieldDefList 2329// PosFieldDefList
3017#[derive(Debug, PartialEq, Eq, Hash)] 2330#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3018#[repr(transparent)]
3019pub struct PosFieldDefList { 2331pub struct PosFieldDefList {
3020 pub(crate) syntax: SyntaxNode, 2332 pub(crate) syntax: SyntaxNode,
3021} 2333}
3022unsafe impl TransparentNewType for PosFieldDefList {
3023 type Repr = rowan::SyntaxNode;
3024}
3025 2334
3026impl AstNode for PosFieldDefList { 2335impl AstNode for PosFieldDefList {
3027 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2336 fn cast(syntax: SyntaxNode) -> Option<Self> {
3028 match syntax.kind() { 2337 match syntax.kind() {
3029 POS_FIELD_DEF_LIST => Some(PosFieldDefList::from_repr(syntax.into_repr())), 2338 POS_FIELD_DEF_LIST => Some(PosFieldDefList { syntax }),
3030 _ => None, 2339 _ => None,
3031 } 2340 }
3032 } 2341 }
3033 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2342 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3034} 2343}
3035 2344
3036impl ToOwned for PosFieldDefList {
3037 type Owned = TreeArc<PosFieldDefList>;
3038 fn to_owned(&self) -> TreeArc<PosFieldDefList> { TreeArc::cast(self.syntax.to_owned()) }
3039}
3040
3041 2345
3042impl PosFieldDefList { 2346impl PosFieldDefList {
3043 pub fn fields(&self) -> impl Iterator<Item = &PosFieldDef> { 2347 pub fn fields(&self) -> impl Iterator<Item = PosFieldDef> {
3044 super::children(self) 2348 super::children(self)
3045 } 2349 }
3046} 2350}
3047 2351
3048// PrefixExpr 2352// PrefixExpr
3049#[derive(Debug, PartialEq, Eq, Hash)] 2353#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3050#[repr(transparent)]
3051pub struct PrefixExpr { 2354pub struct PrefixExpr {
3052 pub(crate) syntax: SyntaxNode, 2355 pub(crate) syntax: SyntaxNode,
3053} 2356}
3054unsafe impl TransparentNewType for PrefixExpr {
3055 type Repr = rowan::SyntaxNode;
3056}
3057 2357
3058impl AstNode for PrefixExpr { 2358impl AstNode for PrefixExpr {
3059 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2359 fn cast(syntax: SyntaxNode) -> Option<Self> {
3060 match syntax.kind() { 2360 match syntax.kind() {
3061 PREFIX_EXPR => Some(PrefixExpr::from_repr(syntax.into_repr())), 2361 PREFIX_EXPR => Some(PrefixExpr { syntax }),
3062 _ => None, 2362 _ => None,
3063 } 2363 }
3064 } 2364 }
3065 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2365 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3066} 2366}
3067 2367
3068impl ToOwned for PrefixExpr {
3069 type Owned = TreeArc<PrefixExpr>;
3070 fn to_owned(&self) -> TreeArc<PrefixExpr> { TreeArc::cast(self.syntax.to_owned()) }
3071}
3072
3073 2368
3074impl PrefixExpr { 2369impl PrefixExpr {
3075 pub fn expr(&self) -> Option<&Expr> { 2370 pub fn expr(&self) -> Option<Expr> {
3076 super::child_opt(self) 2371 super::child_opt(self)
3077 } 2372 }
3078} 2373}
3079 2374
3080// RangeExpr 2375// RangeExpr
3081#[derive(Debug, PartialEq, Eq, Hash)] 2376#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3082#[repr(transparent)]
3083pub struct RangeExpr { 2377pub struct RangeExpr {
3084 pub(crate) syntax: SyntaxNode, 2378 pub(crate) syntax: SyntaxNode,
3085} 2379}
3086unsafe impl TransparentNewType for RangeExpr {
3087 type Repr = rowan::SyntaxNode;
3088}
3089 2380
3090impl AstNode for RangeExpr { 2381impl AstNode for RangeExpr {
3091 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2382 fn cast(syntax: SyntaxNode) -> Option<Self> {
3092 match syntax.kind() { 2383 match syntax.kind() {
3093 RANGE_EXPR => Some(RangeExpr::from_repr(syntax.into_repr())), 2384 RANGE_EXPR => Some(RangeExpr { syntax }),
3094 _ => None, 2385 _ => None,
3095 } 2386 }
3096 } 2387 }
3097 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2388 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3098} 2389}
3099 2390
3100impl ToOwned for RangeExpr {
3101 type Owned = TreeArc<RangeExpr>;
3102 fn to_owned(&self) -> TreeArc<RangeExpr> { TreeArc::cast(self.syntax.to_owned()) }
3103}
3104
3105 2391
3106impl RangeExpr {} 2392impl RangeExpr {}
3107 2393
3108// RangePat 2394// RangePat
3109#[derive(Debug, PartialEq, Eq, Hash)] 2395#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3110#[repr(transparent)]
3111pub struct RangePat { 2396pub struct RangePat {
3112 pub(crate) syntax: SyntaxNode, 2397 pub(crate) syntax: SyntaxNode,
3113} 2398}
3114unsafe impl TransparentNewType for RangePat {
3115 type Repr = rowan::SyntaxNode;
3116}
3117 2399
3118impl AstNode for RangePat { 2400impl AstNode for RangePat {
3119 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2401 fn cast(syntax: SyntaxNode) -> Option<Self> {
3120 match syntax.kind() { 2402 match syntax.kind() {
3121 RANGE_PAT => Some(RangePat::from_repr(syntax.into_repr())), 2403 RANGE_PAT => Some(RangePat { syntax }),
3122 _ => None, 2404 _ => None,
3123 } 2405 }
3124 } 2406 }
3125 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2407 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3126} 2408}
3127 2409
3128impl ToOwned for RangePat {
3129 type Owned = TreeArc<RangePat>;
3130 fn to_owned(&self) -> TreeArc<RangePat> { TreeArc::cast(self.syntax.to_owned()) }
3131}
3132
3133 2410
3134impl RangePat {} 2411impl RangePat {}
3135 2412
3136// RefExpr 2413// RefExpr
3137#[derive(Debug, PartialEq, Eq, Hash)] 2414#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3138#[repr(transparent)]
3139pub struct RefExpr { 2415pub struct RefExpr {
3140 pub(crate) syntax: SyntaxNode, 2416 pub(crate) syntax: SyntaxNode,
3141} 2417}
3142unsafe impl TransparentNewType for RefExpr {
3143 type Repr = rowan::SyntaxNode;
3144}
3145 2418
3146impl AstNode for RefExpr { 2419impl AstNode for RefExpr {
3147 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2420 fn cast(syntax: SyntaxNode) -> Option<Self> {
3148 match syntax.kind() { 2421 match syntax.kind() {
3149 REF_EXPR => Some(RefExpr::from_repr(syntax.into_repr())), 2422 REF_EXPR => Some(RefExpr { syntax }),
3150 _ => None, 2423 _ => None,
3151 } 2424 }
3152 } 2425 }
3153 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2426 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3154} 2427}
3155 2428
3156impl ToOwned for RefExpr {
3157 type Owned = TreeArc<RefExpr>;
3158 fn to_owned(&self) -> TreeArc<RefExpr> { TreeArc::cast(self.syntax.to_owned()) }
3159}
3160
3161 2429
3162impl RefExpr { 2430impl RefExpr {
3163 pub fn expr(&self) -> Option<&Expr> { 2431 pub fn expr(&self) -> Option<Expr> {
3164 super::child_opt(self) 2432 super::child_opt(self)
3165 } 2433 }
3166} 2434}
3167 2435
3168// RefPat 2436// RefPat
3169#[derive(Debug, PartialEq, Eq, Hash)] 2437#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3170#[repr(transparent)]
3171pub struct RefPat { 2438pub struct RefPat {
3172 pub(crate) syntax: SyntaxNode, 2439 pub(crate) syntax: SyntaxNode,
3173} 2440}
3174unsafe impl TransparentNewType for RefPat {
3175 type Repr = rowan::SyntaxNode;
3176}
3177 2441
3178impl AstNode for RefPat { 2442impl AstNode for RefPat {
3179 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2443 fn cast(syntax: SyntaxNode) -> Option<Self> {
3180 match syntax.kind() { 2444 match syntax.kind() {
3181 REF_PAT => Some(RefPat::from_repr(syntax.into_repr())), 2445 REF_PAT => Some(RefPat { syntax }),
3182 _ => None, 2446 _ => None,
3183 } 2447 }
3184 } 2448 }
3185 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2449 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3186} 2450}
3187 2451
3188impl ToOwned for RefPat {
3189 type Owned = TreeArc<RefPat>;
3190 fn to_owned(&self) -> TreeArc<RefPat> { TreeArc::cast(self.syntax.to_owned()) }
3191}
3192
3193 2452
3194impl RefPat { 2453impl RefPat {
3195 pub fn pat(&self) -> Option<&Pat> { 2454 pub fn pat(&self) -> Option<Pat> {
3196 super::child_opt(self) 2455 super::child_opt(self)
3197 } 2456 }
3198} 2457}
3199 2458
3200// ReferenceType 2459// ReferenceType
3201#[derive(Debug, PartialEq, Eq, Hash)] 2460#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3202#[repr(transparent)]
3203pub struct ReferenceType { 2461pub struct ReferenceType {
3204 pub(crate) syntax: SyntaxNode, 2462 pub(crate) syntax: SyntaxNode,
3205} 2463}
3206unsafe impl TransparentNewType for ReferenceType {
3207 type Repr = rowan::SyntaxNode;
3208}
3209 2464
3210impl AstNode for ReferenceType { 2465impl AstNode for ReferenceType {
3211 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2466 fn cast(syntax: SyntaxNode) -> Option<Self> {
3212 match syntax.kind() { 2467 match syntax.kind() {
3213 REFERENCE_TYPE => Some(ReferenceType::from_repr(syntax.into_repr())), 2468 REFERENCE_TYPE => Some(ReferenceType { syntax }),
3214 _ => None, 2469 _ => None,
3215 } 2470 }
3216 } 2471 }
3217 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2472 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3218} 2473}
3219 2474
3220impl ToOwned for ReferenceType {
3221 type Owned = TreeArc<ReferenceType>;
3222 fn to_owned(&self) -> TreeArc<ReferenceType> { TreeArc::cast(self.syntax.to_owned()) }
3223}
3224
3225 2475
3226impl ReferenceType { 2476impl ReferenceType {
3227 pub fn type_ref(&self) -> Option<&TypeRef> { 2477 pub fn type_ref(&self) -> Option<TypeRef> {
3228 super::child_opt(self) 2478 super::child_opt(self)
3229 } 2479 }
3230} 2480}
3231 2481
3232// RetType 2482// RetType
3233#[derive(Debug, PartialEq, Eq, Hash)] 2483#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3234#[repr(transparent)]
3235pub struct RetType { 2484pub struct RetType {
3236 pub(crate) syntax: SyntaxNode, 2485 pub(crate) syntax: SyntaxNode,
3237} 2486}
3238unsafe impl TransparentNewType for RetType {
3239 type Repr = rowan::SyntaxNode;
3240}
3241 2487
3242impl AstNode for RetType { 2488impl AstNode for RetType {
3243 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2489 fn cast(syntax: SyntaxNode) -> Option<Self> {
3244 match syntax.kind() { 2490 match syntax.kind() {
3245 RET_TYPE => Some(RetType::from_repr(syntax.into_repr())), 2491 RET_TYPE => Some(RetType { syntax }),
3246 _ => None, 2492 _ => None,
3247 } 2493 }
3248 } 2494 }
3249 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2495 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3250} 2496}
3251 2497
3252impl ToOwned for RetType {
3253 type Owned = TreeArc<RetType>;
3254 fn to_owned(&self) -> TreeArc<RetType> { TreeArc::cast(self.syntax.to_owned()) }
3255}
3256
3257 2498
3258impl RetType { 2499impl RetType {
3259 pub fn type_ref(&self) -> Option<&TypeRef> { 2500 pub fn type_ref(&self) -> Option<TypeRef> {
3260 super::child_opt(self) 2501 super::child_opt(self)
3261 } 2502 }
3262} 2503}
3263 2504
3264// ReturnExpr 2505// ReturnExpr
3265#[derive(Debug, PartialEq, Eq, Hash)] 2506#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3266#[repr(transparent)]
3267pub struct ReturnExpr { 2507pub struct ReturnExpr {
3268 pub(crate) syntax: SyntaxNode, 2508 pub(crate) syntax: SyntaxNode,
3269} 2509}
3270unsafe impl TransparentNewType for ReturnExpr {
3271 type Repr = rowan::SyntaxNode;
3272}
3273 2510
3274impl AstNode for ReturnExpr { 2511impl AstNode for ReturnExpr {
3275 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2512 fn cast(syntax: SyntaxNode) -> Option<Self> {
3276 match syntax.kind() { 2513 match syntax.kind() {
3277 RETURN_EXPR => Some(ReturnExpr::from_repr(syntax.into_repr())), 2514 RETURN_EXPR => Some(ReturnExpr { syntax }),
3278 _ => None, 2515 _ => None,
3279 } 2516 }
3280 } 2517 }
3281 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2518 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3282} 2519}
3283 2520
3284impl ToOwned for ReturnExpr {
3285 type Owned = TreeArc<ReturnExpr>;
3286 fn to_owned(&self) -> TreeArc<ReturnExpr> { TreeArc::cast(self.syntax.to_owned()) }
3287}
3288
3289 2521
3290impl ReturnExpr { 2522impl ReturnExpr {
3291 pub fn expr(&self) -> Option<&Expr> { 2523 pub fn expr(&self) -> Option<Expr> {
3292 super::child_opt(self) 2524 super::child_opt(self)
3293 } 2525 }
3294} 2526}
3295 2527
3296// SelfParam 2528// SelfParam
3297#[derive(Debug, PartialEq, Eq, Hash)] 2529#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3298#[repr(transparent)]
3299pub struct SelfParam { 2530pub struct SelfParam {
3300 pub(crate) syntax: SyntaxNode, 2531 pub(crate) syntax: SyntaxNode,
3301} 2532}
3302unsafe impl TransparentNewType for SelfParam {
3303 type Repr = rowan::SyntaxNode;
3304}
3305 2533
3306impl AstNode for SelfParam { 2534impl AstNode for SelfParam {
3307 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2535 fn cast(syntax: SyntaxNode) -> Option<Self> {
3308 match syntax.kind() { 2536 match syntax.kind() {
3309 SELF_PARAM => Some(SelfParam::from_repr(syntax.into_repr())), 2537 SELF_PARAM => Some(SelfParam { syntax }),
3310 _ => None, 2538 _ => None,
3311 } 2539 }
3312 } 2540 }
3313 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2541 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3314} 2542}
3315 2543
3316impl ToOwned for SelfParam {
3317 type Owned = TreeArc<SelfParam>;
3318 fn to_owned(&self) -> TreeArc<SelfParam> { TreeArc::cast(self.syntax.to_owned()) }
3319}
3320
3321 2544
3322impl ast::TypeAscriptionOwner for SelfParam {} 2545impl ast::TypeAscriptionOwner for SelfParam {}
3323impl SelfParam {} 2546impl SelfParam {}
3324 2547
3325// SlicePat 2548// SlicePat
3326#[derive(Debug, PartialEq, Eq, Hash)] 2549#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3327#[repr(transparent)]
3328pub struct SlicePat { 2550pub struct SlicePat {
3329 pub(crate) syntax: SyntaxNode, 2551 pub(crate) syntax: SyntaxNode,
3330} 2552}
3331unsafe impl TransparentNewType for SlicePat {
3332 type Repr = rowan::SyntaxNode;
3333}
3334 2553
3335impl AstNode for SlicePat { 2554impl AstNode for SlicePat {
3336 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2555 fn cast(syntax: SyntaxNode) -> Option<Self> {
3337 match syntax.kind() { 2556 match syntax.kind() {
3338 SLICE_PAT => Some(SlicePat::from_repr(syntax.into_repr())), 2557 SLICE_PAT => Some(SlicePat { syntax }),
3339 _ => None, 2558 _ => None,
3340 } 2559 }
3341 } 2560 }
3342 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2561 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3343} 2562}
3344 2563
3345impl ToOwned for SlicePat {
3346 type Owned = TreeArc<SlicePat>;
3347 fn to_owned(&self) -> TreeArc<SlicePat> { TreeArc::cast(self.syntax.to_owned()) }
3348}
3349
3350 2564
3351impl SlicePat {} 2565impl SlicePat {}
3352 2566
3353// SliceType 2567// SliceType
3354#[derive(Debug, PartialEq, Eq, Hash)] 2568#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3355#[repr(transparent)]
3356pub struct SliceType { 2569pub struct SliceType {
3357 pub(crate) syntax: SyntaxNode, 2570 pub(crate) syntax: SyntaxNode,
3358} 2571}
3359unsafe impl TransparentNewType for SliceType {
3360 type Repr = rowan::SyntaxNode;
3361}
3362 2572
3363impl AstNode for SliceType { 2573impl AstNode for SliceType {
3364 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2574 fn cast(syntax: SyntaxNode) -> Option<Self> {
3365 match syntax.kind() { 2575 match syntax.kind() {
3366 SLICE_TYPE => Some(SliceType::from_repr(syntax.into_repr())), 2576 SLICE_TYPE => Some(SliceType { syntax }),
3367 _ => None, 2577 _ => None,
3368 } 2578 }
3369 } 2579 }
3370 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2580 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3371} 2581}
3372 2582
3373impl ToOwned for SliceType {
3374 type Owned = TreeArc<SliceType>;
3375 fn to_owned(&self) -> TreeArc<SliceType> { TreeArc::cast(self.syntax.to_owned()) }
3376}
3377
3378 2583
3379impl SliceType { 2584impl SliceType {
3380 pub fn type_ref(&self) -> Option<&TypeRef> { 2585 pub fn type_ref(&self) -> Option<TypeRef> {
3381 super::child_opt(self) 2586 super::child_opt(self)
3382 } 2587 }
3383} 2588}
3384 2589
3385// SourceFile 2590// SourceFile
3386#[derive(Debug, PartialEq, Eq, Hash)] 2591#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3387#[repr(transparent)]
3388pub struct SourceFile { 2592pub struct SourceFile {
3389 pub(crate) syntax: SyntaxNode, 2593 pub(crate) syntax: SyntaxNode,
3390} 2594}
3391unsafe impl TransparentNewType for SourceFile {
3392 type Repr = rowan::SyntaxNode;
3393}
3394 2595
3395impl AstNode for SourceFile { 2596impl AstNode for SourceFile {
3396 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2597 fn cast(syntax: SyntaxNode) -> Option<Self> {
3397 match syntax.kind() { 2598 match syntax.kind() {
3398 SOURCE_FILE => Some(SourceFile::from_repr(syntax.into_repr())), 2599 SOURCE_FILE => Some(SourceFile { syntax }),
3399 _ => None, 2600 _ => None,
3400 } 2601 }
3401 } 2602 }
3402 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2603 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3403} 2604}
3404 2605
3405impl ToOwned for SourceFile {
3406 type Owned = TreeArc<SourceFile>;
3407 fn to_owned(&self) -> TreeArc<SourceFile> { TreeArc::cast(self.syntax.to_owned()) }
3408}
3409
3410 2606
3411impl ast::ModuleItemOwner for SourceFile {} 2607impl ast::ModuleItemOwner for SourceFile {}
3412impl ast::FnDefOwner for SourceFile {} 2608impl ast::FnDefOwner for SourceFile {}
3413impl SourceFile { 2609impl SourceFile {
3414 pub fn modules(&self) -> impl Iterator<Item = &Module> { 2610 pub fn modules(&self) -> impl Iterator<Item = Module> {
3415 super::children(self) 2611 super::children(self)
3416 } 2612 }
3417} 2613}
3418 2614
3419// StaticDef 2615// StaticDef
3420#[derive(Debug, PartialEq, Eq, Hash)] 2616#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3421#[repr(transparent)]
3422pub struct StaticDef { 2617pub struct StaticDef {
3423 pub(crate) syntax: SyntaxNode, 2618 pub(crate) syntax: SyntaxNode,
3424} 2619}
3425unsafe impl TransparentNewType for StaticDef {
3426 type Repr = rowan::SyntaxNode;
3427}
3428 2620
3429impl AstNode for StaticDef { 2621impl AstNode for StaticDef {
3430 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2622 fn cast(syntax: SyntaxNode) -> Option<Self> {
3431 match syntax.kind() { 2623 match syntax.kind() {
3432 STATIC_DEF => Some(StaticDef::from_repr(syntax.into_repr())), 2624 STATIC_DEF => Some(StaticDef { syntax }),
3433 _ => None, 2625 _ => None,
3434 } 2626 }
3435 } 2627 }
3436 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2628 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3437} 2629}
3438 2630
3439impl ToOwned for StaticDef {
3440 type Owned = TreeArc<StaticDef>;
3441 fn to_owned(&self) -> TreeArc<StaticDef> { TreeArc::cast(self.syntax.to_owned()) }
3442}
3443
3444 2631
3445impl ast::VisibilityOwner for StaticDef {} 2632impl ast::VisibilityOwner for StaticDef {}
3446impl ast::NameOwner for StaticDef {} 2633impl ast::NameOwner for StaticDef {}
@@ -3449,59 +2636,50 @@ impl ast::AttrsOwner for StaticDef {}
3449impl ast::DocCommentsOwner for StaticDef {} 2636impl ast::DocCommentsOwner for StaticDef {}
3450impl ast::TypeAscriptionOwner for StaticDef {} 2637impl ast::TypeAscriptionOwner for StaticDef {}
3451impl StaticDef { 2638impl StaticDef {
3452 pub fn body(&self) -> Option<&Expr> { 2639 pub fn body(&self) -> Option<Expr> {
3453 super::child_opt(self) 2640 super::child_opt(self)
3454 } 2641 }
3455} 2642}
3456 2643
3457// Stmt 2644// Stmt
3458#[derive(Debug, PartialEq, Eq, Hash)] 2645#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3459#[repr(transparent)]
3460pub struct Stmt { 2646pub struct Stmt {
3461 pub(crate) syntax: SyntaxNode, 2647 pub(crate) syntax: SyntaxNode,
3462} 2648}
3463unsafe impl TransparentNewType for Stmt {
3464 type Repr = rowan::SyntaxNode;
3465}
3466 2649
3467#[derive(Debug, Clone, Copy, PartialEq, Eq)] 2650#[derive(Debug, Clone, PartialEq, Eq)]
3468pub enum StmtKind<'a> { 2651pub enum StmtKind {
3469 ExprStmt(&'a ExprStmt), 2652 ExprStmt(ExprStmt),
3470 LetStmt(&'a LetStmt), 2653 LetStmt(LetStmt),
3471} 2654}
3472impl<'a> From<&'a ExprStmt> for &'a Stmt { 2655impl From<ExprStmt> for Stmt {
3473 fn from(n: &'a ExprStmt) -> &'a Stmt { 2656 fn from(n: ExprStmt) -> Stmt {
3474 Stmt::cast(&n.syntax).unwrap() 2657 Stmt::cast(n.syntax).unwrap()
3475 } 2658 }
3476} 2659}
3477impl<'a> From<&'a LetStmt> for &'a Stmt { 2660impl From<LetStmt> for Stmt {
3478 fn from(n: &'a LetStmt) -> &'a Stmt { 2661 fn from(n: LetStmt) -> Stmt {
3479 Stmt::cast(&n.syntax).unwrap() 2662 Stmt::cast(n.syntax).unwrap()
3480 } 2663 }
3481} 2664}
3482 2665
3483 2666
3484impl AstNode for Stmt { 2667impl AstNode for Stmt {
3485 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2668 fn cast(syntax: SyntaxNode) -> Option<Self> {
3486 match syntax.kind() { 2669 match syntax.kind() {
3487 | EXPR_STMT 2670 | EXPR_STMT
3488 | LET_STMT => Some(Stmt::from_repr(syntax.into_repr())), 2671 | LET_STMT => Some(Stmt { syntax }),
3489 _ => None, 2672 _ => None,
3490 } 2673 }
3491 } 2674 }
3492 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2675 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3493} 2676}
3494 2677
3495impl ToOwned for Stmt {
3496 type Owned = TreeArc<Stmt>;
3497 fn to_owned(&self) -> TreeArc<Stmt> { TreeArc::cast(self.syntax.to_owned()) }
3498}
3499
3500impl Stmt { 2678impl Stmt {
3501 pub fn kind(&self) -> StmtKind { 2679 pub fn kind(&self) -> StmtKind {
3502 match self.syntax.kind() { 2680 match self.syntax.kind() {
3503 EXPR_STMT => StmtKind::ExprStmt(ExprStmt::cast(&self.syntax).unwrap()), 2681 EXPR_STMT => StmtKind::ExprStmt(ExprStmt::cast(self.syntax.clone()).unwrap()),
3504 LET_STMT => StmtKind::LetStmt(LetStmt::cast(&self.syntax).unwrap()), 2682 LET_STMT => StmtKind::LetStmt(LetStmt::cast(self.syntax.clone()).unwrap()),
3505 _ => unreachable!(), 2683 _ => unreachable!(),
3506 } 2684 }
3507 } 2685 }
@@ -3510,30 +2688,21 @@ impl Stmt {
3510impl Stmt {} 2688impl Stmt {}
3511 2689
3512// StructDef 2690// StructDef
3513#[derive(Debug, PartialEq, Eq, Hash)] 2691#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3514#[repr(transparent)]
3515pub struct StructDef { 2692pub struct StructDef {
3516 pub(crate) syntax: SyntaxNode, 2693 pub(crate) syntax: SyntaxNode,
3517} 2694}
3518unsafe impl TransparentNewType for StructDef {
3519 type Repr = rowan::SyntaxNode;
3520}
3521 2695
3522impl AstNode for StructDef { 2696impl AstNode for StructDef {
3523 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2697 fn cast(syntax: SyntaxNode) -> Option<Self> {
3524 match syntax.kind() { 2698 match syntax.kind() {
3525 STRUCT_DEF => Some(StructDef::from_repr(syntax.into_repr())), 2699 STRUCT_DEF => Some(StructDef { syntax }),
3526 _ => None, 2700 _ => None,
3527 } 2701 }
3528 } 2702 }
3529 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2703 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3530} 2704}
3531 2705
3532impl ToOwned for StructDef {
3533 type Owned = TreeArc<StructDef>;
3534 fn to_owned(&self) -> TreeArc<StructDef> { TreeArc::cast(self.syntax.to_owned()) }
3535}
3536
3537 2706
3538impl ast::VisibilityOwner for StructDef {} 2707impl ast::VisibilityOwner for StructDef {}
3539impl ast::NameOwner for StructDef {} 2708impl ast::NameOwner for StructDef {}
@@ -3543,130 +2712,94 @@ impl ast::DocCommentsOwner for StructDef {}
3543impl StructDef {} 2712impl StructDef {}
3544 2713
3545// StructLit 2714// StructLit
3546#[derive(Debug, PartialEq, Eq, Hash)] 2715#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3547#[repr(transparent)]
3548pub struct StructLit { 2716pub struct StructLit {
3549 pub(crate) syntax: SyntaxNode, 2717 pub(crate) syntax: SyntaxNode,
3550} 2718}
3551unsafe impl TransparentNewType for StructLit {
3552 type Repr = rowan::SyntaxNode;
3553}
3554 2719
3555impl AstNode for StructLit { 2720impl AstNode for StructLit {
3556 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2721 fn cast(syntax: SyntaxNode) -> Option<Self> {
3557 match syntax.kind() { 2722 match syntax.kind() {
3558 STRUCT_LIT => Some(StructLit::from_repr(syntax.into_repr())), 2723 STRUCT_LIT => Some(StructLit { syntax }),
3559 _ => None, 2724 _ => None,
3560 } 2725 }
3561 } 2726 }
3562 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2727 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3563} 2728}
3564 2729
3565impl ToOwned for StructLit {
3566 type Owned = TreeArc<StructLit>;
3567 fn to_owned(&self) -> TreeArc<StructLit> { TreeArc::cast(self.syntax.to_owned()) }
3568}
3569
3570 2730
3571impl StructLit { 2731impl StructLit {
3572 pub fn path(&self) -> Option<&Path> { 2732 pub fn path(&self) -> Option<Path> {
3573 super::child_opt(self) 2733 super::child_opt(self)
3574 } 2734 }
3575 2735
3576 pub fn named_field_list(&self) -> Option<&NamedFieldList> { 2736 pub fn named_field_list(&self) -> Option<NamedFieldList> {
3577 super::child_opt(self) 2737 super::child_opt(self)
3578 } 2738 }
3579} 2739}
3580 2740
3581// StructPat 2741// StructPat
3582#[derive(Debug, PartialEq, Eq, Hash)] 2742#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3583#[repr(transparent)]
3584pub struct StructPat { 2743pub struct StructPat {
3585 pub(crate) syntax: SyntaxNode, 2744 pub(crate) syntax: SyntaxNode,
3586} 2745}
3587unsafe impl TransparentNewType for StructPat {
3588 type Repr = rowan::SyntaxNode;
3589}
3590 2746
3591impl AstNode for StructPat { 2747impl AstNode for StructPat {
3592 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2748 fn cast(syntax: SyntaxNode) -> Option<Self> {
3593 match syntax.kind() { 2749 match syntax.kind() {
3594 STRUCT_PAT => Some(StructPat::from_repr(syntax.into_repr())), 2750 STRUCT_PAT => Some(StructPat { syntax }),
3595 _ => None, 2751 _ => None,
3596 } 2752 }
3597 } 2753 }
3598 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2754 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3599} 2755}
3600 2756
3601impl ToOwned for StructPat {
3602 type Owned = TreeArc<StructPat>;
3603 fn to_owned(&self) -> TreeArc<StructPat> { TreeArc::cast(self.syntax.to_owned()) }
3604}
3605
3606 2757
3607impl StructPat { 2758impl StructPat {
3608 pub fn field_pat_list(&self) -> Option<&FieldPatList> { 2759 pub fn field_pat_list(&self) -> Option<FieldPatList> {
3609 super::child_opt(self) 2760 super::child_opt(self)
3610 } 2761 }
3611 2762
3612 pub fn path(&self) -> Option<&Path> { 2763 pub fn path(&self) -> Option<Path> {
3613 super::child_opt(self) 2764 super::child_opt(self)
3614 } 2765 }
3615} 2766}
3616 2767
3617// TokenTree 2768// TokenTree
3618#[derive(Debug, PartialEq, Eq, Hash)] 2769#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3619#[repr(transparent)]
3620pub struct TokenTree { 2770pub struct TokenTree {
3621 pub(crate) syntax: SyntaxNode, 2771 pub(crate) syntax: SyntaxNode,
3622} 2772}
3623unsafe impl TransparentNewType for TokenTree {
3624 type Repr = rowan::SyntaxNode;
3625}
3626 2773
3627impl AstNode for TokenTree { 2774impl AstNode for TokenTree {
3628 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2775 fn cast(syntax: SyntaxNode) -> Option<Self> {
3629 match syntax.kind() { 2776 match syntax.kind() {
3630 TOKEN_TREE => Some(TokenTree::from_repr(syntax.into_repr())), 2777 TOKEN_TREE => Some(TokenTree { syntax }),
3631 _ => None, 2778 _ => None,
3632 } 2779 }
3633 } 2780 }
3634 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2781 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3635} 2782}
3636 2783
3637impl ToOwned for TokenTree {
3638 type Owned = TreeArc<TokenTree>;
3639 fn to_owned(&self) -> TreeArc<TokenTree> { TreeArc::cast(self.syntax.to_owned()) }
3640}
3641
3642 2784
3643impl TokenTree {} 2785impl TokenTree {}
3644 2786
3645// TraitDef 2787// TraitDef
3646#[derive(Debug, PartialEq, Eq, Hash)] 2788#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3647#[repr(transparent)]
3648pub struct TraitDef { 2789pub struct TraitDef {
3649 pub(crate) syntax: SyntaxNode, 2790 pub(crate) syntax: SyntaxNode,
3650} 2791}
3651unsafe impl TransparentNewType for TraitDef {
3652 type Repr = rowan::SyntaxNode;
3653}
3654 2792
3655impl AstNode for TraitDef { 2793impl AstNode for TraitDef {
3656 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2794 fn cast(syntax: SyntaxNode) -> Option<Self> {
3657 match syntax.kind() { 2795 match syntax.kind() {
3658 TRAIT_DEF => Some(TraitDef::from_repr(syntax.into_repr())), 2796 TRAIT_DEF => Some(TraitDef { syntax }),
3659 _ => None, 2797 _ => None,
3660 } 2798 }
3661 } 2799 }
3662 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2800 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3663} 2801}
3664 2802
3665impl ToOwned for TraitDef {
3666 type Owned = TreeArc<TraitDef>;
3667 fn to_owned(&self) -> TreeArc<TraitDef> { TreeArc::cast(self.syntax.to_owned()) }
3668}
3669
3670 2803
3671impl ast::VisibilityOwner for TraitDef {} 2804impl ast::VisibilityOwner for TraitDef {}
3672impl ast::NameOwner for TraitDef {} 2805impl ast::NameOwner for TraitDef {}
@@ -3675,229 +2808,166 @@ impl ast::DocCommentsOwner for TraitDef {}
3675impl ast::TypeParamsOwner for TraitDef {} 2808impl ast::TypeParamsOwner for TraitDef {}
3676impl ast::TypeBoundsOwner for TraitDef {} 2809impl ast::TypeBoundsOwner for TraitDef {}
3677impl TraitDef { 2810impl TraitDef {
3678 pub fn item_list(&self) -> Option<&ItemList> { 2811 pub fn item_list(&self) -> Option<ItemList> {
3679 super::child_opt(self) 2812 super::child_opt(self)
3680 } 2813 }
3681} 2814}
3682 2815
3683// TryBlockExpr 2816// TryBlockExpr
3684#[derive(Debug, PartialEq, Eq, Hash)] 2817#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3685#[repr(transparent)]
3686pub struct TryBlockExpr { 2818pub struct TryBlockExpr {
3687 pub(crate) syntax: SyntaxNode, 2819 pub(crate) syntax: SyntaxNode,
3688} 2820}
3689unsafe impl TransparentNewType for TryBlockExpr {
3690 type Repr = rowan::SyntaxNode;
3691}
3692 2821
3693impl AstNode for TryBlockExpr { 2822impl AstNode for TryBlockExpr {
3694 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2823 fn cast(syntax: SyntaxNode) -> Option<Self> {
3695 match syntax.kind() { 2824 match syntax.kind() {
3696 TRY_BLOCK_EXPR => Some(TryBlockExpr::from_repr(syntax.into_repr())), 2825 TRY_BLOCK_EXPR => Some(TryBlockExpr { syntax }),
3697 _ => None, 2826 _ => None,
3698 } 2827 }
3699 } 2828 }
3700 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2829 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3701} 2830}
3702 2831
3703impl ToOwned for TryBlockExpr {
3704 type Owned = TreeArc<TryBlockExpr>;
3705 fn to_owned(&self) -> TreeArc<TryBlockExpr> { TreeArc::cast(self.syntax.to_owned()) }
3706}
3707
3708 2832
3709impl ast::TryBlockBodyOwner for TryBlockExpr {} 2833impl ast::TryBlockBodyOwner for TryBlockExpr {}
3710impl TryBlockExpr {} 2834impl TryBlockExpr {}
3711 2835
3712// TryExpr 2836// TryExpr
3713#[derive(Debug, PartialEq, Eq, Hash)] 2837#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3714#[repr(transparent)]
3715pub struct TryExpr { 2838pub struct TryExpr {
3716 pub(crate) syntax: SyntaxNode, 2839 pub(crate) syntax: SyntaxNode,
3717} 2840}
3718unsafe impl TransparentNewType for TryExpr {
3719 type Repr = rowan::SyntaxNode;
3720}
3721 2841
3722impl AstNode for TryExpr { 2842impl AstNode for TryExpr {
3723 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2843 fn cast(syntax: SyntaxNode) -> Option<Self> {
3724 match syntax.kind() { 2844 match syntax.kind() {
3725 TRY_EXPR => Some(TryExpr::from_repr(syntax.into_repr())), 2845 TRY_EXPR => Some(TryExpr { syntax }),
3726 _ => None, 2846 _ => None,
3727 } 2847 }
3728 } 2848 }
3729 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2849 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3730} 2850}
3731 2851
3732impl ToOwned for TryExpr {
3733 type Owned = TreeArc<TryExpr>;
3734 fn to_owned(&self) -> TreeArc<TryExpr> { TreeArc::cast(self.syntax.to_owned()) }
3735}
3736
3737 2852
3738impl TryExpr { 2853impl TryExpr {
3739 pub fn expr(&self) -> Option<&Expr> { 2854 pub fn expr(&self) -> Option<Expr> {
3740 super::child_opt(self) 2855 super::child_opt(self)
3741 } 2856 }
3742} 2857}
3743 2858
3744// TupleExpr 2859// TupleExpr
3745#[derive(Debug, PartialEq, Eq, Hash)] 2860#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3746#[repr(transparent)]
3747pub struct TupleExpr { 2861pub struct TupleExpr {
3748 pub(crate) syntax: SyntaxNode, 2862 pub(crate) syntax: SyntaxNode,
3749} 2863}
3750unsafe impl TransparentNewType for TupleExpr {
3751 type Repr = rowan::SyntaxNode;
3752}
3753 2864
3754impl AstNode for TupleExpr { 2865impl AstNode for TupleExpr {
3755 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2866 fn cast(syntax: SyntaxNode) -> Option<Self> {
3756 match syntax.kind() { 2867 match syntax.kind() {
3757 TUPLE_EXPR => Some(TupleExpr::from_repr(syntax.into_repr())), 2868 TUPLE_EXPR => Some(TupleExpr { syntax }),
3758 _ => None, 2869 _ => None,
3759 } 2870 }
3760 } 2871 }
3761 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2872 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3762} 2873}
3763 2874
3764impl ToOwned for TupleExpr {
3765 type Owned = TreeArc<TupleExpr>;
3766 fn to_owned(&self) -> TreeArc<TupleExpr> { TreeArc::cast(self.syntax.to_owned()) }
3767}
3768
3769 2875
3770impl TupleExpr { 2876impl TupleExpr {
3771 pub fn exprs(&self) -> impl Iterator<Item = &Expr> { 2877 pub fn exprs(&self) -> impl Iterator<Item = Expr> {
3772 super::children(self) 2878 super::children(self)
3773 } 2879 }
3774} 2880}
3775 2881
3776// TuplePat 2882// TuplePat
3777#[derive(Debug, PartialEq, Eq, Hash)] 2883#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3778#[repr(transparent)]
3779pub struct TuplePat { 2884pub struct TuplePat {
3780 pub(crate) syntax: SyntaxNode, 2885 pub(crate) syntax: SyntaxNode,
3781} 2886}
3782unsafe impl TransparentNewType for TuplePat {
3783 type Repr = rowan::SyntaxNode;
3784}
3785 2887
3786impl AstNode for TuplePat { 2888impl AstNode for TuplePat {
3787 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2889 fn cast(syntax: SyntaxNode) -> Option<Self> {
3788 match syntax.kind() { 2890 match syntax.kind() {
3789 TUPLE_PAT => Some(TuplePat::from_repr(syntax.into_repr())), 2891 TUPLE_PAT => Some(TuplePat { syntax }),
3790 _ => None, 2892 _ => None,
3791 } 2893 }
3792 } 2894 }
3793 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2895 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3794} 2896}
3795 2897
3796impl ToOwned for TuplePat {
3797 type Owned = TreeArc<TuplePat>;
3798 fn to_owned(&self) -> TreeArc<TuplePat> { TreeArc::cast(self.syntax.to_owned()) }
3799}
3800
3801 2898
3802impl TuplePat { 2899impl TuplePat {
3803 pub fn args(&self) -> impl Iterator<Item = &Pat> { 2900 pub fn args(&self) -> impl Iterator<Item = Pat> {
3804 super::children(self) 2901 super::children(self)
3805 } 2902 }
3806} 2903}
3807 2904
3808// TupleStructPat 2905// TupleStructPat
3809#[derive(Debug, PartialEq, Eq, Hash)] 2906#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3810#[repr(transparent)]
3811pub struct TupleStructPat { 2907pub struct TupleStructPat {
3812 pub(crate) syntax: SyntaxNode, 2908 pub(crate) syntax: SyntaxNode,
3813} 2909}
3814unsafe impl TransparentNewType for TupleStructPat {
3815 type Repr = rowan::SyntaxNode;
3816}
3817 2910
3818impl AstNode for TupleStructPat { 2911impl AstNode for TupleStructPat {
3819 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2912 fn cast(syntax: SyntaxNode) -> Option<Self> {
3820 match syntax.kind() { 2913 match syntax.kind() {
3821 TUPLE_STRUCT_PAT => Some(TupleStructPat::from_repr(syntax.into_repr())), 2914 TUPLE_STRUCT_PAT => Some(TupleStructPat { syntax }),
3822 _ => None, 2915 _ => None,
3823 } 2916 }
3824 } 2917 }
3825 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2918 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3826} 2919}
3827 2920
3828impl ToOwned for TupleStructPat {
3829 type Owned = TreeArc<TupleStructPat>;
3830 fn to_owned(&self) -> TreeArc<TupleStructPat> { TreeArc::cast(self.syntax.to_owned()) }
3831}
3832
3833 2921
3834impl TupleStructPat { 2922impl TupleStructPat {
3835 pub fn args(&self) -> impl Iterator<Item = &Pat> { 2923 pub fn args(&self) -> impl Iterator<Item = Pat> {
3836 super::children(self) 2924 super::children(self)
3837 } 2925 }
3838 2926
3839 pub fn path(&self) -> Option<&Path> { 2927 pub fn path(&self) -> Option<Path> {
3840 super::child_opt(self) 2928 super::child_opt(self)
3841 } 2929 }
3842} 2930}
3843 2931
3844// TupleType 2932// TupleType
3845#[derive(Debug, PartialEq, Eq, Hash)] 2933#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3846#[repr(transparent)]
3847pub struct TupleType { 2934pub struct TupleType {
3848 pub(crate) syntax: SyntaxNode, 2935 pub(crate) syntax: SyntaxNode,
3849} 2936}
3850unsafe impl TransparentNewType for TupleType {
3851 type Repr = rowan::SyntaxNode;
3852}
3853 2937
3854impl AstNode for TupleType { 2938impl AstNode for TupleType {
3855 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2939 fn cast(syntax: SyntaxNode) -> Option<Self> {
3856 match syntax.kind() { 2940 match syntax.kind() {
3857 TUPLE_TYPE => Some(TupleType::from_repr(syntax.into_repr())), 2941 TUPLE_TYPE => Some(TupleType { syntax }),
3858 _ => None, 2942 _ => None,
3859 } 2943 }
3860 } 2944 }
3861 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2945 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3862} 2946}
3863 2947
3864impl ToOwned for TupleType {
3865 type Owned = TreeArc<TupleType>;
3866 fn to_owned(&self) -> TreeArc<TupleType> { TreeArc::cast(self.syntax.to_owned()) }
3867}
3868
3869 2948
3870impl TupleType { 2949impl TupleType {
3871 pub fn fields(&self) -> impl Iterator<Item = &TypeRef> { 2950 pub fn fields(&self) -> impl Iterator<Item = TypeRef> {
3872 super::children(self) 2951 super::children(self)
3873 } 2952 }
3874} 2953}
3875 2954
3876// TypeAliasDef 2955// TypeAliasDef
3877#[derive(Debug, PartialEq, Eq, Hash)] 2956#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3878#[repr(transparent)]
3879pub struct TypeAliasDef { 2957pub struct TypeAliasDef {
3880 pub(crate) syntax: SyntaxNode, 2958 pub(crate) syntax: SyntaxNode,
3881} 2959}
3882unsafe impl TransparentNewType for TypeAliasDef {
3883 type Repr = rowan::SyntaxNode;
3884}
3885 2960
3886impl AstNode for TypeAliasDef { 2961impl AstNode for TypeAliasDef {
3887 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2962 fn cast(syntax: SyntaxNode) -> Option<Self> {
3888 match syntax.kind() { 2963 match syntax.kind() {
3889 TYPE_ALIAS_DEF => Some(TypeAliasDef::from_repr(syntax.into_repr())), 2964 TYPE_ALIAS_DEF => Some(TypeAliasDef { syntax }),
3890 _ => None, 2965 _ => None,
3891 } 2966 }
3892 } 2967 }
3893 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2968 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3894} 2969}
3895 2970
3896impl ToOwned for TypeAliasDef {
3897 type Owned = TreeArc<TypeAliasDef>;
3898 fn to_owned(&self) -> TreeArc<TypeAliasDef> { TreeArc::cast(self.syntax.to_owned()) }
3899}
3900
3901 2971
3902impl ast::VisibilityOwner for TypeAliasDef {} 2972impl ast::VisibilityOwner for TypeAliasDef {}
3903impl ast::NameOwner for TypeAliasDef {} 2973impl ast::NameOwner for TypeAliasDef {}
@@ -3906,172 +2976,127 @@ impl ast::AttrsOwner for TypeAliasDef {}
3906impl ast::DocCommentsOwner for TypeAliasDef {} 2976impl ast::DocCommentsOwner for TypeAliasDef {}
3907impl ast::TypeBoundsOwner for TypeAliasDef {} 2977impl ast::TypeBoundsOwner for TypeAliasDef {}
3908impl TypeAliasDef { 2978impl TypeAliasDef {
3909 pub fn type_ref(&self) -> Option<&TypeRef> { 2979 pub fn type_ref(&self) -> Option<TypeRef> {
3910 super::child_opt(self) 2980 super::child_opt(self)
3911 } 2981 }
3912} 2982}
3913 2983
3914// TypeArg 2984// TypeArg
3915#[derive(Debug, PartialEq, Eq, Hash)] 2985#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3916#[repr(transparent)]
3917pub struct TypeArg { 2986pub struct TypeArg {
3918 pub(crate) syntax: SyntaxNode, 2987 pub(crate) syntax: SyntaxNode,
3919} 2988}
3920unsafe impl TransparentNewType for TypeArg {
3921 type Repr = rowan::SyntaxNode;
3922}
3923 2989
3924impl AstNode for TypeArg { 2990impl AstNode for TypeArg {
3925 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 2991 fn cast(syntax: SyntaxNode) -> Option<Self> {
3926 match syntax.kind() { 2992 match syntax.kind() {
3927 TYPE_ARG => Some(TypeArg::from_repr(syntax.into_repr())), 2993 TYPE_ARG => Some(TypeArg { syntax }),
3928 _ => None, 2994 _ => None,
3929 } 2995 }
3930 } 2996 }
3931 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2997 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3932} 2998}
3933 2999
3934impl ToOwned for TypeArg {
3935 type Owned = TreeArc<TypeArg>;
3936 fn to_owned(&self) -> TreeArc<TypeArg> { TreeArc::cast(self.syntax.to_owned()) }
3937}
3938
3939 3000
3940impl TypeArg { 3001impl TypeArg {
3941 pub fn type_ref(&self) -> Option<&TypeRef> { 3002 pub fn type_ref(&self) -> Option<TypeRef> {
3942 super::child_opt(self) 3003 super::child_opt(self)
3943 } 3004 }
3944} 3005}
3945 3006
3946// TypeArgList 3007// TypeArgList
3947#[derive(Debug, PartialEq, Eq, Hash)] 3008#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3948#[repr(transparent)]
3949pub struct TypeArgList { 3009pub struct TypeArgList {
3950 pub(crate) syntax: SyntaxNode, 3010 pub(crate) syntax: SyntaxNode,
3951} 3011}
3952unsafe impl TransparentNewType for TypeArgList {
3953 type Repr = rowan::SyntaxNode;
3954}
3955 3012
3956impl AstNode for TypeArgList { 3013impl AstNode for TypeArgList {
3957 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3014 fn cast(syntax: SyntaxNode) -> Option<Self> {
3958 match syntax.kind() { 3015 match syntax.kind() {
3959 TYPE_ARG_LIST => Some(TypeArgList::from_repr(syntax.into_repr())), 3016 TYPE_ARG_LIST => Some(TypeArgList { syntax }),
3960 _ => None, 3017 _ => None,
3961 } 3018 }
3962 } 3019 }
3963 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3020 fn syntax(&self) -> &SyntaxNode { &self.syntax }
3964} 3021}
3965 3022
3966impl ToOwned for TypeArgList {
3967 type Owned = TreeArc<TypeArgList>;
3968 fn to_owned(&self) -> TreeArc<TypeArgList> { TreeArc::cast(self.syntax.to_owned()) }
3969}
3970
3971 3023
3972impl TypeArgList { 3024impl TypeArgList {
3973 pub fn type_args(&self) -> impl Iterator<Item = &TypeArg> { 3025 pub fn type_args(&self) -> impl Iterator<Item = TypeArg> {
3974 super::children(self) 3026 super::children(self)
3975 } 3027 }
3976 3028
3977 pub fn lifetime_args(&self) -> impl Iterator<Item = &LifetimeArg> { 3029 pub fn lifetime_args(&self) -> impl Iterator<Item = LifetimeArg> {
3978 super::children(self) 3030 super::children(self)
3979 } 3031 }
3980 3032
3981 pub fn assoc_type_args(&self) -> impl Iterator<Item = &AssocTypeArg> { 3033 pub fn assoc_type_args(&self) -> impl Iterator<Item = AssocTypeArg> {
3982 super::children(self) 3034 super::children(self)
3983 } 3035 }
3984} 3036}
3985 3037
3986// TypeBound 3038// TypeBound
3987#[derive(Debug, PartialEq, Eq, Hash)] 3039#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3988#[repr(transparent)]
3989pub struct TypeBound { 3040pub struct TypeBound {
3990 pub(crate) syntax: SyntaxNode, 3041 pub(crate) syntax: SyntaxNode,
3991} 3042}
3992unsafe impl TransparentNewType for TypeBound {
3993 type Repr = rowan::SyntaxNode;
3994}
3995 3043
3996impl AstNode for TypeBound { 3044impl AstNode for TypeBound {
3997 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3045 fn cast(syntax: SyntaxNode) -> Option<Self> {
3998 match syntax.kind() { 3046 match syntax.kind() {
3999 TYPE_BOUND => Some(TypeBound::from_repr(syntax.into_repr())), 3047 TYPE_BOUND => Some(TypeBound { syntax }),
4000 _ => None, 3048 _ => None,
4001 } 3049 }
4002 } 3050 }
4003 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3051 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4004} 3052}
4005 3053
4006impl ToOwned for TypeBound {
4007 type Owned = TreeArc<TypeBound>;
4008 fn to_owned(&self) -> TreeArc<TypeBound> { TreeArc::cast(self.syntax.to_owned()) }
4009}
4010
4011 3054
4012impl TypeBound { 3055impl TypeBound {
4013 pub fn type_ref(&self) -> Option<&TypeRef> { 3056 pub fn type_ref(&self) -> Option<TypeRef> {
4014 super::child_opt(self) 3057 super::child_opt(self)
4015 } 3058 }
4016} 3059}
4017 3060
4018// TypeBoundList 3061// TypeBoundList
4019#[derive(Debug, PartialEq, Eq, Hash)] 3062#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4020#[repr(transparent)]
4021pub struct TypeBoundList { 3063pub struct TypeBoundList {
4022 pub(crate) syntax: SyntaxNode, 3064 pub(crate) syntax: SyntaxNode,
4023} 3065}
4024unsafe impl TransparentNewType for TypeBoundList {
4025 type Repr = rowan::SyntaxNode;
4026}
4027 3066
4028impl AstNode for TypeBoundList { 3067impl AstNode for TypeBoundList {
4029 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3068 fn cast(syntax: SyntaxNode) -> Option<Self> {
4030 match syntax.kind() { 3069 match syntax.kind() {
4031 TYPE_BOUND_LIST => Some(TypeBoundList::from_repr(syntax.into_repr())), 3070 TYPE_BOUND_LIST => Some(TypeBoundList { syntax }),
4032 _ => None, 3071 _ => None,
4033 } 3072 }
4034 } 3073 }
4035 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3074 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4036} 3075}
4037 3076
4038impl ToOwned for TypeBoundList {
4039 type Owned = TreeArc<TypeBoundList>;
4040 fn to_owned(&self) -> TreeArc<TypeBoundList> { TreeArc::cast(self.syntax.to_owned()) }
4041}
4042
4043 3077
4044impl TypeBoundList { 3078impl TypeBoundList {
4045 pub fn bounds(&self) -> impl Iterator<Item = &TypeBound> { 3079 pub fn bounds(&self) -> impl Iterator<Item = TypeBound> {
4046 super::children(self) 3080 super::children(self)
4047 } 3081 }
4048} 3082}
4049 3083
4050// TypeParam 3084// TypeParam
4051#[derive(Debug, PartialEq, Eq, Hash)] 3085#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4052#[repr(transparent)]
4053pub struct TypeParam { 3086pub struct TypeParam {
4054 pub(crate) syntax: SyntaxNode, 3087 pub(crate) syntax: SyntaxNode,
4055} 3088}
4056unsafe impl TransparentNewType for TypeParam {
4057 type Repr = rowan::SyntaxNode;
4058}
4059 3089
4060impl AstNode for TypeParam { 3090impl AstNode for TypeParam {
4061 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3091 fn cast(syntax: SyntaxNode) -> Option<Self> {
4062 match syntax.kind() { 3092 match syntax.kind() {
4063 TYPE_PARAM => Some(TypeParam::from_repr(syntax.into_repr())), 3093 TYPE_PARAM => Some(TypeParam { syntax }),
4064 _ => None, 3094 _ => None,
4065 } 3095 }
4066 } 3096 }
4067 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3097 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4068} 3098}
4069 3099
4070impl ToOwned for TypeParam {
4071 type Owned = TreeArc<TypeParam>;
4072 fn to_owned(&self) -> TreeArc<TypeParam> { TreeArc::cast(self.syntax.to_owned()) }
4073}
4074
4075 3100
4076impl ast::NameOwner for TypeParam {} 3101impl ast::NameOwner for TypeParam {}
4077impl ast::AttrsOwner for TypeParam {} 3102impl ast::AttrsOwner for TypeParam {}
@@ -4080,136 +3105,123 @@ impl ast::DefaultTypeParamOwner for TypeParam {}
4080impl TypeParam {} 3105impl TypeParam {}
4081 3106
4082// TypeParamList 3107// TypeParamList
4083#[derive(Debug, PartialEq, Eq, Hash)] 3108#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4084#[repr(transparent)]
4085pub struct TypeParamList { 3109pub struct TypeParamList {
4086 pub(crate) syntax: SyntaxNode, 3110 pub(crate) syntax: SyntaxNode,
4087} 3111}
4088unsafe impl TransparentNewType for TypeParamList {
4089 type Repr = rowan::SyntaxNode;
4090}
4091 3112
4092impl AstNode for TypeParamList { 3113impl AstNode for TypeParamList {
4093 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3114 fn cast(syntax: SyntaxNode) -> Option<Self> {
4094 match syntax.kind() { 3115 match syntax.kind() {
4095 TYPE_PARAM_LIST => Some(TypeParamList::from_repr(syntax.into_repr())), 3116 TYPE_PARAM_LIST => Some(TypeParamList { syntax }),
4096 _ => None, 3117 _ => None,
4097 } 3118 }
4098 } 3119 }
4099 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3120 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4100} 3121}
4101 3122
4102impl ToOwned for TypeParamList {
4103 type Owned = TreeArc<TypeParamList>;
4104 fn to_owned(&self) -> TreeArc<TypeParamList> { TreeArc::cast(self.syntax.to_owned()) }
4105}
4106
4107 3123
4108impl TypeParamList { 3124impl TypeParamList {
4109 pub fn type_params(&self) -> impl Iterator<Item = &TypeParam> { 3125 pub fn type_params(&self) -> impl Iterator<Item = TypeParam> {
4110 super::children(self) 3126 super::children(self)
4111 } 3127 }
4112 3128
4113 pub fn lifetime_params(&self) -> impl Iterator<Item = &LifetimeParam> { 3129 pub fn lifetime_params(&self) -> impl Iterator<Item = LifetimeParam> {
4114 super::children(self) 3130 super::children(self)
4115 } 3131 }
4116} 3132}
4117 3133
4118// TypeRef 3134// TypeRef
4119#[derive(Debug, PartialEq, Eq, Hash)] 3135#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4120#[repr(transparent)]
4121pub struct TypeRef { 3136pub struct TypeRef {
4122 pub(crate) syntax: SyntaxNode, 3137 pub(crate) syntax: SyntaxNode,
4123} 3138}
4124unsafe impl TransparentNewType for TypeRef {
4125 type Repr = rowan::SyntaxNode;
4126}
4127 3139
4128#[derive(Debug, Clone, Copy, PartialEq, Eq)] 3140#[derive(Debug, Clone, PartialEq, Eq)]
4129pub enum TypeRefKind<'a> { 3141pub enum TypeRefKind {
4130 ParenType(&'a ParenType), 3142 ParenType(ParenType),
4131 TupleType(&'a TupleType), 3143 TupleType(TupleType),
4132 NeverType(&'a NeverType), 3144 NeverType(NeverType),
4133 PathType(&'a PathType), 3145 PathType(PathType),
4134 PointerType(&'a PointerType), 3146 PointerType(PointerType),
4135 ArrayType(&'a ArrayType), 3147 ArrayType(ArrayType),
4136 SliceType(&'a SliceType), 3148 SliceType(SliceType),
4137 ReferenceType(&'a ReferenceType), 3149 ReferenceType(ReferenceType),
4138 PlaceholderType(&'a PlaceholderType), 3150 PlaceholderType(PlaceholderType),
4139 FnPointerType(&'a FnPointerType), 3151 FnPointerType(FnPointerType),
4140 ForType(&'a ForType), 3152 ForType(ForType),
4141 ImplTraitType(&'a ImplTraitType), 3153 ImplTraitType(ImplTraitType),
4142 DynTraitType(&'a DynTraitType), 3154 DynTraitType(DynTraitType),
4143} 3155}
4144impl<'a> From<&'a ParenType> for &'a TypeRef { 3156impl From<ParenType> for TypeRef {
4145 fn from(n: &'a ParenType) -> &'a TypeRef { 3157 fn from(n: ParenType) -> TypeRef {
4146 TypeRef::cast(&n.syntax).unwrap() 3158 TypeRef::cast(n.syntax).unwrap()
4147 } 3159 }
4148} 3160}
4149impl<'a> From<&'a TupleType> for &'a TypeRef { 3161impl From<TupleType> for TypeRef {
4150 fn from(n: &'a TupleType) -> &'a TypeRef { 3162 fn from(n: TupleType) -> TypeRef {
4151 TypeRef::cast(&n.syntax).unwrap() 3163 TypeRef::cast(n.syntax).unwrap()
4152 } 3164 }
4153} 3165}
4154impl<'a> From<&'a NeverType> for &'a TypeRef { 3166impl From<NeverType> for TypeRef {
4155 fn from(n: &'a NeverType) -> &'a TypeRef { 3167 fn from(n: NeverType) -> TypeRef {
4156 TypeRef::cast(&n.syntax).unwrap() 3168 TypeRef::cast(n.syntax).unwrap()
4157 } 3169 }
4158} 3170}
4159impl<'a> From<&'a PathType> for &'a TypeRef { 3171impl From<PathType> for TypeRef {
4160 fn from(n: &'a PathType) -> &'a TypeRef { 3172 fn from(n: PathType) -> TypeRef {
4161 TypeRef::cast(&n.syntax).unwrap() 3173 TypeRef::cast(n.syntax).unwrap()
4162 } 3174 }
4163} 3175}
4164impl<'a> From<&'a PointerType> for &'a TypeRef { 3176impl From<PointerType> for TypeRef {
4165 fn from(n: &'a PointerType) -> &'a TypeRef { 3177 fn from(n: PointerType) -> TypeRef {
4166 TypeRef::cast(&n.syntax).unwrap() 3178 TypeRef::cast(n.syntax).unwrap()
4167 } 3179 }
4168} 3180}
4169impl<'a> From<&'a ArrayType> for &'a TypeRef { 3181impl From<ArrayType> for TypeRef {
4170 fn from(n: &'a ArrayType) -> &'a TypeRef { 3182 fn from(n: ArrayType) -> TypeRef {
4171 TypeRef::cast(&n.syntax).unwrap() 3183 TypeRef::cast(n.syntax).unwrap()
4172 } 3184 }
4173} 3185}
4174impl<'a> From<&'a SliceType> for &'a TypeRef { 3186impl From<SliceType> for TypeRef {
4175 fn from(n: &'a SliceType) -> &'a TypeRef { 3187 fn from(n: SliceType) -> TypeRef {
4176 TypeRef::cast(&n.syntax).unwrap() 3188 TypeRef::cast(n.syntax).unwrap()
4177 } 3189 }
4178} 3190}
4179impl<'a> From<&'a ReferenceType> for &'a TypeRef { 3191impl From<ReferenceType> for TypeRef {
4180 fn from(n: &'a ReferenceType) -> &'a TypeRef { 3192 fn from(n: ReferenceType) -> TypeRef {
4181 TypeRef::cast(&n.syntax).unwrap() 3193 TypeRef::cast(n.syntax).unwrap()
4182 } 3194 }
4183} 3195}
4184impl<'a> From<&'a PlaceholderType> for &'a TypeRef { 3196impl From<PlaceholderType> for TypeRef {
4185 fn from(n: &'a PlaceholderType) -> &'a TypeRef { 3197 fn from(n: PlaceholderType) -> TypeRef {
4186 TypeRef::cast(&n.syntax).unwrap() 3198 TypeRef::cast(n.syntax).unwrap()
4187 } 3199 }
4188} 3200}
4189impl<'a> From<&'a FnPointerType> for &'a TypeRef { 3201impl From<FnPointerType> for TypeRef {
4190 fn from(n: &'a FnPointerType) -> &'a TypeRef { 3202 fn from(n: FnPointerType) -> TypeRef {
4191 TypeRef::cast(&n.syntax).unwrap() 3203 TypeRef::cast(n.syntax).unwrap()
4192 } 3204 }
4193} 3205}
4194impl<'a> From<&'a ForType> for &'a TypeRef { 3206impl From<ForType> for TypeRef {
4195 fn from(n: &'a ForType) -> &'a TypeRef { 3207 fn from(n: ForType) -> TypeRef {
4196 TypeRef::cast(&n.syntax).unwrap() 3208 TypeRef::cast(n.syntax).unwrap()
4197 } 3209 }
4198} 3210}
4199impl<'a> From<&'a ImplTraitType> for &'a TypeRef { 3211impl From<ImplTraitType> for TypeRef {
4200 fn from(n: &'a ImplTraitType) -> &'a TypeRef { 3212 fn from(n: ImplTraitType) -> TypeRef {
4201 TypeRef::cast(&n.syntax).unwrap() 3213 TypeRef::cast(n.syntax).unwrap()
4202 } 3214 }
4203} 3215}
4204impl<'a> From<&'a DynTraitType> for &'a TypeRef { 3216impl From<DynTraitType> for TypeRef {
4205 fn from(n: &'a DynTraitType) -> &'a TypeRef { 3217 fn from(n: DynTraitType) -> TypeRef {
4206 TypeRef::cast(&n.syntax).unwrap() 3218 TypeRef::cast(n.syntax).unwrap()
4207 } 3219 }
4208} 3220}
4209 3221
4210 3222
4211impl AstNode for TypeRef { 3223impl AstNode for TypeRef {
4212 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3224 fn cast(syntax: SyntaxNode) -> Option<Self> {
4213 match syntax.kind() { 3225 match syntax.kind() {
4214 | PAREN_TYPE 3226 | PAREN_TYPE
4215 | TUPLE_TYPE 3227 | TUPLE_TYPE
@@ -4223,34 +3235,29 @@ impl AstNode for TypeRef {
4223 | FN_POINTER_TYPE 3235 | FN_POINTER_TYPE
4224 | FOR_TYPE 3236 | FOR_TYPE
4225 | IMPL_TRAIT_TYPE 3237 | IMPL_TRAIT_TYPE
4226 | DYN_TRAIT_TYPE => Some(TypeRef::from_repr(syntax.into_repr())), 3238 | DYN_TRAIT_TYPE => Some(TypeRef { syntax }),
4227 _ => None, 3239 _ => None,
4228 } 3240 }
4229 } 3241 }
4230 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3242 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4231} 3243}
4232 3244
4233impl ToOwned for TypeRef {
4234 type Owned = TreeArc<TypeRef>;
4235 fn to_owned(&self) -> TreeArc<TypeRef> { TreeArc::cast(self.syntax.to_owned()) }
4236}
4237
4238impl TypeRef { 3245impl TypeRef {
4239 pub fn kind(&self) -> TypeRefKind { 3246 pub fn kind(&self) -> TypeRefKind {
4240 match self.syntax.kind() { 3247 match self.syntax.kind() {
4241 PAREN_TYPE => TypeRefKind::ParenType(ParenType::cast(&self.syntax).unwrap()), 3248 PAREN_TYPE => TypeRefKind::ParenType(ParenType::cast(self.syntax.clone()).unwrap()),
4242 TUPLE_TYPE => TypeRefKind::TupleType(TupleType::cast(&self.syntax).unwrap()), 3249 TUPLE_TYPE => TypeRefKind::TupleType(TupleType::cast(self.syntax.clone()).unwrap()),
4243 NEVER_TYPE => TypeRefKind::NeverType(NeverType::cast(&self.syntax).unwrap()), 3250 NEVER_TYPE => TypeRefKind::NeverType(NeverType::cast(self.syntax.clone()).unwrap()),
4244 PATH_TYPE => TypeRefKind::PathType(PathType::cast(&self.syntax).unwrap()), 3251 PATH_TYPE => TypeRefKind::PathType(PathType::cast(self.syntax.clone()).unwrap()),
4245 POINTER_TYPE => TypeRefKind::PointerType(PointerType::cast(&self.syntax).unwrap()), 3252 POINTER_TYPE => TypeRefKind::PointerType(PointerType::cast(self.syntax.clone()).unwrap()),
4246 ARRAY_TYPE => TypeRefKind::ArrayType(ArrayType::cast(&self.syntax).unwrap()), 3253 ARRAY_TYPE => TypeRefKind::ArrayType(ArrayType::cast(self.syntax.clone()).unwrap()),
4247 SLICE_TYPE => TypeRefKind::SliceType(SliceType::cast(&self.syntax).unwrap()), 3254 SLICE_TYPE => TypeRefKind::SliceType(SliceType::cast(self.syntax.clone()).unwrap()),
4248 REFERENCE_TYPE => TypeRefKind::ReferenceType(ReferenceType::cast(&self.syntax).unwrap()), 3255 REFERENCE_TYPE => TypeRefKind::ReferenceType(ReferenceType::cast(self.syntax.clone()).unwrap()),
4249 PLACEHOLDER_TYPE => TypeRefKind::PlaceholderType(PlaceholderType::cast(&self.syntax).unwrap()), 3256 PLACEHOLDER_TYPE => TypeRefKind::PlaceholderType(PlaceholderType::cast(self.syntax.clone()).unwrap()),
4250 FN_POINTER_TYPE => TypeRefKind::FnPointerType(FnPointerType::cast(&self.syntax).unwrap()), 3257 FN_POINTER_TYPE => TypeRefKind::FnPointerType(FnPointerType::cast(self.syntax.clone()).unwrap()),
4251 FOR_TYPE => TypeRefKind::ForType(ForType::cast(&self.syntax).unwrap()), 3258 FOR_TYPE => TypeRefKind::ForType(ForType::cast(self.syntax.clone()).unwrap()),
4252 IMPL_TRAIT_TYPE => TypeRefKind::ImplTraitType(ImplTraitType::cast(&self.syntax).unwrap()), 3259 IMPL_TRAIT_TYPE => TypeRefKind::ImplTraitType(ImplTraitType::cast(self.syntax.clone()).unwrap()),
4253 DYN_TRAIT_TYPE => TypeRefKind::DynTraitType(DynTraitType::cast(&self.syntax).unwrap()), 3260 DYN_TRAIT_TYPE => TypeRefKind::DynTraitType(DynTraitType::cast(self.syntax.clone()).unwrap()),
4254 _ => unreachable!(), 3261 _ => unreachable!(),
4255 } 3262 }
4256 } 3263 }
@@ -4259,232 +3266,169 @@ impl TypeRef {
4259impl TypeRef {} 3266impl TypeRef {}
4260 3267
4261// UseItem 3268// UseItem
4262#[derive(Debug, PartialEq, Eq, Hash)] 3269#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4263#[repr(transparent)]
4264pub struct UseItem { 3270pub struct UseItem {
4265 pub(crate) syntax: SyntaxNode, 3271 pub(crate) syntax: SyntaxNode,
4266} 3272}
4267unsafe impl TransparentNewType for UseItem {
4268 type Repr = rowan::SyntaxNode;
4269}
4270 3273
4271impl AstNode for UseItem { 3274impl AstNode for UseItem {
4272 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3275 fn cast(syntax: SyntaxNode) -> Option<Self> {
4273 match syntax.kind() { 3276 match syntax.kind() {
4274 USE_ITEM => Some(UseItem::from_repr(syntax.into_repr())), 3277 USE_ITEM => Some(UseItem { syntax }),
4275 _ => None, 3278 _ => None,
4276 } 3279 }
4277 } 3280 }
4278 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3281 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4279} 3282}
4280 3283
4281impl ToOwned for UseItem {
4282 type Owned = TreeArc<UseItem>;
4283 fn to_owned(&self) -> TreeArc<UseItem> { TreeArc::cast(self.syntax.to_owned()) }
4284}
4285
4286 3284
4287impl ast::AttrsOwner for UseItem {} 3285impl ast::AttrsOwner for UseItem {}
4288impl UseItem { 3286impl UseItem {
4289 pub fn use_tree(&self) -> Option<&UseTree> { 3287 pub fn use_tree(&self) -> Option<UseTree> {
4290 super::child_opt(self) 3288 super::child_opt(self)
4291 } 3289 }
4292} 3290}
4293 3291
4294// UseTree 3292// UseTree
4295#[derive(Debug, PartialEq, Eq, Hash)] 3293#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4296#[repr(transparent)]
4297pub struct UseTree { 3294pub struct UseTree {
4298 pub(crate) syntax: SyntaxNode, 3295 pub(crate) syntax: SyntaxNode,
4299} 3296}
4300unsafe impl TransparentNewType for UseTree {
4301 type Repr = rowan::SyntaxNode;
4302}
4303 3297
4304impl AstNode for UseTree { 3298impl AstNode for UseTree {
4305 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3299 fn cast(syntax: SyntaxNode) -> Option<Self> {
4306 match syntax.kind() { 3300 match syntax.kind() {
4307 USE_TREE => Some(UseTree::from_repr(syntax.into_repr())), 3301 USE_TREE => Some(UseTree { syntax }),
4308 _ => None, 3302 _ => None,
4309 } 3303 }
4310 } 3304 }
4311 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3305 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4312} 3306}
4313 3307
4314impl ToOwned for UseTree {
4315 type Owned = TreeArc<UseTree>;
4316 fn to_owned(&self) -> TreeArc<UseTree> { TreeArc::cast(self.syntax.to_owned()) }
4317}
4318
4319 3308
4320impl UseTree { 3309impl UseTree {
4321 pub fn path(&self) -> Option<&Path> { 3310 pub fn path(&self) -> Option<Path> {
4322 super::child_opt(self) 3311 super::child_opt(self)
4323 } 3312 }
4324 3313
4325 pub fn use_tree_list(&self) -> Option<&UseTreeList> { 3314 pub fn use_tree_list(&self) -> Option<UseTreeList> {
4326 super::child_opt(self) 3315 super::child_opt(self)
4327 } 3316 }
4328 3317
4329 pub fn alias(&self) -> Option<&Alias> { 3318 pub fn alias(&self) -> Option<Alias> {
4330 super::child_opt(self) 3319 super::child_opt(self)
4331 } 3320 }
4332} 3321}
4333 3322
4334// UseTreeList 3323// UseTreeList
4335#[derive(Debug, PartialEq, Eq, Hash)] 3324#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4336#[repr(transparent)]
4337pub struct UseTreeList { 3325pub struct UseTreeList {
4338 pub(crate) syntax: SyntaxNode, 3326 pub(crate) syntax: SyntaxNode,
4339} 3327}
4340unsafe impl TransparentNewType for UseTreeList {
4341 type Repr = rowan::SyntaxNode;
4342}
4343 3328
4344impl AstNode for UseTreeList { 3329impl AstNode for UseTreeList {
4345 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3330 fn cast(syntax: SyntaxNode) -> Option<Self> {
4346 match syntax.kind() { 3331 match syntax.kind() {
4347 USE_TREE_LIST => Some(UseTreeList::from_repr(syntax.into_repr())), 3332 USE_TREE_LIST => Some(UseTreeList { syntax }),
4348 _ => None, 3333 _ => None,
4349 } 3334 }
4350 } 3335 }
4351 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3336 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4352} 3337}
4353 3338
4354impl ToOwned for UseTreeList {
4355 type Owned = TreeArc<UseTreeList>;
4356 fn to_owned(&self) -> TreeArc<UseTreeList> { TreeArc::cast(self.syntax.to_owned()) }
4357}
4358
4359 3339
4360impl UseTreeList { 3340impl UseTreeList {
4361 pub fn use_trees(&self) -> impl Iterator<Item = &UseTree> { 3341 pub fn use_trees(&self) -> impl Iterator<Item = UseTree> {
4362 super::children(self) 3342 super::children(self)
4363 } 3343 }
4364} 3344}
4365 3345
4366// Visibility 3346// Visibility
4367#[derive(Debug, PartialEq, Eq, Hash)] 3347#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4368#[repr(transparent)]
4369pub struct Visibility { 3348pub struct Visibility {
4370 pub(crate) syntax: SyntaxNode, 3349 pub(crate) syntax: SyntaxNode,
4371} 3350}
4372unsafe impl TransparentNewType for Visibility {
4373 type Repr = rowan::SyntaxNode;
4374}
4375 3351
4376impl AstNode for Visibility { 3352impl AstNode for Visibility {
4377 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3353 fn cast(syntax: SyntaxNode) -> Option<Self> {
4378 match syntax.kind() { 3354 match syntax.kind() {
4379 VISIBILITY => Some(Visibility::from_repr(syntax.into_repr())), 3355 VISIBILITY => Some(Visibility { syntax }),
4380 _ => None, 3356 _ => None,
4381 } 3357 }
4382 } 3358 }
4383 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3359 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4384} 3360}
4385 3361
4386impl ToOwned for Visibility {
4387 type Owned = TreeArc<Visibility>;
4388 fn to_owned(&self) -> TreeArc<Visibility> { TreeArc::cast(self.syntax.to_owned()) }
4389}
4390
4391 3362
4392impl Visibility {} 3363impl Visibility {}
4393 3364
4394// WhereClause 3365// WhereClause
4395#[derive(Debug, PartialEq, Eq, Hash)] 3366#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4396#[repr(transparent)]
4397pub struct WhereClause { 3367pub struct WhereClause {
4398 pub(crate) syntax: SyntaxNode, 3368 pub(crate) syntax: SyntaxNode,
4399} 3369}
4400unsafe impl TransparentNewType for WhereClause {
4401 type Repr = rowan::SyntaxNode;
4402}
4403 3370
4404impl AstNode for WhereClause { 3371impl AstNode for WhereClause {
4405 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3372 fn cast(syntax: SyntaxNode) -> Option<Self> {
4406 match syntax.kind() { 3373 match syntax.kind() {
4407 WHERE_CLAUSE => Some(WhereClause::from_repr(syntax.into_repr())), 3374 WHERE_CLAUSE => Some(WhereClause { syntax }),
4408 _ => None, 3375 _ => None,
4409 } 3376 }
4410 } 3377 }
4411 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3378 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4412} 3379}
4413 3380
4414impl ToOwned for WhereClause {
4415 type Owned = TreeArc<WhereClause>;
4416 fn to_owned(&self) -> TreeArc<WhereClause> { TreeArc::cast(self.syntax.to_owned()) }
4417}
4418
4419 3381
4420impl WhereClause { 3382impl WhereClause {
4421 pub fn predicates(&self) -> impl Iterator<Item = &WherePred> { 3383 pub fn predicates(&self) -> impl Iterator<Item = WherePred> {
4422 super::children(self) 3384 super::children(self)
4423 } 3385 }
4424} 3386}
4425 3387
4426// WherePred 3388// WherePred
4427#[derive(Debug, PartialEq, Eq, Hash)] 3389#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4428#[repr(transparent)]
4429pub struct WherePred { 3390pub struct WherePred {
4430 pub(crate) syntax: SyntaxNode, 3391 pub(crate) syntax: SyntaxNode,
4431} 3392}
4432unsafe impl TransparentNewType for WherePred {
4433 type Repr = rowan::SyntaxNode;
4434}
4435 3393
4436impl AstNode for WherePred { 3394impl AstNode for WherePred {
4437 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3395 fn cast(syntax: SyntaxNode) -> Option<Self> {
4438 match syntax.kind() { 3396 match syntax.kind() {
4439 WHERE_PRED => Some(WherePred::from_repr(syntax.into_repr())), 3397 WHERE_PRED => Some(WherePred { syntax }),
4440 _ => None, 3398 _ => None,
4441 } 3399 }
4442 } 3400 }
4443 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3401 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4444} 3402}
4445 3403
4446impl ToOwned for WherePred {
4447 type Owned = TreeArc<WherePred>;
4448 fn to_owned(&self) -> TreeArc<WherePred> { TreeArc::cast(self.syntax.to_owned()) }
4449}
4450
4451 3404
4452impl ast::TypeBoundsOwner for WherePred {} 3405impl ast::TypeBoundsOwner for WherePred {}
4453impl WherePred { 3406impl WherePred {
4454 pub fn type_ref(&self) -> Option<&TypeRef> { 3407 pub fn type_ref(&self) -> Option<TypeRef> {
4455 super::child_opt(self) 3408 super::child_opt(self)
4456 } 3409 }
4457} 3410}
4458 3411
4459// WhileExpr 3412// WhileExpr
4460#[derive(Debug, PartialEq, Eq, Hash)] 3413#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4461#[repr(transparent)]
4462pub struct WhileExpr { 3414pub struct WhileExpr {
4463 pub(crate) syntax: SyntaxNode, 3415 pub(crate) syntax: SyntaxNode,
4464} 3416}
4465unsafe impl TransparentNewType for WhileExpr {
4466 type Repr = rowan::SyntaxNode;
4467}
4468 3417
4469impl AstNode for WhileExpr { 3418impl AstNode for WhileExpr {
4470 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 3419 fn cast(syntax: SyntaxNode) -> Option<Self> {
4471 match syntax.kind() { 3420 match syntax.kind() {
4472 WHILE_EXPR => Some(WhileExpr::from_repr(syntax.into_repr())), 3421 WHILE_EXPR => Some(WhileExpr { syntax }),
4473 _ => None, 3422 _ => None,
4474 } 3423 }
4475 } 3424 }
4476 fn syntax(&self) -> &SyntaxNode { &self.syntax } 3425 fn syntax(&self) -> &SyntaxNode { &self.syntax }
4477} 3426}
4478 3427
4479impl ToOwned for WhileExpr {
4480 type Owned = TreeArc<WhileExpr>;
4481 fn to_owned(&self) -> TreeArc<WhileExpr> { TreeArc::cast(self.syntax.to_owned()) }
4482}
4483
4484 3428
4485impl ast::LoopBodyOwner for WhileExpr {} 3429impl ast::LoopBodyOwner for WhileExpr {}
4486impl WhileExpr { 3430impl WhileExpr {
4487 pub fn condition(&self) -> Option<&Condition> { 3431 pub fn condition(&self) -> Option<Condition> {
4488 super::child_opt(self) 3432 super::child_opt(self)
4489 } 3433 }
4490} 3434}
diff --git a/crates/ra_syntax/src/ast/generated.rs.tera b/crates/ra_syntax/src/ast/generated.rs.tera
index c8a13fc5f..f3365c560 100644
--- a/crates/ra_syntax/src/ast/generated.rs.tera
+++ b/crates/ra_syntax/src/ast/generated.rs.tera
@@ -11,94 +11,73 @@ the below applies to the result of this template
11 11
12#![cfg_attr(rustfmt, rustfmt_skip)] 12#![cfg_attr(rustfmt, rustfmt_skip)]
13 13
14use rowan::TransparentNewType;
15
16use crate::{ 14use crate::{
17 SyntaxNode, SyntaxKind::*, 15 SyntaxNode, SyntaxKind::*,
18 syntax_node::{TreeArc},
19 ast::{self, AstNode}, 16 ast::{self, AstNode},
20}; 17};
21{% for node, methods in ast %} 18{% for node, methods in ast %}
22// {{ node }} 19// {{ node }}
23 20
24{%- if methods.enum %} 21{%- if methods.enum %}
25#[derive(Debug, PartialEq, Eq, Hash)] 22#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26#[repr(transparent)]
27pub struct {{ node }} { 23pub struct {{ node }} {
28 pub(crate) syntax: SyntaxNode, 24 pub(crate) syntax: SyntaxNode,
29} 25}
30unsafe impl TransparentNewType for {{ node }} {
31 type Repr = rowan::SyntaxNode;
32}
33 26
34#[derive(Debug, Clone, Copy, PartialEq, Eq)] 27#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum {{ node }}Kind<'a> { 28pub enum {{ node }}Kind {
36{%- for kind in methods.enum %} 29{%- for kind in methods.enum %}
37 {{ kind }}(&'a {{ kind }}), 30 {{ kind }}({{ kind }}),
38{%- endfor %} 31{%- endfor %}
39} 32}
40 33
41{%- for kind in methods.enum %} 34{%- for kind in methods.enum %}
42impl<'a> From<&'a {{ kind }}> for &'a {{ node }} { 35impl From<{{ kind }}> for {{ node }} {
43 fn from(n: &'a {{ kind }}) -> &'a {{ node }} { 36 fn from(n: {{ kind }}) -> {{ node }} {
44 {{ node }}::cast(&n.syntax).unwrap() 37 {{ node }}::cast(n.syntax).unwrap()
45 } 38 }
46} 39}
47{%- endfor %} 40{%- endfor %}
48 41
49 42
50impl AstNode for {{ node }} { 43impl AstNode for {{ node }} {
51 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 44 fn cast(syntax: SyntaxNode) -> Option<Self> {
52 match syntax.kind() { 45 match syntax.kind() {
53 {%- for kind in methods.enum %} 46 {%- for kind in methods.enum %}
54 | {{ kind | SCREAM }} 47 | {{ kind | SCREAM }}
55 {%- endfor %} => Some({{ node }}::from_repr(syntax.into_repr())), 48 {%- endfor %} => Some({{ node }} { syntax }),
56 _ => None, 49 _ => None,
57 } 50 }
58 } 51 }
59 fn syntax(&self) -> &SyntaxNode { &self.syntax } 52 fn syntax(&self) -> &SyntaxNode { &self.syntax }
60} 53}
61 54
62impl ToOwned for {{ node }} {
63 type Owned = TreeArc<{{ node }}>;
64 fn to_owned(&self) -> TreeArc<{{ node }}> { TreeArc::cast(self.syntax.to_owned()) }
65}
66
67impl {{ node }} { 55impl {{ node }} {
68 pub fn kind(&self) -> {{ node }}Kind { 56 pub fn kind(&self) -> {{ node }}Kind {
69 match self.syntax.kind() { 57 match self.syntax.kind() {
70 {%- for kind in methods.enum %} 58 {%- for kind in methods.enum %}
71 {{ kind | SCREAM }} => {{ node }}Kind::{{ kind }}({{ kind }}::cast(&self.syntax).unwrap()), 59 {{ kind | SCREAM }} => {{ node }}Kind::{{ kind }}({{ kind }}::cast(self.syntax.clone()).unwrap()),
72 {%- endfor %} 60 {%- endfor %}
73 _ => unreachable!(), 61 _ => unreachable!(),
74 } 62 }
75 } 63 }
76} 64}
77{% else %} 65{% else %}
78#[derive(Debug, PartialEq, Eq, Hash)] 66#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79#[repr(transparent)]
80pub struct {{ node }} { 67pub struct {{ node }} {
81 pub(crate) syntax: SyntaxNode, 68 pub(crate) syntax: SyntaxNode,
82} 69}
83unsafe impl TransparentNewType for {{ node }} {
84 type Repr = rowan::SyntaxNode;
85}
86 70
87impl AstNode for {{ node }} { 71impl AstNode for {{ node }} {
88 fn cast(syntax: &SyntaxNode) -> Option<&Self> { 72 fn cast(syntax: SyntaxNode) -> Option<Self> {
89 match syntax.kind() { 73 match syntax.kind() {
90 {{ node | SCREAM }} => Some({{ node }}::from_repr(syntax.into_repr())), 74 {{ node | SCREAM }} => Some({{ node }} { syntax }),
91 _ => None, 75 _ => None,
92 } 76 }
93 } 77 }
94 fn syntax(&self) -> &SyntaxNode { &self.syntax } 78 fn syntax(&self) -> &SyntaxNode { &self.syntax }
95} 79}
96 80
97impl ToOwned for {{ node }} {
98 type Owned = TreeArc<{{ node }}>;
99 fn to_owned(&self) -> TreeArc<{{ node }}> { TreeArc::cast(self.syntax.to_owned()) }
100}
101
102{% endif %} 81{% endif %}
103{% if methods.traits -%} 82{% if methods.traits -%}
104 83
@@ -113,7 +92,7 @@ impl {{ node }} {
113{%- for m in methods.collections -%} 92{%- for m in methods.collections -%}
114{%- set method_name = m.0 -%} 93{%- set method_name = m.0 -%}
115{%- set ChildName = m.1 %} 94{%- set ChildName = m.1 %}
116 pub fn {{ method_name }}(&self) -> impl Iterator<Item = &{{ ChildName }}> { 95 pub fn {{ method_name }}(&self) -> impl Iterator<Item = {{ ChildName }}> {
117 super::children(self) 96 super::children(self)
118 } 97 }
119{% endfor -%} 98{% endfor -%}
@@ -129,7 +108,7 @@ impl {{ node }} {
129{%- set method_name = m.0 -%} 108{%- set method_name = m.0 -%}
130{%- set ChildName = m.1 %} 109{%- set ChildName = m.1 %}
131{%- endif %} 110{%- endif %}
132 pub fn {{ method_name }}(&self) -> Option<&{{ ChildName }}> { 111 pub fn {{ method_name }}(&self) -> Option<{{ ChildName }}> {
133 super::child_opt(self) 112 super::child_opt(self)
134 } 113 }
135{% endfor -%} 114{% endfor -%}
diff --git a/crates/ra_syntax/src/ast/tokens.rs b/crates/ra_syntax/src/ast/tokens.rs
index be63b3c9e..87cca325d 100644
--- a/crates/ra_syntax/src/ast/tokens.rs
+++ b/crates/ra_syntax/src/ast/tokens.rs
@@ -6,23 +6,23 @@ use crate::{
6 SyntaxToken, 6 SyntaxToken,
7}; 7};
8 8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
10pub struct Comment<'a>(SyntaxToken<'a>); 10pub struct Comment(SyntaxToken);
11 11
12impl<'a> AstToken<'a> for Comment<'a> { 12impl AstToken for Comment {
13 fn cast(token: SyntaxToken<'a>) -> Option<Self> { 13 fn cast(token: SyntaxToken) -> Option<Self> {
14 if token.kind() == COMMENT { 14 if token.kind() == COMMENT {
15 Some(Comment(token)) 15 Some(Comment(token))
16 } else { 16 } else {
17 None 17 None
18 } 18 }
19 } 19 }
20 fn syntax(&self) -> SyntaxToken<'a> { 20 fn syntax(&self) -> &SyntaxToken {
21 self.0 21 &self.0
22 } 22 }
23} 23}
24 24
25impl<'a> Comment<'a> { 25impl Comment {
26 pub fn kind(&self) -> CommentKind { 26 pub fn kind(&self) -> CommentKind {
27 kind_by_prefix(self.text()) 27 kind_by_prefix(self.text())
28 } 28 }
@@ -90,22 +90,22 @@ fn prefix_by_kind(kind: CommentKind) -> &'static str {
90 unreachable!() 90 unreachable!()
91} 91}
92 92
93pub struct Whitespace<'a>(SyntaxToken<'a>); 93pub struct Whitespace(SyntaxToken);
94 94
95impl<'a> AstToken<'a> for Whitespace<'a> { 95impl AstToken for Whitespace {
96 fn cast(token: SyntaxToken<'a>) -> Option<Self> { 96 fn cast(token: SyntaxToken) -> Option<Self> {
97 if token.kind() == WHITESPACE { 97 if token.kind() == WHITESPACE {
98 Some(Whitespace(token)) 98 Some(Whitespace(token))
99 } else { 99 } else {
100 None 100 None
101 } 101 }
102 } 102 }
103 fn syntax(&self) -> SyntaxToken<'a> { 103 fn syntax(&self) -> &SyntaxToken {
104 self.0 104 &self.0
105 } 105 }
106} 106}
107 107
108impl<'a> Whitespace<'a> { 108impl Whitespace {
109 pub fn spans_multiple_lines(&self) -> bool { 109 pub fn spans_multiple_lines(&self) -> bool {
110 let text = self.text(); 110 let text = self.text();
111 text.find('\n').map_or(false, |idx| text[idx + 1..].contains('\n')) 111 text.find('\n').map_or(false, |idx| text[idx + 1..].contains('\n'))
diff --git a/crates/ra_syntax/src/ast/traits.rs b/crates/ra_syntax/src/ast/traits.rs
index 29cb53e35..ecbd2d427 100644
--- a/crates/ra_syntax/src/ast/traits.rs
+++ b/crates/ra_syntax/src/ast/traits.rs
@@ -10,37 +10,37 @@ use crate::{
10}; 10};
11 11
12pub trait TypeAscriptionOwner: AstNode { 12pub trait TypeAscriptionOwner: AstNode {
13 fn ascribed_type(&self) -> Option<&ast::TypeRef> { 13 fn ascribed_type(&self) -> Option<ast::TypeRef> {
14 child_opt(self) 14 child_opt(self)
15 } 15 }
16} 16}
17 17
18pub trait NameOwner: AstNode { 18pub trait NameOwner: AstNode {
19 fn name(&self) -> Option<&ast::Name> { 19 fn name(&self) -> Option<ast::Name> {
20 child_opt(self) 20 child_opt(self)
21 } 21 }
22} 22}
23 23
24pub trait VisibilityOwner: AstNode { 24pub trait VisibilityOwner: AstNode {
25 fn visibility(&self) -> Option<&ast::Visibility> { 25 fn visibility(&self) -> Option<ast::Visibility> {
26 child_opt(self) 26 child_opt(self)
27 } 27 }
28} 28}
29 29
30pub trait LoopBodyOwner: AstNode { 30pub trait LoopBodyOwner: AstNode {
31 fn loop_body(&self) -> Option<&ast::Block> { 31 fn loop_body(&self) -> Option<ast::Block> {
32 child_opt(self) 32 child_opt(self)
33 } 33 }
34} 34}
35 35
36pub trait TryBlockBodyOwner: AstNode { 36pub trait TryBlockBodyOwner: AstNode {
37 fn try_body(&self) -> Option<&ast::Block> { 37 fn try_body(&self) -> Option<ast::Block> {
38 child_opt(self) 38 child_opt(self)
39 } 39 }
40} 40}
41 41
42pub trait ArgListOwner: AstNode { 42pub trait ArgListOwner: AstNode {
43 fn arg_list(&self) -> Option<&ast::ArgList> { 43 fn arg_list(&self) -> Option<ast::ArgList> {
44 child_opt(self) 44 child_opt(self)
45 } 45 }
46} 46}
@@ -51,10 +51,10 @@ pub trait FnDefOwner: AstNode {
51 } 51 }
52} 52}
53 53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)] 54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum ItemOrMacro<'a> { 55pub enum ItemOrMacro {
56 Item(&'a ast::ModuleItem), 56 Item(ast::ModuleItem),
57 Macro(&'a ast::MacroCall), 57 Macro(ast::MacroCall),
58} 58}
59 59
60pub trait ModuleItemOwner: AstNode { 60pub trait ModuleItemOwner: AstNode {
@@ -67,14 +67,14 @@ pub trait ModuleItemOwner: AstNode {
67} 67}
68 68
69#[derive(Debug)] 69#[derive(Debug)]
70pub struct ItemOrMacroIter<'a>(SyntaxNodeChildren<'a>); 70pub struct ItemOrMacroIter(SyntaxNodeChildren);
71 71
72impl<'a> Iterator for ItemOrMacroIter<'a> { 72impl Iterator for ItemOrMacroIter {
73 type Item = ItemOrMacro<'a>; 73 type Item = ItemOrMacro;
74 fn next(&mut self) -> Option<ItemOrMacro<'a>> { 74 fn next(&mut self) -> Option<ItemOrMacro> {
75 loop { 75 loop {
76 let n = self.0.next()?; 76 let n = self.0.next()?;
77 if let Some(item) = ast::ModuleItem::cast(n) { 77 if let Some(item) = ast::ModuleItem::cast(n.clone()) {
78 return Some(ItemOrMacro::Item(item)); 78 return Some(ItemOrMacro::Item(item));
79 } 79 }
80 if let Some(call) = ast::MacroCall::cast(n) { 80 if let Some(call) = ast::MacroCall::cast(n) {
@@ -85,17 +85,17 @@ impl<'a> Iterator for ItemOrMacroIter<'a> {
85} 85}
86 86
87pub trait TypeParamsOwner: AstNode { 87pub trait TypeParamsOwner: AstNode {
88 fn type_param_list(&self) -> Option<&ast::TypeParamList> { 88 fn type_param_list(&self) -> Option<ast::TypeParamList> {
89 child_opt(self) 89 child_opt(self)
90 } 90 }
91 91
92 fn where_clause(&self) -> Option<&ast::WhereClause> { 92 fn where_clause(&self) -> Option<ast::WhereClause> {
93 child_opt(self) 93 child_opt(self)
94 } 94 }
95} 95}
96 96
97pub trait TypeBoundsOwner: AstNode { 97pub trait TypeBoundsOwner: AstNode {
98 fn type_bound_list(&self) -> Option<&ast::TypeBoundList> { 98 fn type_bound_list(&self) -> Option<ast::TypeBoundList> {
99 child_opt(self) 99 child_opt(self)
100 } 100 }
101} 101}
@@ -148,19 +148,19 @@ pub trait DocCommentsOwner: AstNode {
148 } 148 }
149} 149}
150 150
151pub struct CommentIter<'a> { 151pub struct CommentIter {
152 iter: SyntaxElementChildren<'a>, 152 iter: SyntaxElementChildren,
153} 153}
154 154
155impl<'a> Iterator for CommentIter<'a> { 155impl Iterator for CommentIter {
156 type Item = ast::Comment<'a>; 156 type Item = ast::Comment;
157 fn next(&mut self) -> Option<ast::Comment<'a>> { 157 fn next(&mut self) -> Option<ast::Comment> {
158 self.iter.by_ref().find_map(|el| el.as_token().and_then(ast::Comment::cast)) 158 self.iter.by_ref().find_map(|el| el.as_token().cloned().and_then(ast::Comment::cast))
159 } 159 }
160} 160}
161 161
162pub trait DefaultTypeParamOwner: AstNode { 162pub trait DefaultTypeParamOwner: AstNode {
163 fn default_type(&self) -> Option<&ast::PathType> { 163 fn default_type(&self) -> Option<ast::PathType> {
164 child_opt(self) 164 child_opt(self)
165 } 165 }
166} 166}
diff --git a/crates/ra_syntax/src/fuzz.rs b/crates/ra_syntax/src/fuzz.rs
index 00039f970..716925b2f 100644
--- a/crates/ra_syntax/src/fuzz.rs
+++ b/crates/ra_syntax/src/fuzz.rs
@@ -9,7 +9,7 @@ fn check_file_invariants(file: &SourceFile) {
9 9
10pub fn check_parser(text: &str) { 10pub fn check_parser(text: &str) {
11 let file = SourceFile::parse(text); 11 let file = SourceFile::parse(text);
12 check_file_invariants(&file.tree); 12 check_file_invariants(&file.tree());
13} 13}
14 14
15#[derive(Debug, Clone)] 15#[derive(Debug, Clone)]
@@ -45,16 +45,16 @@ impl CheckReparse {
45 pub fn run(&self) { 45 pub fn run(&self) {
46 let parse = SourceFile::parse(&self.text); 46 let parse = SourceFile::parse(&self.text);
47 let new_parse = parse.reparse(&self.edit); 47 let new_parse = parse.reparse(&self.edit);
48 check_file_invariants(&new_parse.tree); 48 check_file_invariants(&new_parse.tree());
49 assert_eq!(&new_parse.tree.syntax().text().to_string(), &self.edited_text); 49 assert_eq!(&new_parse.tree().syntax().text().to_string(), &self.edited_text);
50 let full_reparse = SourceFile::parse(&self.edited_text); 50 let full_reparse = SourceFile::parse(&self.edited_text);
51 for (a, b) in 51 for (a, b) in
52 new_parse.tree.syntax().descendants().zip(full_reparse.tree.syntax().descendants()) 52 new_parse.tree().syntax().descendants().zip(full_reparse.tree().syntax().descendants())
53 { 53 {
54 if (a.kind(), a.range()) != (b.kind(), b.range()) { 54 if (a.kind(), a.range()) != (b.kind(), b.range()) {
55 eprint!("original:\n{}", parse.tree.syntax().debug_dump()); 55 eprint!("original:\n{}", parse.tree().syntax().debug_dump());
56 eprint!("reparsed:\n{}", new_parse.tree.syntax().debug_dump()); 56 eprint!("reparsed:\n{}", new_parse.tree().syntax().debug_dump());
57 eprint!("full reparse:\n{}", full_reparse.tree.syntax().debug_dump()); 57 eprint!("full reparse:\n{}", full_reparse.tree().syntax().debug_dump());
58 assert_eq!( 58 assert_eq!(
59 format!("{:?}", a), 59 format!("{:?}", a),
60 format!("{:?}", b), 60 format!("{:?}", b),
diff --git a/crates/ra_syntax/src/lib.rs b/crates/ra_syntax/src/lib.rs
index 534c206a6..2dca4e3e8 100644
--- a/crates/ra_syntax/src/lib.rs
+++ b/crates/ra_syntax/src/lib.rs
@@ -31,7 +31,7 @@ pub mod ast;
31#[doc(hidden)] 31#[doc(hidden)]
32pub mod fuzz; 32pub mod fuzz;
33 33
34use std::{fmt::Write, sync::Arc}; 34use std::{fmt::Write, marker::PhantomData, sync::Arc};
35 35
36use ra_text_edit::AtomTextEdit; 36use ra_text_edit::AtomTextEdit;
37 37
@@ -43,8 +43,8 @@ pub use crate::{
43 ptr::{AstPtr, SyntaxNodePtr}, 43 ptr::{AstPtr, SyntaxNodePtr},
44 syntax_error::{Location, SyntaxError, SyntaxErrorKind}, 44 syntax_error::{Location, SyntaxError, SyntaxErrorKind},
45 syntax_node::{ 45 syntax_node::{
46 Direction, InsertPosition, SyntaxElement, SyntaxNode, SyntaxNodeWrapper, SyntaxToken, 46 Direction, InsertPosition, SyntaxElement, SyntaxNode, SyntaxToken, SyntaxTreeBuilder,
47 SyntaxTreeBuilder, TreeArc, WalkEvent, 47 WalkEvent,
48 }, 48 },
49 syntax_text::SyntaxText, 49 syntax_text::SyntaxText,
50}; 50};
@@ -58,48 +58,63 @@ pub use rowan::{SmolStr, TextRange, TextUnit};
58/// Note that we always produce a syntax tree, even for completely invalid 58/// Note that we always produce a syntax tree, even for completely invalid
59/// files. 59/// files.
60#[derive(Debug, PartialEq, Eq)] 60#[derive(Debug, PartialEq, Eq)]
61pub struct Parse<T: SyntaxNodeWrapper> { 61pub struct Parse<T> {
62 tree: TreeArc<T>, 62 green: GreenNode,
63 errors: Arc<Vec<SyntaxError>>, 63 errors: Arc<Vec<SyntaxError>>,
64 _ty: PhantomData<fn() -> T>,
64} 65}
65 66
66impl<T: SyntaxNodeWrapper> Clone for Parse<T> { 67impl<T> Clone for Parse<T> {
67 fn clone(&self) -> Parse<T> { 68 fn clone(&self) -> Parse<T> {
68 Parse { tree: self.tree.clone(), errors: self.errors.clone() } 69 Parse { green: self.green.clone(), errors: self.errors.clone(), _ty: PhantomData }
69 } 70 }
70} 71}
71 72
72impl<T: SyntaxNodeWrapper> Parse<T> { 73impl<T> Parse<T> {
73 fn new(tree: TreeArc<T>, errors: Vec<SyntaxError>) -> Parse<T> { 74 fn new(green: GreenNode, errors: Vec<SyntaxError>) -> Parse<T> {
74 Parse { tree, errors: Arc::new(errors) } 75 Parse { green, errors: Arc::new(errors), _ty: PhantomData }
75 } 76 }
76 77
77 pub fn tree(&self) -> &T { 78 pub fn syntax_node(&self) -> SyntaxNode {
78 &*self.tree 79 SyntaxNode::new(self.green.clone())
80 }
81}
82
83impl<T: AstNode> Parse<T> {
84 pub fn to_syntax(self) -> Parse<SyntaxNode> {
85 Parse { green: self.green, errors: self.errors, _ty: PhantomData }
86 }
87
88 pub fn tree(&self) -> T {
89 T::cast(self.syntax_node()).unwrap()
79 } 90 }
80 91
81 pub fn errors(&self) -> &[SyntaxError] { 92 pub fn errors(&self) -> &[SyntaxError] {
82 &*self.errors 93 &*self.errors
83 } 94 }
84 95
85 pub fn ok(self) -> Result<TreeArc<T>, Arc<Vec<SyntaxError>>> { 96 pub fn ok(self) -> Result<T, Arc<Vec<SyntaxError>>> {
86 if self.errors.is_empty() { 97 if self.errors.is_empty() {
87 Ok(self.tree) 98 Ok(self.tree())
88 } else { 99 } else {
89 Err(self.errors) 100 Err(self.errors)
90 } 101 }
91 } 102 }
92} 103}
93 104
94impl<T: AstNode> Parse<T> { 105impl Parse<SyntaxNode> {
95 pub fn to_syntax(this: Self) -> Parse<SyntaxNode> { 106 pub fn cast<N: AstNode>(self) -> Option<Parse<N>> {
96 Parse { tree: this.tree().syntax().to_owned(), errors: this.errors } 107 if N::cast(self.syntax_node()).is_some() {
108 Some(Parse { green: self.green, errors: self.errors, _ty: PhantomData })
109 } else {
110 None
111 }
97 } 112 }
98} 113}
99 114
100impl Parse<SourceFile> { 115impl Parse<SourceFile> {
101 pub fn debug_dump(&self) -> String { 116 pub fn debug_dump(&self) -> String {
102 let mut buf = self.tree.syntax().debug_dump(); 117 let mut buf = self.tree().syntax().debug_dump();
103 for err in self.errors.iter() { 118 for err in self.errors.iter() {
104 writeln!(buf, "error {:?}: {}", err.location(), err.kind()).unwrap(); 119 writeln!(buf, "error {:?}: {}", err.location(), err.kind()).unwrap();
105 } 120 }
@@ -112,45 +127,38 @@ impl Parse<SourceFile> {
112 127
113 fn incremental_reparse(&self, edit: &AtomTextEdit) -> Option<Parse<SourceFile>> { 128 fn incremental_reparse(&self, edit: &AtomTextEdit) -> Option<Parse<SourceFile>> {
114 // FIXME: validation errors are not handled here 129 // FIXME: validation errors are not handled here
115 parsing::incremental_reparse(self.tree.syntax(), edit, self.errors.to_vec()).map( 130 parsing::incremental_reparse(self.tree().syntax(), edit, self.errors.to_vec()).map(
116 |(green_node, errors, _reparsed_range)| Parse { 131 |(green_node, errors, _reparsed_range)| Parse {
117 tree: SourceFile::new(green_node), 132 green: green_node,
118 errors: Arc::new(errors), 133 errors: Arc::new(errors),
134 _ty: PhantomData,
119 }, 135 },
120 ) 136 )
121 } 137 }
122 138
123 fn full_reparse(&self, edit: &AtomTextEdit) -> Parse<SourceFile> { 139 fn full_reparse(&self, edit: &AtomTextEdit) -> Parse<SourceFile> {
124 let text = edit.apply(self.tree.syntax().text().to_string()); 140 let text = edit.apply(self.tree().syntax().text().to_string());
125 SourceFile::parse(&text) 141 SourceFile::parse(&text)
126 } 142 }
127} 143}
128 144
129impl Parse<SyntaxNode> {
130 pub fn cast<T: AstNode>(self) -> Option<Parse<T>> {
131 let node = T::cast(&self.tree)?;
132 Some(Parse { tree: node.to_owned(), errors: self.errors })
133 }
134}
135
136/// `SourceFile` represents a parse tree for a single Rust file. 145/// `SourceFile` represents a parse tree for a single Rust file.
137pub use crate::ast::SourceFile; 146pub use crate::ast::SourceFile;
138 147
139impl SourceFile { 148impl SourceFile {
140 fn new(green: GreenNode) -> TreeArc<SourceFile> { 149 fn new(green: GreenNode) -> SourceFile {
141 let root = SyntaxNode::new(green); 150 let root = SyntaxNode::new(green);
142 if cfg!(debug_assertions) { 151 if cfg!(debug_assertions) {
143 validation::validate_block_structure(&root); 152 validation::validate_block_structure(&root);
144 } 153 }
145 assert_eq!(root.kind(), SyntaxKind::SOURCE_FILE); 154 assert_eq!(root.kind(), SyntaxKind::SOURCE_FILE);
146 TreeArc::cast(root) 155 SourceFile::cast(root).unwrap()
147 } 156 }
148 157
149 pub fn parse(text: &str) -> Parse<SourceFile> { 158 pub fn parse(text: &str) -> Parse<SourceFile> {
150 let (green, mut errors) = parsing::parse_text(text); 159 let (green, mut errors) = parsing::parse_text(text);
151 let tree = SourceFile::new(green); 160 errors.extend(validation::validate(&SourceFile::new(green.clone())));
152 errors.extend(validation::validate(&tree)); 161 Parse { green, errors: Arc::new(errors), _ty: PhantomData }
153 Parse { tree, errors: Arc::new(errors) }
154 } 162 }
155} 163}
156 164
@@ -170,14 +178,14 @@ fn api_walkthrough() {
170 // The `parse` method returns a `Parse` -- a pair of syntax tree and a list 178 // The `parse` method returns a `Parse` -- a pair of syntax tree and a list
171 // of errors. That is, syntax tree is constructed even in presence of errors. 179 // of errors. That is, syntax tree is constructed even in presence of errors.
172 let parse = SourceFile::parse(source_code); 180 let parse = SourceFile::parse(source_code);
173 assert!(parse.errors.is_empty()); 181 assert!(parse.errors().is_empty());
174 182
175 // Due to the way ownership is set up, owned syntax Nodes always live behind 183 // The `tree` method returns an owned syntax node of type `SourceFile`.
176 // a `TreeArc` smart pointer. `TreeArc` is roughly an `std::sync::Arc` which 184 // Owned nodes are cheap: inside, they are `Rc` handles to the underling data.
177 // points to the whole file instead of an individual node. 185 let file: SourceFile = parse.tree();
178 let file: TreeArc<SourceFile> = parse.tree;
179 186
180 // `SourceFile` is the root of the syntax tree. We can iterate file's items: 187 // `SourceFile` is the root of the syntax tree. We can iterate file's items.
188 // Let's fetch the `foo` function.
181 let mut func = None; 189 let mut func = None;
182 for item in file.items() { 190 for item in file.items() {
183 match item.kind() { 191 match item.kind() {
@@ -185,31 +193,26 @@ fn api_walkthrough() {
185 _ => unreachable!(), 193 _ => unreachable!(),
186 } 194 }
187 } 195 }
188 // The returned items are always references. 196 let func: ast::FnDef = func.unwrap();
189 let func: &ast::FnDef = func.unwrap();
190
191 // All nodes implement `ToOwned` trait, with `Owned = TreeArc<Self>`.
192 // `to_owned` is a cheap operation: atomic increment.
193 let _owned_func: TreeArc<ast::FnDef> = func.to_owned();
194 197
195 // Each AST node has a bunch of getters for children. All getters return 198 // Each AST node has a bunch of getters for children. All getters return
196 // `Option`s though, to account for incomplete code. Some getters are common 199 // `Option`s though, to account for incomplete code. Some getters are common
197 // for several kinds of node. In this case, a trait like `ast::NameOwner` 200 // for several kinds of node. In this case, a trait like `ast::NameOwner`
198 // usually exists. By convention, all ast types should be used with `ast::` 201 // usually exists. By convention, all ast types should be used with `ast::`
199 // qualifier. 202 // qualifier.
200 let name: Option<&ast::Name> = func.name(); 203 let name: Option<ast::Name> = func.name();
201 let name = name.unwrap(); 204 let name = name.unwrap();
202 assert_eq!(name.text(), "foo"); 205 assert_eq!(name.text(), "foo");
203 206
204 // Let's get the `1 + 1` expression! 207 // Let's get the `1 + 1` expression!
205 let block: &ast::Block = func.body().unwrap(); 208 let block: ast::Block = func.body().unwrap();
206 let expr: &ast::Expr = block.expr().unwrap(); 209 let expr: ast::Expr = block.expr().unwrap();
207 210
208 // "Enum"-like nodes are represented using the "kind" pattern. It allows us 211 // "Enum"-like nodes are represented using the "kind" pattern. It allows us
209 // to match exhaustively against all flavors of nodes, while maintaining 212 // to match exhaustively against all flavors of nodes, while maintaining
210 // internal representation flexibility. The drawback is that one can't write 213 // internal representation flexibility. The drawback is that one can't write
211 // nested matches as one pattern. 214 // nested matches as one pattern.
212 let bin_expr: &ast::BinExpr = match expr.kind() { 215 let bin_expr: ast::BinExpr = match expr.kind() {
213 ast::ExprKind::BinExpr(e) => e, 216 ast::ExprKind::BinExpr(e) => e,
214 _ => unreachable!(), 217 _ => unreachable!(),
215 }; 218 };
@@ -219,23 +222,14 @@ fn api_walkthrough() {
219 let expr_syntax: &SyntaxNode = expr.syntax(); 222 let expr_syntax: &SyntaxNode = expr.syntax();
220 223
221 // Note how `expr` and `bin_expr` are in fact the same node underneath: 224 // Note how `expr` and `bin_expr` are in fact the same node underneath:
222 assert!(std::ptr::eq(expr_syntax, bin_expr.syntax())); 225 assert!(expr_syntax == bin_expr.syntax());
223 226
224 // To go from CST to AST, `AstNode::cast` function is used: 227 // To go from CST to AST, `AstNode::cast` function is used:
225 let expr = match ast::Expr::cast(expr_syntax) { 228 let _expr: ast::Expr = match ast::Expr::cast(expr_syntax.clone()) {
226 Some(e) => e, 229 Some(e) => e,
227 None => unreachable!(), 230 None => unreachable!(),
228 }; 231 };
229 232
230 // Note how expr is also a reference!
231 let expr: &ast::Expr = expr;
232
233 // This is possible because the underlying representation is the same:
234 assert_eq!(
235 expr as *const ast::Expr as *const u8,
236 expr_syntax as *const SyntaxNode as *const u8
237 );
238
239 // The two properties each syntax node has is a `SyntaxKind`: 233 // The two properties each syntax node has is a `SyntaxKind`:
240 assert_eq!(expr_syntax.kind(), SyntaxKind::BIN_EXPR); 234 assert_eq!(expr_syntax.kind(), SyntaxKind::BIN_EXPR);
241 235
@@ -248,7 +242,7 @@ fn api_walkthrough() {
248 assert_eq!(text.to_string(), "1 + 1"); 242 assert_eq!(text.to_string(), "1 + 1");
249 243
250 // There's a bunch of traversal methods on `SyntaxNode`: 244 // There's a bunch of traversal methods on `SyntaxNode`:
251 assert_eq!(expr_syntax.parent(), Some(block.syntax())); 245 assert_eq!(expr_syntax.parent().as_ref(), Some(block.syntax()));
252 assert_eq!(block.syntax().first_child_or_token().map(|it| it.kind()), Some(T!['{'])); 246 assert_eq!(block.syntax().first_child_or_token().map(|it| it.kind()), Some(T!['{']));
253 assert_eq!( 247 assert_eq!(
254 expr_syntax.next_sibling_or_token().map(|it| it.kind()), 248 expr_syntax.next_sibling_or_token().map(|it| it.kind()),
@@ -257,7 +251,7 @@ fn api_walkthrough() {
257 251
258 // As well as some iterator helpers: 252 // As well as some iterator helpers:
259 let f = expr_syntax.ancestors().find_map(ast::FnDef::cast); 253 let f = expr_syntax.ancestors().find_map(ast::FnDef::cast);
260 assert_eq!(f, Some(&*func)); 254 assert_eq!(f, Some(func));
261 assert!(expr_syntax.siblings_with_tokens(Direction::Next).any(|it| it.kind() == T!['}'])); 255 assert!(expr_syntax.siblings_with_tokens(Direction::Next).any(|it| it.kind() == T!['}']));
262 assert_eq!( 256 assert_eq!(
263 expr_syntax.descendants_with_tokens().count(), 257 expr_syntax.descendants_with_tokens().count(),
@@ -272,7 +266,7 @@ fn api_walkthrough() {
272 for event in expr_syntax.preorder_with_tokens() { 266 for event in expr_syntax.preorder_with_tokens() {
273 match event { 267 match event {
274 WalkEvent::Enter(node) => { 268 WalkEvent::Enter(node) => {
275 let text = match node { 269 let text = match &node {
276 SyntaxElement::Node(it) => it.text().to_string(), 270 SyntaxElement::Node(it) => it.text().to_string(),
277 SyntaxElement::Token(it) => it.text().to_string(), 271 SyntaxElement::Token(it) => it.text().to_string(),
278 }; 272 };
@@ -319,7 +313,7 @@ fn api_walkthrough() {
319 let mut exprs_visit = Vec::new(); 313 let mut exprs_visit = Vec::new();
320 for node in file.syntax().descendants() { 314 for node in file.syntax().descendants() {
321 if let Some(result) = 315 if let Some(result) =
322 visitor().visit::<ast::Expr, _>(|expr| expr.syntax().text().to_string()).accept(node) 316 visitor().visit::<ast::Expr, _>(|expr| expr.syntax().text().to_string()).accept(&node)
323 { 317 {
324 exprs_visit.push(result); 318 exprs_visit.push(result);
325 } 319 }
diff --git a/crates/ra_syntax/src/parsing/reparsing.rs b/crates/ra_syntax/src/parsing/reparsing.rs
index eeca94020..b4ad9e019 100644
--- a/crates/ra_syntax/src/parsing/reparsing.rs
+++ b/crates/ra_syntax/src/parsing/reparsing.rs
@@ -41,7 +41,7 @@ fn reparse_token<'node>(
41 root: &'node SyntaxNode, 41 root: &'node SyntaxNode,
42 edit: &AtomTextEdit, 42 edit: &AtomTextEdit,
43) -> Option<(GreenNode, TextRange)> { 43) -> Option<(GreenNode, TextRange)> {
44 let token = algo::find_covering_element(root, edit.delete).as_token()?; 44 let token = algo::find_covering_element(root, edit.delete).as_token()?.clone();
45 match token.kind() { 45 match token.kind() {
46 WHITESPACE | COMMENT | IDENT | STRING | RAW_STRING => { 46 WHITESPACE | COMMENT | IDENT | STRING | RAW_STRING => {
47 if token.kind() == WHITESPACE || token.kind() == COMMENT { 47 if token.kind() == WHITESPACE || token.kind() == COMMENT {
@@ -51,7 +51,7 @@ fn reparse_token<'node>(
51 } 51 }
52 } 52 }
53 53
54 let text = get_text_after_edit(token.into(), &edit); 54 let text = get_text_after_edit(token.clone().into(), &edit);
55 let lex_tokens = tokenize(&text); 55 let lex_tokens = tokenize(&text);
56 let lex_token = match lex_tokens[..] { 56 let lex_token = match lex_tokens[..] {
57 [lex_token] if lex_token.kind == token.kind() => lex_token, 57 [lex_token] if lex_token.kind == token.kind() => lex_token,
@@ -81,7 +81,7 @@ fn reparse_block<'node>(
81 edit: &AtomTextEdit, 81 edit: &AtomTextEdit,
82) -> Option<(GreenNode, Vec<SyntaxError>, TextRange)> { 82) -> Option<(GreenNode, Vec<SyntaxError>, TextRange)> {
83 let (node, reparser) = find_reparsable_node(root, edit.delete)?; 83 let (node, reparser) = find_reparsable_node(root, edit.delete)?;
84 let text = get_text_after_edit(node.into(), &edit); 84 let text = get_text_after_edit(node.clone().into(), &edit);
85 let tokens = tokenize(&text); 85 let tokens = tokenize(&text);
86 if !is_balanced(&tokens) { 86 if !is_balanced(&tokens) {
87 return None; 87 return None;
@@ -109,7 +109,7 @@ fn is_contextual_kw(text: &str) -> bool {
109 } 109 }
110} 110}
111 111
112fn find_reparsable_node(node: &SyntaxNode, range: TextRange) -> Option<(&SyntaxNode, Reparser)> { 112fn find_reparsable_node(node: &SyntaxNode, range: TextRange) -> Option<(SyntaxNode, Reparser)> {
113 let node = algo::find_covering_element(node, range); 113 let node = algo::find_covering_element(node, range);
114 let mut ancestors = match node { 114 let mut ancestors = match node {
115 SyntaxElement::Token(it) => it.parent().ancestors(), 115 SyntaxElement::Token(it) => it.parent().ancestors(),
@@ -167,8 +167,6 @@ fn merge_errors(
167 167
168#[cfg(test)] 168#[cfg(test)]
169mod tests { 169mod tests {
170 use std::sync::Arc;
171
172 use test_utils::{assert_eq_text, extract_range}; 170 use test_utils::{assert_eq_text, extract_range};
173 171
174 use super::*; 172 use super::*;
@@ -180,18 +178,18 @@ mod tests {
180 let after = edit.apply(before.clone()); 178 let after = edit.apply(before.clone());
181 179
182 let fully_reparsed = SourceFile::parse(&after); 180 let fully_reparsed = SourceFile::parse(&after);
183 let incrementally_reparsed = { 181 let incrementally_reparsed: Parse<SourceFile> = {
184 let f = SourceFile::parse(&before); 182 let f = SourceFile::parse(&before);
185 let edit = AtomTextEdit { delete: range, insert: replace_with.to_string() }; 183 let edit = AtomTextEdit { delete: range, insert: replace_with.to_string() };
186 let (green, new_errors, range) = 184 let (green, new_errors, range) =
187 incremental_reparse(f.tree.syntax(), &edit, f.errors.to_vec()).unwrap(); 185 incremental_reparse(f.tree().syntax(), &edit, f.errors.to_vec()).unwrap();
188 assert_eq!(range.len(), reparsed_len.into(), "reparsed fragment has wrong length"); 186 assert_eq!(range.len(), reparsed_len.into(), "reparsed fragment has wrong length");
189 Parse { tree: SourceFile::new(green), errors: Arc::new(new_errors) } 187 Parse::new(green, new_errors)
190 }; 188 };
191 189
192 assert_eq_text!( 190 assert_eq_text!(
193 &fully_reparsed.tree.syntax().debug_dump(), 191 &fully_reparsed.tree().syntax().debug_dump(),
194 &incrementally_reparsed.tree.syntax().debug_dump(), 192 &incrementally_reparsed.tree().syntax().debug_dump(),
195 ); 193 );
196 } 194 }
197 195
diff --git a/crates/ra_syntax/src/ptr.rs b/crates/ra_syntax/src/ptr.rs
index 4823eb82e..016256075 100644
--- a/crates/ra_syntax/src/ptr.rs
+++ b/crates/ra_syntax/src/ptr.rs
@@ -1,6 +1,7 @@
1use crate::{AstNode, SyntaxKind, SyntaxNode, TextRange};
2use std::{iter::successors, marker::PhantomData}; 1use std::{iter::successors, marker::PhantomData};
3 2
3use crate::{AstNode, SyntaxKind, SyntaxNode, TextRange};
4
4/// A pointer to a syntax node inside a file. It can be used to remember a 5/// A pointer to a syntax node inside a file. It can be used to remember a
5/// specific node across reparses of the same file. 6/// specific node across reparses of the same file.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -14,9 +15,9 @@ impl SyntaxNodePtr {
14 SyntaxNodePtr { range: node.range(), kind: node.kind() } 15 SyntaxNodePtr { range: node.range(), kind: node.kind() }
15 } 16 }
16 17
17 pub fn to_node(self, root: &SyntaxNode) -> &SyntaxNode { 18 pub fn to_node(self, root: &SyntaxNode) -> SyntaxNode {
18 assert!(root.parent().is_none()); 19 assert!(root.parent().is_none());
19 successors(Some(root), |&node| { 20 successors(Some(root.clone()), |node| {
20 node.children().find(|it| self.range.is_subrange(&it.range())) 21 node.children().find(|it| self.range.is_subrange(&it.range()))
21 }) 22 })
22 .find(|it| it.range() == self.range && it.kind() == self.kind) 23 .find(|it| it.range() == self.range && it.kind() == self.kind)
@@ -51,7 +52,7 @@ impl<N: AstNode> AstPtr<N> {
51 AstPtr { raw: SyntaxNodePtr::new(node.syntax()), _ty: PhantomData } 52 AstPtr { raw: SyntaxNodePtr::new(node.syntax()), _ty: PhantomData }
52 } 53 }
53 54
54 pub fn to_node(self, root: &SyntaxNode) -> &N { 55 pub fn to_node(self, root: &SyntaxNode) -> N {
55 let syntax_node = self.raw.to_node(root); 56 let syntax_node = self.raw.to_node(root);
56 N::cast(syntax_node).unwrap() 57 N::cast(syntax_node).unwrap()
57 } 58 }
@@ -75,5 +76,5 @@ fn test_local_syntax_ptr() {
75 let field = file.syntax().descendants().find_map(ast::NamedFieldDef::cast).unwrap(); 76 let field = file.syntax().descendants().find_map(ast::NamedFieldDef::cast).unwrap();
76 let ptr = SyntaxNodePtr::new(field.syntax()); 77 let ptr = SyntaxNodePtr::new(field.syntax());
77 let field_syntax = ptr.to_node(file.syntax()); 78 let field_syntax = ptr.to_node(file.syntax());
78 assert_eq!(field.syntax(), &*field_syntax); 79 assert_eq!(field.syntax(), &field_syntax);
79} 80}
diff --git a/crates/ra_syntax/src/syntax_node.rs b/crates/ra_syntax/src/syntax_node.rs
index e57813a94..cf680e66a 100644
--- a/crates/ra_syntax/src/syntax_node.rs
+++ b/crates/ra_syntax/src/syntax_node.rs
@@ -7,14 +7,13 @@
7//! modules just wraps its API. 7//! modules just wraps its API.
8 8
9use std::{ 9use std::{
10 borrow::Borrow,
11 fmt::{self, Write}, 10 fmt::{self, Write},
12 iter::successors, 11 iter::successors,
13 ops::RangeInclusive, 12 ops::RangeInclusive,
14}; 13};
15 14
16use ra_parser::ParseError; 15use ra_parser::ParseError;
17use rowan::{GreenNodeBuilder, TransparentNewType}; 16use rowan::GreenNodeBuilder;
18 17
19use crate::{ 18use crate::{
20 syntax_error::{SyntaxError, SyntaxErrorKind}, 19 syntax_error::{SyntaxError, SyntaxErrorKind},
@@ -33,86 +32,8 @@ pub enum InsertPosition<T> {
33 After(T), 32 After(T),
34} 33}
35 34
36/// Marker trait for CST and AST nodes 35#[derive(PartialEq, Eq, Hash, Clone)]
37pub trait SyntaxNodeWrapper: TransparentNewType<Repr = rowan::SyntaxNode> {} 36pub struct SyntaxNode(pub(crate) rowan::cursor::SyntaxNode);
38impl<T: TransparentNewType<Repr = rowan::SyntaxNode>> SyntaxNodeWrapper for T {}
39
40/// An owning smart pointer for CST or AST node.
41#[derive(PartialEq, Eq, Hash)]
42pub struct TreeArc<T: SyntaxNodeWrapper>(pub(crate) rowan::TreeArc<T>);
43
44impl<T: SyntaxNodeWrapper> Borrow<T> for TreeArc<T> {
45 fn borrow(&self) -> &T {
46 &*self
47 }
48}
49
50impl<T> TreeArc<T>
51where
52 T: SyntaxNodeWrapper,
53{
54 pub(crate) fn cast<U>(this: TreeArc<T>) -> TreeArc<U>
55 where
56 U: SyntaxNodeWrapper,
57 {
58 TreeArc(rowan::TreeArc::cast(this.0))
59 }
60}
61
62impl<T> std::ops::Deref for TreeArc<T>
63where
64 T: SyntaxNodeWrapper,
65{
66 type Target = T;
67 fn deref(&self) -> &T {
68 self.0.deref()
69 }
70}
71
72impl<T> PartialEq<T> for TreeArc<T>
73where
74 T: SyntaxNodeWrapper,
75 T: PartialEq<T>,
76{
77 fn eq(&self, other: &T) -> bool {
78 let t: &T = self;
79 t == other
80 }
81}
82
83impl<T> Clone for TreeArc<T>
84where
85 T: SyntaxNodeWrapper,
86{
87 fn clone(&self) -> TreeArc<T> {
88 TreeArc(self.0.clone())
89 }
90}
91
92impl<T> fmt::Debug for TreeArc<T>
93where
94 T: SyntaxNodeWrapper,
95 T: fmt::Debug,
96{
97 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
98 fmt::Debug::fmt(&self.0, fmt)
99 }
100}
101
102#[derive(PartialEq, Eq, Hash)]
103#[repr(transparent)]
104pub struct SyntaxNode(pub(crate) rowan::SyntaxNode);
105unsafe impl TransparentNewType for SyntaxNode {
106 type Repr = rowan::SyntaxNode;
107}
108
109impl ToOwned for SyntaxNode {
110 type Owned = TreeArc<SyntaxNode>;
111 fn to_owned(&self) -> TreeArc<SyntaxNode> {
112 let ptr = TreeArc(self.0.to_owned());
113 TreeArc::cast(ptr)
114 }
115}
116 37
117impl fmt::Debug for SyntaxNode { 38impl fmt::Debug for SyntaxNode {
118 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 39 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
@@ -133,9 +54,9 @@ pub enum Direction {
133} 54}
134 55
135impl SyntaxNode { 56impl SyntaxNode {
136 pub(crate) fn new(green: GreenNode) -> TreeArc<SyntaxNode> { 57 pub(crate) fn new(green: GreenNode) -> SyntaxNode {
137 let ptr = TreeArc(rowan::SyntaxNode::new(green, None)); 58 let inner = rowan::cursor::SyntaxNode::new_root(green);
138 TreeArc::cast(ptr) 59 SyntaxNode(inner)
139 } 60 }
140 61
141 pub fn kind(&self) -> SyntaxKind { 62 pub fn kind(&self) -> SyntaxKind {
@@ -143,47 +64,47 @@ impl SyntaxNode {
143 } 64 }
144 65
145 pub fn range(&self) -> TextRange { 66 pub fn range(&self) -> TextRange {
146 self.0.range() 67 self.0.text_range()
147 } 68 }
148 69
149 pub fn text(&self) -> SyntaxText { 70 pub fn text(&self) -> SyntaxText {
150 SyntaxText::new(self) 71 SyntaxText::new(self)
151 } 72 }
152 73
153 pub fn parent(&self) -> Option<&SyntaxNode> { 74 pub fn parent(&self) -> Option<SyntaxNode> {
154 self.0.parent().map(SyntaxNode::from_repr) 75 self.0.parent().map(SyntaxNode)
155 } 76 }
156 77
157 pub fn first_child(&self) -> Option<&SyntaxNode> { 78 pub fn first_child(&self) -> Option<SyntaxNode> {
158 self.0.first_child().map(SyntaxNode::from_repr) 79 self.0.first_child().map(SyntaxNode)
159 } 80 }
160 81
161 pub fn first_child_or_token(&self) -> Option<SyntaxElement> { 82 pub fn first_child_or_token(&self) -> Option<SyntaxElement> {
162 self.0.first_child_or_token().map(SyntaxElement::from) 83 self.0.first_child_or_token().map(SyntaxElement::new)
163 } 84 }
164 85
165 pub fn last_child(&self) -> Option<&SyntaxNode> { 86 pub fn last_child(&self) -> Option<SyntaxNode> {
166 self.0.last_child().map(SyntaxNode::from_repr) 87 self.0.last_child().map(SyntaxNode)
167 } 88 }
168 89
169 pub fn last_child_or_token(&self) -> Option<SyntaxElement> { 90 pub fn last_child_or_token(&self) -> Option<SyntaxElement> {
170 self.0.last_child_or_token().map(SyntaxElement::from) 91 self.0.last_child_or_token().map(SyntaxElement::new)
171 } 92 }
172 93
173 pub fn next_sibling(&self) -> Option<&SyntaxNode> { 94 pub fn next_sibling(&self) -> Option<SyntaxNode> {
174 self.0.next_sibling().map(SyntaxNode::from_repr) 95 self.0.next_sibling().map(SyntaxNode)
175 } 96 }
176 97
177 pub fn next_sibling_or_token(&self) -> Option<SyntaxElement> { 98 pub fn next_sibling_or_token(&self) -> Option<SyntaxElement> {
178 self.0.next_sibling_or_token().map(SyntaxElement::from) 99 self.0.next_sibling_or_token().map(SyntaxElement::new)
179 } 100 }
180 101
181 pub fn prev_sibling(&self) -> Option<&SyntaxNode> { 102 pub fn prev_sibling(&self) -> Option<SyntaxNode> {
182 self.0.prev_sibling().map(SyntaxNode::from_repr) 103 self.0.prev_sibling().map(SyntaxNode)
183 } 104 }
184 105
185 pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement> { 106 pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement> {
186 self.0.prev_sibling_or_token().map(SyntaxElement::from) 107 self.0.prev_sibling_or_token().map(SyntaxElement::new)
187 } 108 }
188 109
189 pub fn children(&self) -> SyntaxNodeChildren { 110 pub fn children(&self) -> SyntaxNodeChildren {
@@ -195,18 +116,18 @@ impl SyntaxNode {
195 } 116 }
196 117
197 pub fn first_token(&self) -> Option<SyntaxToken> { 118 pub fn first_token(&self) -> Option<SyntaxToken> {
198 self.0.first_token().map(SyntaxToken::from) 119 self.0.first_token().map(SyntaxToken)
199 } 120 }
200 121
201 pub fn last_token(&self) -> Option<SyntaxToken> { 122 pub fn last_token(&self) -> Option<SyntaxToken> {
202 self.0.last_token().map(SyntaxToken::from) 123 self.0.last_token().map(SyntaxToken)
203 } 124 }
204 125
205 pub fn ancestors(&self) -> impl Iterator<Item = &SyntaxNode> { 126 pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode> {
206 successors(Some(self), |&node| node.parent()) 127 successors(Some(self.clone()), |node| node.parent())
207 } 128 }
208 129
209 pub fn descendants(&self) -> impl Iterator<Item = &SyntaxNode> { 130 pub fn descendants(&self) -> impl Iterator<Item = SyntaxNode> {
210 self.preorder().filter_map(|event| match event { 131 self.preorder().filter_map(|event| match event {
211 WalkEvent::Enter(node) => Some(node), 132 WalkEvent::Enter(node) => Some(node),
212 WalkEvent::Leave(_) => None, 133 WalkEvent::Leave(_) => None,
@@ -220,8 +141,8 @@ impl SyntaxNode {
220 }) 141 })
221 } 142 }
222 143
223 pub fn siblings(&self, direction: Direction) -> impl Iterator<Item = &SyntaxNode> { 144 pub fn siblings(&self, direction: Direction) -> impl Iterator<Item = SyntaxNode> {
224 successors(Some(self), move |&node| match direction { 145 successors(Some(self.clone()), move |node| match direction {
225 Direction::Next => node.next_sibling(), 146 Direction::Next => node.next_sibling(),
226 Direction::Prev => node.prev_sibling(), 147 Direction::Prev => node.prev_sibling(),
227 }) 148 })
@@ -231,29 +152,29 @@ impl SyntaxNode {
231 &self, 152 &self,
232 direction: Direction, 153 direction: Direction,
233 ) -> impl Iterator<Item = SyntaxElement> { 154 ) -> impl Iterator<Item = SyntaxElement> {
234 let me: SyntaxElement = self.into(); 155 let me: SyntaxElement = self.clone().into();
235 successors(Some(me), move |el| match direction { 156 successors(Some(me), move |el| match direction {
236 Direction::Next => el.next_sibling_or_token(), 157 Direction::Next => el.next_sibling_or_token(),
237 Direction::Prev => el.prev_sibling_or_token(), 158 Direction::Prev => el.prev_sibling_or_token(),
238 }) 159 })
239 } 160 }
240 161
241 pub fn preorder(&self) -> impl Iterator<Item = WalkEvent<&SyntaxNode>> { 162 pub fn preorder(&self) -> impl Iterator<Item = WalkEvent<SyntaxNode>> {
242 self.0.preorder().map(|event| match event { 163 self.0.preorder().map(|event| match event {
243 WalkEvent::Enter(n) => WalkEvent::Enter(SyntaxNode::from_repr(n)), 164 WalkEvent::Enter(n) => WalkEvent::Enter(SyntaxNode(n)),
244 WalkEvent::Leave(n) => WalkEvent::Leave(SyntaxNode::from_repr(n)), 165 WalkEvent::Leave(n) => WalkEvent::Leave(SyntaxNode(n)),
245 }) 166 })
246 } 167 }
247 168
248 pub fn preorder_with_tokens(&self) -> impl Iterator<Item = WalkEvent<SyntaxElement>> { 169 pub fn preorder_with_tokens(&self) -> impl Iterator<Item = WalkEvent<SyntaxElement>> {
249 self.0.preorder_with_tokens().map(|event| match event { 170 self.0.preorder_with_tokens().map(|event| match event {
250 WalkEvent::Enter(n) => WalkEvent::Enter(n.into()), 171 WalkEvent::Enter(n) => WalkEvent::Enter(SyntaxElement::new(n)),
251 WalkEvent::Leave(n) => WalkEvent::Leave(n.into()), 172 WalkEvent::Leave(n) => WalkEvent::Leave(SyntaxElement::new(n)),
252 }) 173 })
253 } 174 }
254 175
255 pub fn memory_size_of_subtree(&self) -> usize { 176 pub fn memory_size_of_subtree(&self) -> usize {
256 self.0.memory_size_of_subtree() 177 0
257 } 178 }
258 179
259 pub fn debug_dump(&self) -> String { 180 pub fn debug_dump(&self) -> String {
@@ -290,11 +211,11 @@ impl SyntaxNode {
290 /// 211 ///
291 /// This is a type-unsafe low-level editing API, if you need to use it, 212 /// This is a type-unsafe low-level editing API, if you need to use it,
292 /// prefer to create a type-safe abstraction on top of it instead. 213 /// prefer to create a type-safe abstraction on top of it instead.
293 pub fn insert_children<'a>( 214 pub fn insert_children(
294 &self, 215 &self,
295 position: InsertPosition<SyntaxElement<'_>>, 216 position: InsertPosition<SyntaxElement>,
296 to_insert: impl Iterator<Item = SyntaxElement<'a>>, 217 to_insert: impl Iterator<Item = SyntaxElement>,
297 ) -> TreeArc<SyntaxNode> { 218 ) -> SyntaxNode {
298 let mut delta = TextUnit::default(); 219 let mut delta = TextUnit::default();
299 let to_insert = to_insert.map(|element| { 220 let to_insert = to_insert.map(|element| {
300 delta += element.text_len(); 221 delta += element.text_len();
@@ -303,7 +224,7 @@ impl SyntaxNode {
303 224
304 let old_children = self.0.green().children(); 225 let old_children = self.0.green().children();
305 226
306 let new_children = match position { 227 let new_children = match &position {
307 InsertPosition::First => { 228 InsertPosition::First => {
308 to_insert.chain(old_children.iter().cloned()).collect::<Box<[_]>>() 229 to_insert.chain(old_children.iter().cloned()).collect::<Box<[_]>>()
309 } 230 }
@@ -312,7 +233,7 @@ impl SyntaxNode {
312 } 233 }
313 InsertPosition::Before(anchor) | InsertPosition::After(anchor) => { 234 InsertPosition::Before(anchor) | InsertPosition::After(anchor) => {
314 let take_anchor = if let InsertPosition::After(_) = position { 1 } else { 0 }; 235 let take_anchor = if let InsertPosition::After(_) = position { 1 } else { 0 };
315 let split_at = self.position_of_child(anchor) + take_anchor; 236 let split_at = self.position_of_child(anchor.clone()) + take_anchor;
316 let (before, after) = old_children.split_at(split_at); 237 let (before, after) = old_children.split_at(split_at);
317 before 238 before
318 .iter() 239 .iter()
@@ -330,13 +251,13 @@ impl SyntaxNode {
330 /// 251 ///
331 /// This is a type-unsafe low-level editing API, if you need to use it, 252 /// This is a type-unsafe low-level editing API, if you need to use it,
332 /// prefer to create a type-safe abstraction on top of it instead. 253 /// prefer to create a type-safe abstraction on top of it instead.
333 pub fn replace_children<'a>( 254 pub fn replace_children(
334 &self, 255 &self,
335 to_delete: RangeInclusive<SyntaxElement<'_>>, 256 to_delete: RangeInclusive<SyntaxElement>,
336 to_insert: impl Iterator<Item = SyntaxElement<'a>>, 257 to_insert: impl Iterator<Item = SyntaxElement>,
337 ) -> TreeArc<SyntaxNode> { 258 ) -> SyntaxNode {
338 let start = self.position_of_child(*to_delete.start()); 259 let start = self.position_of_child(to_delete.start().clone());
339 let end = self.position_of_child(*to_delete.end()); 260 let end = self.position_of_child(to_delete.end().clone());
340 let old_children = self.0.green().children(); 261 let old_children = self.0.green().children();
341 262
342 let new_children = old_children[..start] 263 let new_children = old_children[..start]
@@ -348,7 +269,7 @@ impl SyntaxNode {
348 self.with_children(new_children) 269 self.with_children(new_children)
349 } 270 }
350 271
351 fn with_children(&self, new_children: Box<[rowan::GreenElement]>) -> TreeArc<SyntaxNode> { 272 fn with_children(&self, new_children: Box<[rowan::GreenElement]>) -> SyntaxNode {
352 let len = new_children.iter().map(|it| it.text_len()).sum::<TextUnit>(); 273 let len = new_children.iter().map(|it| it.text_len()).sum::<TextUnit>();
353 let new_node = GreenNode::new(rowan::SyntaxKind(self.kind() as u16), new_children); 274 let new_node = GreenNode::new(rowan::SyntaxKind(self.kind() as u16), new_children);
354 let new_file_node = self.replace_with(new_node); 275 let new_file_node = self.replace_with(new_node);
@@ -364,7 +285,7 @@ impl SyntaxNode {
364 fn position_of_child(&self, child: SyntaxElement) -> usize { 285 fn position_of_child(&self, child: SyntaxElement) -> usize {
365 self.children_with_tokens() 286 self.children_with_tokens()
366 .position(|it| it == child) 287 .position(|it| it == child)
367 .expect("elemetn is not a child of current element") 288 .expect("element is not a child of current element")
368 } 289 }
369} 290}
370 291
@@ -377,11 +298,11 @@ fn to_green_element(element: SyntaxElement) -> rowan::GreenElement {
377 } 298 }
378} 299}
379 300
380#[derive(Clone, Copy, PartialEq, Eq, Hash)] 301#[derive(Clone, PartialEq, Eq, Hash)]
381pub struct SyntaxToken<'a>(pub(crate) rowan::SyntaxToken<'a>); 302pub struct SyntaxToken(pub(crate) rowan::cursor::SyntaxToken);
382 303
383//FIXME: always output text 304//FIXME: always output text
384impl<'a> fmt::Debug for SyntaxToken<'a> { 305impl fmt::Debug for SyntaxToken {
385 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 306 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
386 write!(fmt, "{:?}@{:?}", self.kind(), self.range())?; 307 write!(fmt, "{:?}@{:?}", self.kind(), self.range())?;
387 if self.text().len() < 25 { 308 if self.text().len() < 25 {
@@ -398,60 +319,54 @@ impl<'a> fmt::Debug for SyntaxToken<'a> {
398 } 319 }
399} 320}
400 321
401impl<'a> fmt::Display for SyntaxToken<'a> { 322impl fmt::Display for SyntaxToken {
402 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 323 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
403 fmt::Display::fmt(self.text(), fmt) 324 fmt::Display::fmt(self.text(), fmt)
404 } 325 }
405} 326}
406 327
407impl<'a> From<rowan::SyntaxToken<'a>> for SyntaxToken<'a> { 328impl SyntaxToken {
408 fn from(t: rowan::SyntaxToken<'a>) -> Self {
409 SyntaxToken(t)
410 }
411}
412
413impl<'a> SyntaxToken<'a> {
414 pub fn kind(&self) -> SyntaxKind { 329 pub fn kind(&self) -> SyntaxKind {
415 self.0.kind().0.into() 330 self.0.kind().0.into()
416 } 331 }
417 332
418 pub fn text(&self) -> &'a SmolStr { 333 pub fn text(&self) -> &SmolStr {
419 self.0.text() 334 self.0.text()
420 } 335 }
421 336
422 pub fn range(&self) -> TextRange { 337 pub fn range(&self) -> TextRange {
423 self.0.range() 338 self.0.text_range()
424 } 339 }
425 340
426 pub fn parent(&self) -> &'a SyntaxNode { 341 pub fn parent(&self) -> SyntaxNode {
427 SyntaxNode::from_repr(self.0.parent()) 342 SyntaxNode(self.0.parent())
428 } 343 }
429 344
430 pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<'a>> { 345 pub fn next_sibling_or_token(&self) -> Option<SyntaxElement> {
431 self.0.next_sibling_or_token().map(SyntaxElement::from) 346 self.0.next_sibling_or_token().map(SyntaxElement::new)
432 } 347 }
433 348
434 pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<'a>> { 349 pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement> {
435 self.0.prev_sibling_or_token().map(SyntaxElement::from) 350 self.0.prev_sibling_or_token().map(SyntaxElement::new)
436 } 351 }
437 352
438 pub fn siblings_with_tokens( 353 pub fn siblings_with_tokens(
439 &self, 354 &self,
440 direction: Direction, 355 direction: Direction,
441 ) -> impl Iterator<Item = SyntaxElement<'a>> { 356 ) -> impl Iterator<Item = SyntaxElement> {
442 let me: SyntaxElement = (*self).into(); 357 let me: SyntaxElement = self.clone().into();
443 successors(Some(me), move |el| match direction { 358 successors(Some(me), move |el| match direction {
444 Direction::Next => el.next_sibling_or_token(), 359 Direction::Next => el.next_sibling_or_token(),
445 Direction::Prev => el.prev_sibling_or_token(), 360 Direction::Prev => el.prev_sibling_or_token(),
446 }) 361 })
447 } 362 }
448 363
449 pub fn next_token(&self) -> Option<SyntaxToken<'a>> { 364 pub fn next_token(&self) -> Option<SyntaxToken> {
450 self.0.next_token().map(SyntaxToken::from) 365 self.0.next_token().map(SyntaxToken)
451 } 366 }
452 367
453 pub fn prev_token(&self) -> Option<SyntaxToken<'a>> { 368 pub fn prev_token(&self) -> Option<SyntaxToken> {
454 self.0.prev_token().map(SyntaxToken::from) 369 self.0.prev_token().map(SyntaxToken)
455 } 370 }
456 371
457 pub(crate) fn replace_with(&self, new_token: GreenToken) -> GreenNode { 372 pub(crate) fn replace_with(&self, new_token: GreenToken) -> GreenNode {
@@ -459,13 +374,25 @@ impl<'a> SyntaxToken<'a> {
459 } 374 }
460} 375}
461 376
462#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] 377#[derive(Debug, PartialEq, Eq, Hash, Clone)]
463pub enum SyntaxElement<'a> { 378pub enum SyntaxElement {
464 Node(&'a SyntaxNode), 379 Node(SyntaxNode),
465 Token(SyntaxToken<'a>), 380 Token(SyntaxToken),
466} 381}
467 382
468impl<'a> fmt::Display for SyntaxElement<'a> { 383impl From<SyntaxNode> for SyntaxElement {
384 fn from(node: SyntaxNode) -> Self {
385 SyntaxElement::Node(node)
386 }
387}
388
389impl From<SyntaxToken> for SyntaxElement {
390 fn from(token: SyntaxToken) -> Self {
391 SyntaxElement::Token(token)
392 }
393}
394
395impl fmt::Display for SyntaxElement {
469 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 396 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
470 match self { 397 match self {
471 SyntaxElement::Node(it) => fmt::Display::fmt(it, fmt), 398 SyntaxElement::Node(it) => fmt::Display::fmt(it, fmt),
@@ -474,7 +401,14 @@ impl<'a> fmt::Display for SyntaxElement<'a> {
474 } 401 }
475} 402}
476 403
477impl<'a> SyntaxElement<'a> { 404impl SyntaxElement {
405 pub(crate) fn new(el: rowan::cursor::SyntaxElement) -> Self {
406 match el {
407 rowan::cursor::SyntaxElement::Node(it) => SyntaxElement::Node(SyntaxNode(it)),
408 rowan::cursor::SyntaxElement::Token(it) => SyntaxElement::Token(SyntaxToken(it)),
409 }
410 }
411
478 pub fn kind(&self) -> SyntaxKind { 412 pub fn kind(&self) -> SyntaxKind {
479 match self { 413 match self {
480 SyntaxElement::Node(it) => it.kind(), 414 SyntaxElement::Node(it) => it.kind(),
@@ -482,99 +416,74 @@ impl<'a> SyntaxElement<'a> {
482 } 416 }
483 } 417 }
484 418
485 pub fn as_node(&self) -> Option<&'a SyntaxNode> { 419 pub fn as_node(&self) -> Option<&SyntaxNode> {
486 match self { 420 match self {
487 SyntaxElement::Node(node) => Some(*node), 421 SyntaxElement::Node(node) => Some(node),
488 SyntaxElement::Token(_) => None, 422 SyntaxElement::Token(_) => None,
489 } 423 }
490 } 424 }
491 425
492 pub fn as_token(&self) -> Option<SyntaxToken<'a>> { 426 pub fn as_token(&self) -> Option<&SyntaxToken> {
493 match self { 427 match self {
494 SyntaxElement::Node(_) => None, 428 SyntaxElement::Node(_) => None,
495 SyntaxElement::Token(token) => Some(*token), 429 SyntaxElement::Token(token) => Some(token),
496 } 430 }
497 } 431 }
498 432
499 pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<'a>> { 433 pub fn next_sibling_or_token(&self) -> Option<SyntaxElement> {
500 match self { 434 match self {
501 SyntaxElement::Node(it) => it.next_sibling_or_token(), 435 SyntaxElement::Node(it) => it.next_sibling_or_token(),
502 SyntaxElement::Token(it) => it.next_sibling_or_token(), 436 SyntaxElement::Token(it) => it.next_sibling_or_token(),
503 } 437 }
504 } 438 }
505 439
506 pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<'a>> { 440 pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement> {
507 match self { 441 match self {
508 SyntaxElement::Node(it) => it.prev_sibling_or_token(), 442 SyntaxElement::Node(it) => it.prev_sibling_or_token(),
509 SyntaxElement::Token(it) => it.prev_sibling_or_token(), 443 SyntaxElement::Token(it) => it.prev_sibling_or_token(),
510 } 444 }
511 } 445 }
512 446
513 pub fn ancestors(&self) -> impl Iterator<Item = &'a SyntaxNode> { 447 pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode> {
514 match self { 448 match self {
515 SyntaxElement::Node(it) => it, 449 SyntaxElement::Node(it) => it.clone(),
516 SyntaxElement::Token(it) => it.parent(), 450 SyntaxElement::Token(it) => it.parent(),
517 } 451 }
518 .ancestors() 452 .ancestors()
519 } 453 }
520 454
521 fn text_len(&self) -> TextUnit { 455 pub fn range(&self) -> TextRange {
522 match self { 456 match self {
523 SyntaxElement::Node(node) => node.0.green().text_len(), 457 SyntaxElement::Node(it) => it.range(),
524 SyntaxElement::Token(token) => TextUnit::of_str(token.0.text()), 458 SyntaxElement::Token(it) => it.range(),
525 }
526 }
527}
528
529impl<'a> From<rowan::SyntaxElement<'a>> for SyntaxElement<'a> {
530 fn from(el: rowan::SyntaxElement<'a>) -> Self {
531 match el {
532 rowan::SyntaxElement::Node(n) => SyntaxElement::Node(SyntaxNode::from_repr(n)),
533 rowan::SyntaxElement::Token(t) => SyntaxElement::Token(t.into()),
534 } 459 }
535 } 460 }
536}
537
538impl<'a> From<&'a SyntaxNode> for SyntaxElement<'a> {
539 fn from(node: &'a SyntaxNode) -> SyntaxElement<'a> {
540 SyntaxElement::Node(node)
541 }
542}
543
544impl<'a> From<SyntaxToken<'a>> for SyntaxElement<'a> {
545 fn from(token: SyntaxToken<'a>) -> SyntaxElement<'a> {
546 SyntaxElement::Token(token)
547 }
548}
549 461
550impl<'a> SyntaxElement<'a> { 462 fn text_len(&self) -> TextUnit {
551 pub fn range(&self) -> TextRange {
552 match self { 463 match self {
553 SyntaxElement::Node(it) => it.range(), 464 SyntaxElement::Node(node) => node.0.green().text_len(),
554 SyntaxElement::Token(it) => it.range(), 465 SyntaxElement::Token(token) => TextUnit::of_str(token.0.text()),
555 } 466 }
556 } 467 }
557} 468}
558 469
559#[derive(Debug)] 470#[derive(Clone, Debug)]
560pub struct SyntaxNodeChildren<'a>(rowan::SyntaxNodeChildren<'a>); 471pub struct SyntaxNodeChildren(rowan::cursor::SyntaxNodeChildren);
561 472
562impl<'a> Iterator for SyntaxNodeChildren<'a> { 473impl Iterator for SyntaxNodeChildren {
563 type Item = &'a SyntaxNode; 474 type Item = SyntaxNode;
564 475 fn next(&mut self) -> Option<SyntaxNode> {
565 fn next(&mut self) -> Option<&'a SyntaxNode> { 476 self.0.next().map(SyntaxNode)
566 self.0.next().map(SyntaxNode::from_repr)
567 } 477 }
568} 478}
569 479
570#[derive(Debug)] 480#[derive(Clone, Debug)]
571pub struct SyntaxElementChildren<'a>(rowan::SyntaxElementChildren<'a>); 481pub struct SyntaxElementChildren(rowan::cursor::SyntaxElementChildren);
572
573impl<'a> Iterator for SyntaxElementChildren<'a> {
574 type Item = SyntaxElement<'a>;
575 482
576 fn next(&mut self) -> Option<SyntaxElement<'a>> { 483impl Iterator for SyntaxElementChildren {
577 self.0.next().map(SyntaxElement::from) 484 type Item = SyntaxElement;
485 fn next(&mut self) -> Option<SyntaxElement> {
486 self.0.next().map(SyntaxElement::new)
578 } 487 }
579} 488}
580 489
@@ -601,7 +510,7 @@ impl SyntaxTreeBuilder {
601 if cfg!(debug_assertions) { 510 if cfg!(debug_assertions) {
602 crate::validation::validate_block_structure(&node); 511 crate::validation::validate_block_structure(&node);
603 } 512 }
604 Parse::new(node, errors) 513 Parse::new(node.0.green().clone(), errors)
605 } 514 }
606 515
607 pub fn token(&mut self, kind: SyntaxKind, text: SmolStr) { 516 pub fn token(&mut self, kind: SyntaxKind, text: SmolStr) {
diff --git a/crates/ra_syntax/src/syntax_text.rs b/crates/ra_syntax/src/syntax_text.rs
index 939f2c02f..6902a04a2 100644
--- a/crates/ra_syntax/src/syntax_text.rs
+++ b/crates/ra_syntax/src/syntax_text.rs
@@ -16,29 +16,36 @@ impl<'a> SyntaxText<'a> {
16 SyntaxText { node, range: node.range() } 16 SyntaxText { node, range: node.range() }
17 } 17 }
18 18
19 pub fn chunks(&self) -> impl Iterator<Item = &'a str> { 19 pub fn chunks(&self) -> impl Iterator<Item = SmolStr> {
20 let range = self.range; 20 let range = self.range;
21 self.node.descendants_with_tokens().filter_map(move |el| match el { 21 self.node.descendants_with_tokens().filter_map(move |el| match el {
22 SyntaxElement::Token(t) => { 22 SyntaxElement::Token(t) => {
23 let text = t.text(); 23 let text = t.text();
24 let range = range.intersection(&t.range())?; 24 let range = range.intersection(&t.range())?;
25 let range = range - t.range().start(); 25 let res = if range == t.range() {
26 Some(&text[range]) 26 t.text().clone()
27 } else {
28 let range = range - t.range().start();
29 text[range].into()
30 };
31 Some(res)
27 } 32 }
28 SyntaxElement::Node(_) => None, 33 SyntaxElement::Node(_) => None,
29 }) 34 })
30 } 35 }
31 36
32 pub fn push_to(&self, buf: &mut String) { 37 pub fn push_to(&self, buf: &mut String) {
33 self.chunks().for_each(|it| buf.push_str(it)); 38 self.chunks().for_each(|it| buf.push_str(it.as_str()));
34 } 39 }
35 40
36 pub fn to_string(&self) -> String { 41 pub fn to_string(&self) -> String {
37 self.chunks().collect() 42 let mut buf = String::new();
43 self.push_to(&mut buf);
44 buf
38 } 45 }
39 46
40 pub fn to_smol_string(&self) -> SmolStr { 47 pub fn to_smol_string(&self) -> SmolStr {
41 self.chunks().collect() 48 self.to_string().into()
42 } 49 }
43 50
44 pub fn contains(&self, c: char) -> bool { 51 pub fn contains(&self, c: char) -> bool {
@@ -52,7 +59,7 @@ impl<'a> SyntaxText<'a> {
52 let pos: TextUnit = (pos as u32).into(); 59 let pos: TextUnit = (pos as u32).into();
53 return Some(acc + pos); 60 return Some(acc + pos);
54 } 61 }
55 acc += TextUnit::of_str(chunk); 62 acc += TextUnit::of_str(chunk.as_str());
56 } 63 }
57 None 64 None
58 } 65 }
@@ -97,7 +104,7 @@ impl<'a> SyntaxText<'a> {
97 let mut start: TextUnit = 0.into(); 104 let mut start: TextUnit = 0.into();
98 let offset = offset.into(); 105 let offset = offset.into();
99 for chunk in self.chunks() { 106 for chunk in self.chunks() {
100 let end = start + TextUnit::of_str(chunk); 107 let end = start + TextUnit::of_str(chunk.as_str());
101 if start <= offset && offset < end { 108 if start <= offset && offset < end {
102 let off: usize = u32::from(offset - start) as usize; 109 let off: usize = u32::from(offset - start) as usize;
103 return Some(chunk[off..].chars().next().unwrap()); 110 return Some(chunk[off..].chars().next().unwrap());
@@ -129,7 +136,7 @@ impl From<SyntaxText<'_>> for String {
129impl PartialEq<str> for SyntaxText<'_> { 136impl PartialEq<str> for SyntaxText<'_> {
130 fn eq(&self, mut rhs: &str) -> bool { 137 fn eq(&self, mut rhs: &str) -> bool {
131 for chunk in self.chunks() { 138 for chunk in self.chunks() {
132 if !rhs.starts_with(chunk) { 139 if !rhs.starts_with(chunk.as_str()) {
133 return false; 140 return false;
134 } 141 }
135 rhs = &rhs[chunk.len()..]; 142 rhs = &rhs[chunk.len()..];
diff --git a/crates/ra_syntax/src/validation.rs b/crates/ra_syntax/src/validation.rs
index 87522ec18..7140d10c3 100644
--- a/crates/ra_syntax/src/validation.rs
+++ b/crates/ra_syntax/src/validation.rs
@@ -19,13 +19,13 @@ pub(crate) fn validate(file: &SourceFile) -> Vec<SyntaxError> {
19 .visit::<ast::Literal, _>(validate_literal) 19 .visit::<ast::Literal, _>(validate_literal)
20 .visit::<ast::Block, _>(block::validate_block_node) 20 .visit::<ast::Block, _>(block::validate_block_node)
21 .visit::<ast::FieldExpr, _>(field_expr::validate_field_expr_node) 21 .visit::<ast::FieldExpr, _>(field_expr::validate_field_expr_node)
22 .accept(node); 22 .accept(&node);
23 } 23 }
24 errors 24 errors
25} 25}
26 26
27// FIXME: kill duplication 27// FIXME: kill duplication
28fn validate_literal(literal: &ast::Literal, acc: &mut Vec<SyntaxError>) { 28fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
29 let token = literal.token(); 29 let token = literal.token();
30 let text = token.text().as_str(); 30 let text = token.text().as_str();
31 match token.kind() { 31 match token.kind() {
diff --git a/crates/ra_syntax/src/validation/block.rs b/crates/ra_syntax/src/validation/block.rs
index 46650d9b0..f5573bd8f 100644
--- a/crates/ra_syntax/src/validation/block.rs
+++ b/crates/ra_syntax/src/validation/block.rs
@@ -5,7 +5,7 @@ use crate::{
5 SyntaxKind::*, 5 SyntaxKind::*,
6}; 6};
7 7
8pub(crate) fn validate_block_node(node: &ast::Block, errors: &mut Vec<SyntaxError>) { 8pub(crate) fn validate_block_node(node: ast::Block, errors: &mut Vec<SyntaxError>) {
9 if let Some(parent) = node.syntax().parent() { 9 if let Some(parent) = node.syntax().parent() {
10 match parent.kind() { 10 match parent.kind() {
11 FN_DEF => return, 11 FN_DEF => return,
diff --git a/crates/ra_syntax/src/validation/field_expr.rs b/crates/ra_syntax/src/validation/field_expr.rs
index d3020edf7..0e18bd9ca 100644
--- a/crates/ra_syntax/src/validation/field_expr.rs
+++ b/crates/ra_syntax/src/validation/field_expr.rs
@@ -4,7 +4,7 @@ use crate::{
4 SyntaxErrorKind::*, 4 SyntaxErrorKind::*,
5}; 5};
6 6
7pub(crate) fn validate_field_expr_node(node: &ast::FieldExpr, errors: &mut Vec<SyntaxError>) { 7pub(crate) fn validate_field_expr_node(node: ast::FieldExpr, errors: &mut Vec<SyntaxError>) {
8 if let Some(FieldKind::Index(idx)) = node.field_access() { 8 if let Some(FieldKind::Index(idx)) = node.field_access() {
9 if idx.text().chars().any(|c| c < '0' || c > '9') { 9 if idx.text().chars().any(|c| c < '0' || c > '9') {
10 errors.push(SyntaxError::new(InvalidTupleIndexFormat, idx.range())); 10 errors.push(SyntaxError::new(InvalidTupleIndexFormat, idx.range()));