1use std::cell::OnceCell;
4
5use base_db::{Crate, FxIndexSet, SourceDatabase};
6use cfg::CfgOptions;
7use either::Either;
8use hir_expand::{HirFileId, mod_path::PathKind, name::AsName, span_map::SpanMap};
9use la_arena::Arena;
10use rustc_hash::FxHashSet;
11use span::{AstIdMap, FileAstId, SyntaxContext};
12use syntax::{
13 AstNode,
14 ast::{self, HasModuleItem, HasName},
15};
16
17use crate::item_tree::{
18 BigModItem, Const, Enum, ExternBlock, ExternCrate, Function, Impl, ImportAlias, Interned,
19 ItemTree, Macro2, MacroCall, MacroRules, Mod, ModItemId, ModKind, ModPath, RawVisibility,
20 RawVisibilityId, SmallModItem, Static, Struct, StructKind, StructValueNsCtor, Trait, TypeAlias,
21 Union, Use, UseTree, UseTreeKind, VisibilityExplicitness, attrs::AttrsOrCfg,
22};
23
24pub(super) struct Ctx<'db> {
25 pub(super) db: &'db dyn SourceDatabase,
26 tree: ItemTree,
27 source_ast_id_map: &'db AstIdMap,
28 span_map: OnceCell<SpanMap<'db>>,
29 file: HirFileId,
30 cfg_options: OnceCell<&'db CfgOptions>,
31 krate: Crate,
32 top_level: Vec<ModItemId>,
33 visibilities: FxIndexSet<RawVisibility>,
34}
35
36impl<'db> Ctx<'db> {
37 pub(super) fn new(db: &'db dyn SourceDatabase, file: HirFileId, krate: Crate) -> Self {
38 Self {
39 db,
40 tree: ItemTree::default(),
41 source_ast_id_map: file.ast_id_map(db),
42 file,
43 cfg_options: OnceCell::new(),
44 span_map: OnceCell::new(),
45 visibilities: FxIndexSet::default(),
46 top_level: Vec::new(),
47 krate,
48 }
49 }
50
51 #[inline]
52 pub(super) fn cfg_options(&self) -> &'db CfgOptions {
53 self.cfg_options.get_or_init(|| self.krate.cfg_options(self.db))
54 }
55
56 pub(super) fn span_map(&self) -> SpanMap<'_> {
57 *self.span_map.get_or_init(|| self.file.span_map(self.db))
58 }
59
60 pub(super) fn lower_module_items(mut self, item_owner: &dyn HasModuleItem) -> ItemTree {
61 self.top_level = item_owner.items().filter_map(|item| self.lower_mod_item(&item)).collect();
62 self.tree.vis.arena = self.visibilities.into_iter().collect();
63 self.tree.top_level = self.top_level.into_boxed_slice();
64 self.tree
65 }
66
67 pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
68 self.top_level = stmts
69 .statements()
70 .filter_map(|stmt| {
71 match stmt {
72 ast::Stmt::Item(item) => Some(item),
73 ast::Stmt::ExprStmt(es) => match es.expr()? {
76 ast::Expr::MacroExpr(expr) => {
77 cov_mark::hit!(macro_call_in_macro_stmts_is_added_to_item_tree);
78 Some(expr.macro_call()?.into())
79 }
80 _ => None,
81 },
82 _ => None,
83 }
84 })
85 .filter_map(|item| self.lower_mod_item(&item))
86 .collect();
87
88 if let Some(ast::Expr::MacroExpr(tail_macro)) = stmts.expr()
89 && let Some(call) = tail_macro.macro_call()
90 {
91 cov_mark::hit!(macro_stmt_with_trailing_macro_expr);
92 if let Some(mod_item) = self.lower_mod_item(&call.into()) {
93 self.top_level.push(mod_item);
94 }
95 }
96
97 self.tree.vis.arena = self.visibilities.into_iter().collect();
98 self.tree.top_level = self.top_level.into_boxed_slice();
99 self.tree
100 }
101
102 pub(super) fn lower_block(mut self, block: &ast::BlockExpr) -> ItemTree {
103 self.add_attrs(ModItemId::TOP_OWNER, self.lower_attrs(block));
104 self.top_level = block
105 .statements()
106 .filter_map(|stmt| match stmt {
107 ast::Stmt::Item(item) => self.lower_mod_item(&item),
108 ast::Stmt::ExprStmt(es) => match es.expr()? {
111 ast::Expr::MacroExpr(expr) => self.lower_mod_item(&expr.macro_call()?.into()),
112 _ => None,
113 },
114 _ => None,
115 })
116 .collect();
117 if let Some(ast::Expr::MacroExpr(expr)) = block.tail_expr()
118 && let Some(call) = expr.macro_call()
119 && let Some(mod_item) = self.lower_mod_item(&call.into())
120 {
121 self.top_level.push(mod_item);
122 }
123 self.tree.vis.arena = self.visibilities.into_iter().collect();
124 self.tree.top_level = self.top_level.into_boxed_slice();
125 self.tree
126 }
127
128 fn lower_mod_item(&mut self, item: &ast::Item) -> Option<ModItemId> {
129 let mod_item = match item {
130 ast::Item::Struct(ast) => self.lower_struct(ast)?,
131 ast::Item::Union(ast) => self.lower_union(ast)?,
132 ast::Item::Enum(ast) => self.lower_enum(ast)?,
133 ast::Item::Fn(ast) => self.lower_function(ast)?,
134 ast::Item::TypeAlias(ast) => self.lower_type_alias(ast)?,
135 ast::Item::Static(ast) => self.lower_static(ast)?,
136 ast::Item::Const(ast) => self.lower_const(ast),
137 ast::Item::Module(ast) => self.lower_module(ast)?,
138 ast::Item::Trait(ast) => self.lower_trait(ast)?,
139 ast::Item::Impl(ast) => self.lower_impl(ast),
140 ast::Item::Use(ast) => self.lower_use(ast)?,
141 ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast)?,
142 ast::Item::MacroCall(ast) => self.lower_macro_call(ast)?,
143 ast::Item::MacroRules(ast) => self.lower_macro_rules(ast)?,
144 ast::Item::MacroDef(ast) => self.lower_macro_def(ast)?,
145 ast::Item::ExternBlock(ast) => self.lower_extern_block(ast),
146 ast::Item::AsmExpr(_) => return None,
148 };
149 let attrs = self.lower_attrs(item);
150 self.add_attrs(mod_item, attrs);
151
152 Some(mod_item)
153 }
154
155 pub(super) fn add_attrs(&mut self, item: ModItemId, attrs: AttrsOrCfg) {
156 if !attrs.is_empty() {
157 self.tree.attrs.push((item, attrs));
158 }
159 }
160
161 fn alloc_small(&mut self, ast_id: FileAstId<ast::Item>, item: SmallModItem) -> ModItemId {
162 let index = self.tree.small_data.len() as u32;
163 self.tree.small_data.push((ast_id, item));
164 ModItemId::new_small(index)
165 }
166
167 fn alloc_big(&mut self, ast_id: FileAstId<ast::Item>, item: BigModItem) -> ModItemId {
168 let index = self.tree.big_data.len() as u32;
169 self.tree.big_data.push((ast_id, item));
170 ModItemId::new_big(index)
171 }
172
173 fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<ModItemId> {
174 let visibility = self.lower_visibility_from_ast(strukt);
175 let visibility_id = self.alloc_visibility(visibility.clone());
176 let name = strukt.name()?.as_name();
177 let ast_id = self.source_ast_id_map.ast_id(strukt);
178 let value_ns_ctor = match strukt.kind() {
179 StructKind::Record(_) => StructValueNsCtor::NoValueNsCtor,
180 StructKind::Unit => StructValueNsCtor::ValueNsCtorWithVis(visibility_id),
181 StructKind::Tuple(fields) => self.tuple_struct_ctor_vis(visibility, fields),
182 };
183 let res = Struct { name, visibility: visibility_id, value_ns_ctor };
184 Some(self.alloc_big(ast_id.upcast(), BigModItem::Struct(res)))
185 }
186
187 fn tuple_struct_ctor_vis(
188 &mut self,
189 struct_vis: RawVisibility,
190 fields: ast::TupleFieldList,
191 ) -> StructValueNsCtor {
192 if let RawVisibility::PubSelf(_) = struct_vis {
193 return StructValueNsCtor::ValueNsCtorWithVis(self.alloc_visibility(struct_vis));
195 }
196
197 let mut value_ns_ctor_vis = Either::Left(struct_vis);
198 for field in fields.fields() {
199 let field_vis = self.lower_visibility_from_ast(&field);
200 match (&field_vis, &mut value_ns_ctor_vis) {
201 (RawVisibility::PubSelf(_), _) => {
202 value_ns_ctor_vis = Either::Left(field_vis);
204 break;
205 }
206 (_, Either::Left(RawVisibility::Public)) => {
207 value_ns_ctor_vis = Either::Left(field_vis);
209 }
210 (RawVisibility::Module(..), Either::Left(RawVisibility::PubCrate)) => {
211 value_ns_ctor_vis = Either::Left(field_vis);
213 }
214 (
215 RawVisibility::Public | RawVisibility::PubCrate,
216 Either::Right(_)
217 | Either::Left(RawVisibility::Module(..) | RawVisibility::PubCrate),
218 ) => {
219 }
221 (_, Either::Left(RawVisibility::PubSelf(_))) => {
222 unreachable!("we early-exit on `PubSelf`");
223 }
224 (RawVisibility::Module(..), Either::Left(RawVisibility::Module(..))) => {
225 let old_vis = match std::mem::replace(
226 &mut value_ns_ctor_vis,
227 Either::Left(RawVisibility::Public),
228 ) {
229 Either::Left(it) => it,
230 _ => unreachable!(),
231 };
232 let mut multiple = FxHashSet::default();
233 multiple.insert(old_vis);
234 multiple.insert(field_vis);
235 value_ns_ctor_vis = Either::Right(multiple);
236 }
237 (RawVisibility::Module(..), Either::Right(multiple)) => {
238 multiple.insert(field_vis);
239 }
240 }
241 }
242
243 match value_ns_ctor_vis {
244 Either::Left(vis) => StructValueNsCtor::ValueNsCtorWithVis(self.alloc_visibility(vis)),
245 Either::Right(multiple) => {
246 if multiple.len() == 1 {
247 StructValueNsCtor::ValueNsCtorWithVis(
248 self.alloc_visibility(multiple.into_iter().next().unwrap()),
249 )
250 } else {
251 StructValueNsCtor::ValueNsCtorWithMinVis(
252 multiple.into_iter().map(|vis| self.alloc_visibility(vis)).collect(),
253 )
254 }
255 }
256 }
257 }
258
259 fn lower_union(&mut self, union: &ast::Union) -> Option<ModItemId> {
260 let visibility = self.lower_visibility(union);
261 let name = union.name()?.as_name();
262 let ast_id = self.source_ast_id_map.ast_id(union);
263 let res = Union { name, visibility };
264 Some(self.alloc_small(ast_id.upcast(), SmallModItem::Union(res)))
265 }
266
267 fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<ModItemId> {
268 let visibility = self.lower_visibility(enum_);
269 let name = enum_.name()?.as_name();
270 let ast_id = self.source_ast_id_map.ast_id(enum_);
271 let res = Enum { name, visibility };
272 Some(self.alloc_small(ast_id.upcast(), SmallModItem::Enum(res)))
273 }
274
275 fn lower_function(&mut self, func: &ast::Fn) -> Option<ModItemId> {
276 let visibility = self.lower_visibility(func);
277 let name = func.name()?.as_name();
278
279 let ast_id = self.source_ast_id_map.ast_id(func);
280
281 let res = Function { name, visibility };
282
283 Some(self.alloc_small(ast_id.upcast(), SmallModItem::Function(res)))
284 }
285
286 fn lower_type_alias(&mut self, type_alias: &ast::TypeAlias) -> Option<ModItemId> {
287 let name = type_alias.name()?.as_name();
288 let visibility = self.lower_visibility(type_alias);
289 let ast_id = self.source_ast_id_map.ast_id(type_alias);
290 let res = TypeAlias { name, visibility };
291 Some(self.alloc_small(ast_id.upcast(), SmallModItem::TypeAlias(res)))
292 }
293
294 fn lower_static(&mut self, static_: &ast::Static) -> Option<ModItemId> {
295 let name = static_.name()?.as_name();
296 let visibility = self.lower_visibility(static_);
297 let ast_id = self.source_ast_id_map.ast_id(static_);
298 let res = Static { name, visibility };
299 Some(self.alloc_small(ast_id.upcast(), SmallModItem::Static(res)))
300 }
301
302 fn lower_const(&mut self, konst: &ast::Const) -> ModItemId {
303 let name = konst.name().map(|it| it.as_name());
304 let visibility = self.lower_visibility(konst);
305 let ast_id = self.source_ast_id_map.ast_id(konst);
306 let res = Const { name, visibility };
307 self.alloc_small(ast_id.upcast(), SmallModItem::Const(res))
308 }
309
310 fn lower_module(&mut self, module: &ast::Module) -> Option<ModItemId> {
311 let name = module.name()?.as_name();
312 let visibility = self.lower_visibility(module);
313 let kind = if module.semicolon_token().is_some() {
314 ModKind::Outline
315 } else {
316 ModKind::Inline {
317 items: module
318 .item_list()
319 .map(|list| {
320 list.items().filter_map(|item| self.lower_mod_item(&item)).collect()
321 })
322 .unwrap_or_else(|| {
323 cov_mark::hit!(name_res_works_for_broken_modules);
324 Box::new([]) as Box<[_]>
325 }),
326 }
327 };
328 let ast_id = self.source_ast_id_map.ast_id(module);
329 let res = Mod { name, visibility, kind };
330 Some(self.alloc_big(ast_id.upcast(), BigModItem::Mod(res)))
331 }
332
333 fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<ModItemId> {
334 let name = trait_def.name()?.as_name();
335 let visibility = self.lower_visibility(trait_def);
336 let ast_id = self.source_ast_id_map.ast_id(trait_def);
337
338 let def = Trait { name, visibility };
339 Some(self.alloc_small(ast_id.upcast(), SmallModItem::Trait(def)))
340 }
341
342 fn lower_impl(&mut self, impl_def: &ast::Impl) -> ModItemId {
343 let ast_id = self.source_ast_id_map.ast_id(impl_def);
344 let res = Impl { is_trait_impl: impl_def.trait_().is_some() };
347 self.alloc_small(ast_id.upcast(), SmallModItem::Impl(res))
348 }
349
350 fn lower_use(&mut self, use_item: &ast::Use) -> Option<ModItemId> {
351 let visibility = self.lower_visibility(use_item);
352 let ast_id = self.source_ast_id_map.ast_id(use_item);
353 let (use_tree, _) = lower_use_tree(self.db, use_item.use_tree()?, &mut |range| {
354 self.span_map().span_for_range(range).ctx
355 })?;
356
357 let res = Use { visibility, use_tree };
358 Some(self.alloc_big(ast_id.upcast(), BigModItem::Use(res)))
359 }
360
361 fn lower_extern_crate(&mut self, extern_crate: &ast::ExternCrate) -> Option<ModItemId> {
362 let name = extern_crate.name_ref()?.as_name();
363 let alias = extern_crate.rename().map(|a| {
364 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
365 });
366 let visibility = self.lower_visibility(extern_crate);
367 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
368
369 let res = ExternCrate { name, alias, visibility };
370 Some(self.alloc_big(ast_id.upcast(), BigModItem::ExternCrate(res)))
371 }
372
373 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<ModItemId> {
374 let span_map = self.span_map();
375 let path = m.path()?;
376 let range = path.syntax().text_range();
377 let path = Interned::new(ModPath::from_src(self.db, path, &mut |range| {
378 span_map.span_for_range(range).ctx
379 })?);
380 let ast_id = self.source_ast_id_map.ast_id(m);
381 let expand_to = hir_expand::ExpandTo::from_call_site(m);
382 let res = MacroCall { path, expand_to, ctxt: span_map.span_for_range(range).ctx };
383 Some(self.alloc_small(ast_id.upcast(), SmallModItem::MacroCall(res)))
384 }
385
386 fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<ModItemId> {
387 let name = m.name()?;
388 let ast_id = self.source_ast_id_map.ast_id(m);
389
390 let res = MacroRules { name: name.as_name() };
391 Some(self.alloc_small(ast_id.upcast(), SmallModItem::MacroRules(res)))
392 }
393
394 fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<ModItemId> {
395 let name = m.name()?;
396
397 let ast_id = self.source_ast_id_map.ast_id(m);
398 let visibility = self.lower_visibility(m);
399
400 let res = Macro2 { name: name.as_name(), visibility };
401 Some(self.alloc_small(ast_id.upcast(), SmallModItem::Macro2(res)))
402 }
403
404 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> ModItemId {
405 let ast_id = self.source_ast_id_map.ast_id(block);
406 let children: Box<[_]> = block.extern_item_list().map_or(Box::new([]), |list| {
407 list.extern_items()
408 .filter_map(|item| {
409 let mod_item = match &item {
414 ast::ExternItem::Fn(ast) => self.lower_function(ast)?,
415 ast::ExternItem::Static(ast) => self.lower_static(ast)?,
416 ast::ExternItem::TypeAlias(ty) => self.lower_type_alias(ty)?,
417 ast::ExternItem::MacroCall(call) => self.lower_macro_call(call)?,
418 };
419 let attrs = self.lower_attrs(&item);
420 self.add_attrs(mod_item, attrs);
421 Some(mod_item)
422 })
423 .collect()
424 });
425
426 let res = ExternBlock { children };
427 self.alloc_small(ast_id.upcast(), SmallModItem::ExternBlock(res))
428 }
429
430 fn lower_visibility(&mut self, item: &dyn ast::HasVisibility) -> RawVisibilityId {
431 let vis = self.lower_visibility_from_ast(item);
432 self.alloc_visibility(vis)
433 }
434
435 fn lower_visibility_from_ast(&mut self, item: &dyn ast::HasVisibility) -> RawVisibility {
436 visibility_from_ast(self.db, item.visibility(), &mut |range| {
437 self.span_map().span_for_range(range).ctx
438 })
439 }
440
441 fn alloc_visibility(&mut self, vis: RawVisibility) -> RawVisibilityId {
442 match &vis {
443 RawVisibility::Public => RawVisibilityId::PUB,
444 RawVisibility::PubSelf(VisibilityExplicitness::Explicit) => {
445 RawVisibilityId::PRIV_EXPLICIT
446 }
447 RawVisibility::PubSelf(VisibilityExplicitness::Implicit) => {
448 RawVisibilityId::PRIV_IMPLICIT
449 }
450 RawVisibility::PubCrate => RawVisibilityId::PUB_CRATE,
451 _ => RawVisibilityId(self.visibilities.insert_full(vis).0 as u32),
452 }
453 }
454}
455
456struct UseTreeLowering<'a> {
457 db: &'a dyn SourceDatabase,
458 mapping: Arena<ast::UseTree>,
459}
460
461impl UseTreeLowering<'_> {
462 fn lower_use_tree(
463 &mut self,
464 tree: ast::UseTree,
465 span_for_range: &mut dyn FnMut(::tt::TextRange) -> SyntaxContext,
466 ) -> Option<UseTree> {
467 if let Some(use_tree_list) = tree.use_tree_list() {
468 let prefix = match tree.path() {
469 None => None,
471 Some(path) => {
474 match ModPath::from_src(self.db, path, span_for_range) {
475 Some(it) => Some(it),
476 None => {
477 return None;
479 }
480 }
481 }
482 };
483
484 self.mapping.alloc(tree.clone());
485 let list = use_tree_list
486 .use_trees()
487 .filter_map(|tree| self.lower_use_tree(tree, span_for_range))
488 .collect();
489
490 Some(UseTree {
491 kind: UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
492 })
493 } else {
494 let is_glob = tree.star_token().is_some();
495 let path = match tree.path() {
496 Some(path) => Some(ModPath::from_src(self.db, path, span_for_range)?),
497 None => None,
498 };
499 let alias = tree.rename().map(|a| {
500 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
501 });
502 if alias.is_some() && is_glob {
503 return None;
504 }
505
506 match (path, alias, is_glob) {
507 (path, None, true) => {
508 if path.is_none() {
509 cov_mark::hit!(glob_enum_group);
510 }
511 self.mapping.alloc(tree.clone());
512 Some(UseTree { kind: UseTreeKind::Glob { path: path.map(Interned::new) } })
513 }
514 (_, Some(_), true) | (None, None, false) => None,
516 (None, Some(_), false) => None,
518 (Some(path), alias, false) => {
519 self.mapping.alloc(tree.clone());
520 Some(UseTree { kind: UseTreeKind::Single { path: Interned::new(path), alias } })
521 }
522 }
523 }
524 }
525}
526
527pub(crate) fn lower_use_tree(
528 db: &dyn SourceDatabase,
529 tree: ast::UseTree,
530 span_for_range: &mut dyn FnMut(::tt::TextRange) -> SyntaxContext,
531) -> Option<(UseTree, Arena<ast::UseTree>)> {
532 let mut lowering = UseTreeLowering { db, mapping: Arena::new() };
533 let tree = lowering.lower_use_tree(tree, span_for_range)?;
534 Some((tree, lowering.mapping))
535}
536
537fn private_vis() -> RawVisibility {
538 RawVisibility::PubSelf(VisibilityExplicitness::Implicit)
539}
540
541pub(crate) fn visibility_from_ast(
542 db: &dyn SourceDatabase,
543 node: Option<ast::Visibility>,
544 span_for_range: &mut dyn FnMut(::tt::TextRange) -> SyntaxContext,
545) -> RawVisibility {
546 let Some(node) = node else { return private_vis() };
547 let path = match node.kind() {
548 ast::VisibilityKind::In(path) => {
549 let path = ModPath::from_src(db, path, span_for_range);
550 match path {
551 None => return private_vis(),
552 Some(path) => path,
553 }
554 }
555 ast::VisibilityKind::PubCrate => return RawVisibility::PubCrate,
556 ast::VisibilityKind::PubSuper => ModPath::from_kind(PathKind::Super(1)),
557 ast::VisibilityKind::PubSelf => {
558 return RawVisibility::PubSelf(VisibilityExplicitness::Explicit);
559 }
560 ast::VisibilityKind::Pub => return RawVisibility::Public,
561 };
562 RawVisibility::Module(Interned::new(path), VisibilityExplicitness::Explicit)
563}