-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathlib.rs
6017 lines (5360 loc) · 209 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! HIR (previously known as descriptors) provides a high-level object-oriented
//! access to Rust code.
//!
//! The principal difference between HIR and syntax trees is that HIR is bound
//! to a particular crate instance. That is, it has cfg flags and features
//! applied. So, the relation between syntax and HIR is many-to-one.
//!
//! HIR is the public API of the all of the compiler logic above syntax trees.
//! It is written in "OO" style. Each type is self contained (as in, it knows its
//! parents and full context). It should be "clean code".
//!
//! `hir_*` crates are the implementation of the compiler logic.
//! They are written in "ECS" style, with relatively little abstractions.
//! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
//!
//! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
//! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
//! <https://www.tedinski.com/2018/02/06/system-boundaries.html>.
#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
#![recursion_limit = "512"]
mod attrs;
mod from_id;
mod has_source;
mod semantics;
mod source_analyzer;
pub mod db;
pub mod diagnostics;
pub mod symbols;
pub mod term_search;
mod display;
use std::{
mem::discriminant,
ops::{ControlFlow, Not},
};
use arrayvec::ArrayVec;
use base_db::{CrateDisplayName, CrateId, CrateOrigin};
use either::Either;
use hir_def::{
body::BodyDiagnostic,
data::adt::VariantData,
generics::{LifetimeParamData, TypeOrConstParamData, TypeParamProvenance},
hir::{BindingAnnotation, BindingId, ExprId, ExprOrPatId, LabelId, Pat},
item_tree::{AttrOwner, FieldParent, ItemTreeFieldId, ItemTreeNode},
lang_item::LangItemTarget,
layout::{self, ReprOptions, TargetDataLayout},
nameres::{self, diagnostics::DefDiagnostic},
path::ImportAlias,
per_ns::PerNs,
resolver::{HasResolver, Resolver},
type_ref::TypesSourceMap,
AssocItemId, AssocItemLoc, AttrDefId, CallableDefId, ConstId, ConstParamId, CrateRootModuleId,
DefWithBodyId, EnumId, EnumVariantId, ExternCrateId, FunctionId, GenericDefId, GenericParamId,
HasModule, ImplId, InTypeConstId, ItemContainerId, LifetimeParamId, LocalFieldId, Lookup,
MacroExpander, ModuleId, StaticId, StructId, SyntheticSyntax, TraitAliasId, TraitId, TupleId,
TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId,
};
use hir_expand::{
attrs::collect_attrs, proc_macro::ProcMacroKind, AstId, MacroCallKind, RenderedExpandError,
ValueResult,
};
use hir_ty::{
all_super_traits, autoderef, check_orphan_rules,
consteval::{try_const_usize, unknown_const_as_generic, ConstExt},
diagnostics::BodyValidationDiagnostic,
direct_super_traits, error_lifetime, known_const_to_ast,
layout::{Layout as TyLayout, RustcEnumVariantIdx, RustcFieldIdx, TagEncoding},
method_resolution,
mir::{interpret_mir, MutBorrowKind},
primitive::UintTy,
traits::FnTrait,
AliasTy, CallableSig, Canonical, CanonicalVarKinds, Cast, ClosureId, GenericArg,
GenericArgData, Interner, ParamKind, QuantifiedWhereClause, Scalar, Substitution,
TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, TyLoweringDiagnostic,
ValueTyDefId, WhereClause,
};
use itertools::Itertools;
use nameres::diagnostics::DefDiagnosticKind;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use span::{Edition, EditionedFileId, FileId, MacroCallId, SyntaxContextId};
use stdx::{format_to, impl_from, never};
use syntax::{
ast::{self, HasAttrs as _, HasGenericParams, HasName},
format_smolstr, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange, ToSmolStr, T,
};
use triomphe::{Arc, ThinArc};
use crate::db::{DefDatabase, HirDatabase};
pub use crate::{
attrs::{resolve_doc_path_on, HasAttrs},
diagnostics::*,
has_source::HasSource,
semantics::{
PathResolution, Semantics, SemanticsImpl, SemanticsScope, TypeInfo, VisibleTraits,
},
};
pub use hir_ty::method_resolution::TyFingerprint;
// Be careful with these re-exports.
//
// `hir` is the boundary between the compiler and the IDE. It should try hard to
// isolate the compiler from the ide, to allow the two to be refactored
// independently. Re-exporting something from the compiler is the sure way to
// breach the boundary.
//
// Generally, a refactoring which *removes* a name from this list is a good
// idea!
pub use {
cfg::{CfgAtom, CfgExpr, CfgOptions},
hir_def::{
attr::{AttrSourceMap, Attrs, AttrsWithOwner},
data::adt::StructKind,
find_path::PrefixKind,
import_map,
lang_item::LangItem,
nameres::{DefMap, ModuleSource},
path::{ModPath, PathKind},
per_ns::Namespace,
type_ref::{Mutability, TypeRef},
visibility::Visibility,
ImportPathConfig,
// FIXME: This is here since some queries take it as input that are used
// outside of hir.
{AdtId, MacroId, ModuleDefId},
},
hir_expand::{
attrs::{Attr, AttrId},
change::ChangeWithProcMacros,
files::{
FilePosition, FilePositionWrapper, FileRange, FileRangeWrapper, HirFilePosition,
HirFileRange, InFile, InFileWrapper, InMacroFile, InRealFile, MacroFilePosition,
MacroFileRange,
},
hygiene::{marks_rev, SyntaxContextExt},
inert_attr_macro::AttributeTemplate,
name::Name,
prettify_macro_expansion,
proc_macro::{ProcMacros, ProcMacrosBuilder},
tt, ExpandResult, HirFileId, HirFileIdExt, MacroFileId, MacroFileIdExt,
},
hir_ty::{
consteval::ConstEvalError,
diagnostics::UnsafetyReason,
display::{ClosureStyle, HirDisplay, HirDisplayError, HirWrite},
dyn_compatibility::{DynCompatibilityViolation, MethodViolationCode},
layout::LayoutError,
mir::{MirEvalError, MirLowerError},
CastError, FnAbi, PointerCast, Safety,
},
// FIXME: Properly encapsulate mir
hir_ty::{mir, Interner as ChalkTyInterner},
intern::{sym, Symbol},
};
// These are negative re-exports: pub using these names is forbidden, they
// should remain private to hir internals.
#[allow(unused)]
use {
hir_def::path::Path,
hir_expand::{
name::AsName,
span_map::{ExpansionSpanMap, RealSpanMap, SpanMap, SpanMapRef},
},
};
/// hir::Crate describes a single crate. It's the main interface with which
/// a crate's dependencies interact. Mostly, it should be just a proxy for the
/// root module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Crate {
pub(crate) id: CrateId,
}
#[derive(Debug)]
pub struct CrateDependency {
pub krate: Crate,
pub name: Name,
}
impl Crate {
pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
db.crate_graph()[self.id].origin.clone()
}
pub fn is_builtin(self, db: &dyn HirDatabase) -> bool {
matches!(self.origin(db), CrateOrigin::Lang(_))
}
pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
db.crate_graph()[self.id]
.dependencies
.iter()
.map(|dep| {
let krate = Crate { id: dep.crate_id };
let name = dep.as_name();
CrateDependency { krate, name }
})
.collect()
}
pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
let crate_graph = db.crate_graph();
crate_graph
.iter()
.filter(|&krate| {
crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
})
.map(|id| Crate { id })
.collect()
}
pub fn transitive_reverse_dependencies(
self,
db: &dyn HirDatabase,
) -> impl Iterator<Item = Crate> {
db.crate_graph().transitive_rev_deps(self.id).map(|id| Crate { id })
}
pub fn root_module(self) -> Module {
Module { id: CrateRootModuleId::from(self.id).into() }
}
pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
let def_map = db.crate_def_map(self.id);
def_map.modules().map(|(id, _)| def_map.module_id(id).into()).collect()
}
pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
db.crate_graph()[self.id].root_file_id
}
pub fn edition(self, db: &dyn HirDatabase) -> Edition {
db.crate_graph()[self.id].edition
}
pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
db.crate_graph()[self.id].version.clone()
}
pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
db.crate_graph()[self.id].display_name.clone()
}
pub fn query_external_importables(
self,
db: &dyn DefDatabase,
query: import_map::Query,
) -> impl Iterator<Item = Either<ModuleDef, Macro>> {
let _p = tracing::info_span!("query_external_importables").entered();
import_map::search_dependencies(db, self.into(), &query).into_iter().map(|item| {
match ItemInNs::from(item) {
ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
ItemInNs::Macros(mac_id) => Either::Right(mac_id),
}
})
}
pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
db.crate_graph().iter().map(|id| Crate { id }).collect()
}
/// Try to get the root URL of the documentation of a crate.
pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
// Look for #![doc(html_root_url = "...")]
let attrs = db.attrs(AttrDefId::ModuleId(self.root_module().into()));
let doc_url = attrs.by_key(&sym::doc).find_string_value_in_tt(&sym::html_root_url);
doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
}
pub fn cfg(&self, db: &dyn HirDatabase) -> Arc<CfgOptions> {
db.crate_graph()[self.id].cfg_options.clone()
}
pub fn potential_cfg(&self, db: &dyn HirDatabase) -> Arc<CfgOptions> {
let data = &db.crate_graph()[self.id];
data.potential_cfg_options.clone().unwrap_or_else(|| data.cfg_options.clone())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Module {
pub(crate) id: ModuleId,
}
/// The defs which can be visible in the module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ModuleDef {
Module(Module),
Function(Function),
Adt(Adt),
// Can't be directly declared, but can be imported.
Variant(Variant),
Const(Const),
Static(Static),
Trait(Trait),
TraitAlias(TraitAlias),
TypeAlias(TypeAlias),
BuiltinType(BuiltinType),
Macro(Macro),
}
impl_from!(
Module,
Function,
Adt(Struct, Enum, Union),
Variant,
Const,
Static,
Trait,
TraitAlias,
TypeAlias,
BuiltinType,
Macro
for ModuleDef
);
impl From<VariantDef> for ModuleDef {
fn from(var: VariantDef) -> Self {
match var {
VariantDef::Struct(t) => Adt::from(t).into(),
VariantDef::Union(t) => Adt::from(t).into(),
VariantDef::Variant(t) => t.into(),
}
}
}
impl ModuleDef {
pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
match self {
ModuleDef::Module(it) => it.parent(db),
ModuleDef::Function(it) => Some(it.module(db)),
ModuleDef::Adt(it) => Some(it.module(db)),
ModuleDef::Variant(it) => Some(it.module(db)),
ModuleDef::Const(it) => Some(it.module(db)),
ModuleDef::Static(it) => Some(it.module(db)),
ModuleDef::Trait(it) => Some(it.module(db)),
ModuleDef::TraitAlias(it) => Some(it.module(db)),
ModuleDef::TypeAlias(it) => Some(it.module(db)),
ModuleDef::Macro(it) => Some(it.module(db)),
ModuleDef::BuiltinType(_) => None,
}
}
pub fn canonical_path(&self, db: &dyn HirDatabase, edition: Edition) -> Option<String> {
let mut segments = vec![self.name(db)?];
for m in self.module(db)?.path_to_root(db) {
segments.extend(m.name(db))
}
segments.reverse();
Some(segments.iter().map(|it| it.display(db.upcast(), edition)).join("::"))
}
pub fn canonical_module_path(
&self,
db: &dyn HirDatabase,
) -> Option<impl Iterator<Item = Module>> {
self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
}
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
let name = match self {
ModuleDef::Module(it) => it.name(db)?,
ModuleDef::Const(it) => it.name(db)?,
ModuleDef::Adt(it) => it.name(db),
ModuleDef::Trait(it) => it.name(db),
ModuleDef::TraitAlias(it) => it.name(db),
ModuleDef::Function(it) => it.name(db),
ModuleDef::Variant(it) => it.name(db),
ModuleDef::TypeAlias(it) => it.name(db),
ModuleDef::Static(it) => it.name(db),
ModuleDef::Macro(it) => it.name(db),
ModuleDef::BuiltinType(it) => it.name(),
};
Some(name)
}
pub fn diagnostics(self, db: &dyn HirDatabase, style_lints: bool) -> Vec<AnyDiagnostic> {
let id = match self {
ModuleDef::Adt(it) => match it {
Adt::Struct(it) => it.id.into(),
Adt::Enum(it) => it.id.into(),
Adt::Union(it) => it.id.into(),
},
ModuleDef::Trait(it) => it.id.into(),
ModuleDef::TraitAlias(it) => it.id.into(),
ModuleDef::Function(it) => it.id.into(),
ModuleDef::TypeAlias(it) => it.id.into(),
ModuleDef::Module(it) => it.id.into(),
ModuleDef::Const(it) => it.id.into(),
ModuleDef::Static(it) => it.id.into(),
ModuleDef::Variant(it) => it.id.into(),
ModuleDef::BuiltinType(_) | ModuleDef::Macro(_) => return Vec::new(),
};
let mut acc = Vec::new();
match self.as_def_with_body() {
Some(def) => {
def.diagnostics(db, &mut acc, style_lints);
}
None => {
for diag in hir_ty::diagnostics::incorrect_case(db, id) {
acc.push(diag.into())
}
}
}
if let Some(def) = self.as_self_generic_def() {
def.diagnostics(db, &mut acc);
}
acc
}
pub fn as_def_with_body(self) -> Option<DefWithBody> {
match self {
ModuleDef::Function(it) => Some(it.into()),
ModuleDef::Const(it) => Some(it.into()),
ModuleDef::Static(it) => Some(it.into()),
ModuleDef::Variant(it) => Some(it.into()),
ModuleDef::Module(_)
| ModuleDef::Adt(_)
| ModuleDef::Trait(_)
| ModuleDef::TraitAlias(_)
| ModuleDef::TypeAlias(_)
| ModuleDef::Macro(_)
| ModuleDef::BuiltinType(_) => None,
}
}
/// Returns only defs that have generics from themselves, not their parent.
pub fn as_self_generic_def(self) -> Option<GenericDef> {
match self {
ModuleDef::Function(it) => Some(it.into()),
ModuleDef::Adt(it) => Some(it.into()),
ModuleDef::Trait(it) => Some(it.into()),
ModuleDef::TraitAlias(it) => Some(it.into()),
ModuleDef::TypeAlias(it) => Some(it.into()),
ModuleDef::Module(_)
| ModuleDef::Variant(_)
| ModuleDef::Static(_)
| ModuleDef::Const(_)
| ModuleDef::BuiltinType(_)
| ModuleDef::Macro(_) => None,
}
}
pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
Some(match self {
ModuleDef::Module(it) => it.attrs(db),
ModuleDef::Function(it) => it.attrs(db),
ModuleDef::Adt(it) => it.attrs(db),
ModuleDef::Variant(it) => it.attrs(db),
ModuleDef::Const(it) => it.attrs(db),
ModuleDef::Static(it) => it.attrs(db),
ModuleDef::Trait(it) => it.attrs(db),
ModuleDef::TraitAlias(it) => it.attrs(db),
ModuleDef::TypeAlias(it) => it.attrs(db),
ModuleDef::Macro(it) => it.attrs(db),
ModuleDef::BuiltinType(_) => return None,
})
}
}
impl HasVisibility for ModuleDef {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
match *self {
ModuleDef::Module(it) => it.visibility(db),
ModuleDef::Function(it) => it.visibility(db),
ModuleDef::Adt(it) => it.visibility(db),
ModuleDef::Const(it) => it.visibility(db),
ModuleDef::Static(it) => it.visibility(db),
ModuleDef::Trait(it) => it.visibility(db),
ModuleDef::TraitAlias(it) => it.visibility(db),
ModuleDef::TypeAlias(it) => it.visibility(db),
ModuleDef::Variant(it) => it.visibility(db),
ModuleDef::Macro(it) => it.visibility(db),
ModuleDef::BuiltinType(_) => Visibility::Public,
}
}
}
impl Module {
/// Name of this module.
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
self.id.name(db.upcast())
}
/// Returns the crate this module is part of.
pub fn krate(self) -> Crate {
Crate { id: self.id.krate() }
}
/// Topmost parent of this module. Every module has a `crate_root`, but some
/// might be missing `krate`. This can happen if a module's file is not included
/// in the module tree of any target in `Cargo.toml`.
pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
let def_map = db.crate_def_map(self.id.krate());
Module { id: def_map.crate_root().into() }
}
pub fn is_crate_root(self) -> bool {
DefMap::ROOT == self.id.local_id
}
/// Iterates over all child modules.
pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
let def_map = self.id.def_map(db.upcast());
let children = def_map[self.id.local_id]
.children
.values()
.map(|module_id| Module { id: def_map.module_id(*module_id) })
.collect::<Vec<_>>();
children.into_iter()
}
/// Finds a parent module.
pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
let def_map = self.id.def_map(db.upcast());
let parent_id = def_map.containing_module(self.id.local_id)?;
Some(Module { id: parent_id })
}
/// Finds nearest non-block ancestor `Module` (`self` included).
pub fn nearest_non_block_module(self, db: &dyn HirDatabase) -> Module {
let mut id = self.id;
while id.is_block_module() {
id = id.containing_module(db.upcast()).expect("block without parent module");
}
Module { id }
}
pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
let mut res = vec![self];
let mut curr = self;
while let Some(next) = curr.parent(db) {
res.push(next);
curr = next
}
res
}
/// Returns a `ModuleScope`: a set of items, visible in this module.
pub fn scope(
self,
db: &dyn HirDatabase,
visible_from: Option<Module>,
) -> Vec<(Name, ScopeDef)> {
self.id.def_map(db.upcast())[self.id.local_id]
.scope
.entries()
.filter_map(|(name, def)| {
if let Some(m) = visible_from {
let filtered =
def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
if filtered.is_none() && !def.is_none() {
None
} else {
Some((name, filtered))
}
} else {
Some((name, def))
}
})
.flat_map(|(name, def)| {
ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
})
.collect()
}
/// Fills `acc` with the module's diagnostics.
pub fn diagnostics(
self,
db: &dyn HirDatabase,
acc: &mut Vec<AnyDiagnostic>,
style_lints: bool,
) {
let _p = tracing::info_span!("diagnostics", name = ?self.name(db)).entered();
let edition = db.crate_graph()[self.id.krate()].edition;
let def_map = self.id.def_map(db.upcast());
for diag in def_map.diagnostics() {
if diag.in_module != self.id.local_id {
// FIXME: This is accidentally quadratic.
continue;
}
emit_def_diagnostic(db, acc, diag, edition);
}
if !self.id.is_block_module() {
// These are reported by the body of block modules
let scope = &def_map[self.id.local_id].scope;
scope.all_macro_calls().for_each(|it| macro_call_diagnostics(db, it, acc));
}
for def in self.declarations(db) {
match def {
ModuleDef::Module(m) => {
// Only add diagnostics from inline modules
if def_map[m.id.local_id].origin.is_inline() {
m.diagnostics(db, acc, style_lints)
}
acc.extend(def.diagnostics(db, style_lints))
}
ModuleDef::Trait(t) => {
for diag in db.trait_data_with_diagnostics(t.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
for item in t.items(db) {
item.diagnostics(db, acc, style_lints);
}
t.all_macro_calls(db)
.iter()
.for_each(|&(_ast, call_id)| macro_call_diagnostics(db, call_id, acc));
acc.extend(def.diagnostics(db, style_lints))
}
ModuleDef::Adt(adt) => {
match adt {
Adt::Struct(s) => {
let tree_id = s.id.lookup(db.upcast()).id;
let tree_source_maps = tree_id.item_tree_with_source_map(db.upcast()).1;
push_ty_diagnostics(
db,
acc,
db.field_types_with_diagnostics(s.id.into()).1,
tree_source_maps.strukt(tree_id.value).item(),
);
for diag in db.struct_data_with_diagnostics(s.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
}
Adt::Union(u) => {
let tree_id = u.id.lookup(db.upcast()).id;
let tree_source_maps = tree_id.item_tree_with_source_map(db.upcast()).1;
push_ty_diagnostics(
db,
acc,
db.field_types_with_diagnostics(u.id.into()).1,
tree_source_maps.union(tree_id.value).item(),
);
for diag in db.union_data_with_diagnostics(u.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
}
Adt::Enum(e) => {
for v in e.variants(db) {
let tree_id = v.id.lookup(db.upcast()).id;
let tree_source_maps =
tree_id.item_tree_with_source_map(db.upcast()).1;
push_ty_diagnostics(
db,
acc,
db.field_types_with_diagnostics(v.id.into()).1,
tree_source_maps.variant(tree_id.value),
);
acc.extend(ModuleDef::Variant(v).diagnostics(db, style_lints));
for diag in db.enum_variant_data_with_diagnostics(v.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
}
}
}
acc.extend(def.diagnostics(db, style_lints))
}
ModuleDef::Macro(m) => emit_macro_def_diagnostics(db, acc, m),
ModuleDef::TypeAlias(type_alias) => {
let tree_id = type_alias.id.lookup(db.upcast()).id;
let tree_source_maps = tree_id.item_tree_with_source_map(db.upcast()).1;
push_ty_diagnostics(
db,
acc,
db.type_for_type_alias_with_diagnostics(type_alias.id).1,
tree_source_maps.type_alias(tree_id.value).item(),
);
acc.extend(def.diagnostics(db, style_lints));
}
_ => acc.extend(def.diagnostics(db, style_lints)),
}
}
self.legacy_macros(db).into_iter().for_each(|m| emit_macro_def_diagnostics(db, acc, m));
let inherent_impls = db.inherent_impls_in_crate(self.id.krate());
let mut impl_assoc_items_scratch = vec![];
for impl_def in self.impl_defs(db) {
GenericDef::Impl(impl_def).diagnostics(db, acc);
let loc = impl_def.id.lookup(db.upcast());
let (tree, tree_source_maps) = loc.id.item_tree_with_source_map(db.upcast());
let source_map = tree_source_maps.impl_(loc.id.value).item();
let node = &tree[loc.id.value];
let file_id = loc.id.file_id();
if file_id.macro_file().map_or(false, |it| it.is_builtin_derive(db.upcast())) {
// these expansion come from us, diagnosing them is a waste of resources
// FIXME: Once we diagnose the inputs to builtin derives, we should at least extract those diagnostics somehow
continue;
}
impl_def
.all_macro_calls(db)
.iter()
.for_each(|&(_ast, call_id)| macro_call_diagnostics(db, call_id, acc));
let ast_id_map = db.ast_id_map(file_id);
for diag in db.impl_data_with_diagnostics(impl_def.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition);
}
if inherent_impls.invalid_impls().contains(&impl_def.id) {
acc.push(IncoherentImpl { impl_: ast_id_map.get(node.ast_id()), file_id }.into())
}
if !impl_def.check_orphan_rules(db) {
acc.push(TraitImplOrphan { impl_: ast_id_map.get(node.ast_id()), file_id }.into())
}
let trait_ = impl_def.trait_(db);
let trait_is_unsafe = trait_.map_or(false, |t| t.is_unsafe(db));
let impl_is_negative = impl_def.is_negative(db);
let impl_is_unsafe = impl_def.is_unsafe(db);
let drop_maybe_dangle = (|| {
// FIXME: This can be simplified a lot by exposing hir-ty's utils.rs::Generics helper
let trait_ = trait_?;
let drop_trait = db.lang_item(self.krate().into(), LangItem::Drop)?.as_trait()?;
if drop_trait != trait_.into() {
return None;
}
let parent = impl_def.id.into();
let generic_params = db.generic_params(parent);
let lifetime_params = generic_params.iter_lt().map(|(local_id, _)| {
GenericParamId::LifetimeParamId(LifetimeParamId { parent, local_id })
});
let type_params = generic_params
.iter_type_or_consts()
.filter(|(_, it)| it.type_param().is_some())
.map(|(local_id, _)| {
GenericParamId::TypeParamId(TypeParamId::from_unchecked(
TypeOrConstParamId { parent, local_id },
))
});
let res = type_params.chain(lifetime_params).any(|p| {
db.attrs(AttrDefId::GenericParamId(p)).by_key(&sym::may_dangle).exists()
});
Some(res)
})()
.unwrap_or(false);
match (impl_is_unsafe, trait_is_unsafe, impl_is_negative, drop_maybe_dangle) {
// unsafe negative impl
(true, _, true, _) |
// unsafe impl for safe trait
(true, false, _, false) => acc.push(TraitImplIncorrectSafety { impl_: ast_id_map.get(node.ast_id()), file_id, should_be_safe: true }.into()),
// safe impl for unsafe trait
(false, true, false, _) |
// safe impl of dangling drop
(false, false, _, true) => acc.push(TraitImplIncorrectSafety { impl_: ast_id_map.get(node.ast_id()), file_id, should_be_safe: false }.into()),
_ => (),
};
// Negative impls can't have items, don't emit missing items diagnostic for them
if let (false, Some(trait_)) = (impl_is_negative, trait_) {
let items = &db.trait_data(trait_.into()).items;
let required_items = items.iter().filter(|&(_, assoc)| match *assoc {
AssocItemId::FunctionId(it) => !db.function_data(it).has_body(),
AssocItemId::ConstId(id) => !db.const_data(id).has_body,
AssocItemId::TypeAliasId(it) => db.type_alias_data(it).type_ref.is_none(),
});
impl_assoc_items_scratch.extend(db.impl_data(impl_def.id).items.iter().filter_map(
|&item| {
Some((
item,
match item {
AssocItemId::FunctionId(it) => db.function_data(it).name.clone(),
AssocItemId::ConstId(it) => {
db.const_data(it).name.as_ref()?.clone()
}
AssocItemId::TypeAliasId(it) => db.type_alias_data(it).name.clone(),
},
))
},
));
let redundant = impl_assoc_items_scratch
.iter()
.filter(|(id, name)| {
!items.iter().any(|(impl_name, impl_item)| {
discriminant(impl_item) == discriminant(id) && impl_name == name
})
})
.map(|(item, name)| (name.clone(), AssocItem::from(*item)));
for (name, assoc_item) in redundant {
acc.push(
TraitImplRedundantAssocItems {
trait_,
file_id,
impl_: ast_id_map.get(node.ast_id()),
assoc_item: (name, assoc_item),
}
.into(),
)
}
let missing: Vec<_> = required_items
.filter(|(name, id)| {
!impl_assoc_items_scratch.iter().any(|(impl_item, impl_name)| {
discriminant(impl_item) == discriminant(id) && impl_name == name
})
})
.map(|(name, item)| (name.clone(), AssocItem::from(*item)))
.collect();
if !missing.is_empty() {
acc.push(
TraitImplMissingAssocItems {
impl_: ast_id_map.get(node.ast_id()),
file_id,
missing,
}
.into(),
)
}
impl_assoc_items_scratch.clear();
}
push_ty_diagnostics(
db,
acc,
db.impl_self_ty_with_diagnostics(impl_def.id).1,
source_map,
);
push_ty_diagnostics(
db,
acc,
db.impl_trait_with_diagnostics(impl_def.id).and_then(|it| it.1),
source_map,
);
for &item in db.impl_data(impl_def.id).items.iter() {
AssocItem::from(item).diagnostics(db, acc, style_lints);
}
}
}
pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
let def_map = self.id.def_map(db.upcast());
let scope = &def_map[self.id.local_id].scope;
scope
.declarations()
.map(ModuleDef::from)
.chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
.collect()
}
pub fn legacy_macros(self, db: &dyn HirDatabase) -> Vec<Macro> {
let def_map = self.id.def_map(db.upcast());
let scope = &def_map[self.id.local_id].scope;
scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect()
}
pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
let def_map = self.id.def_map(db.upcast());
def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
}
/// Finds a path that can be used to refer to the given item from within
/// this module, if possible.
pub fn find_path(
self,
db: &dyn DefDatabase,
item: impl Into<ItemInNs>,
cfg: ImportPathConfig,
) -> Option<ModPath> {
hir_def::find_path::find_path(
db,
item.into().into(),
self.into(),
PrefixKind::Plain,
false,
cfg,
)
}
/// Finds a path that can be used to refer to the given item from within
/// this module, if possible. This is used for returning import paths for use-statements.
pub fn find_use_path(
self,
db: &dyn DefDatabase,
item: impl Into<ItemInNs>,
prefix_kind: PrefixKind,
cfg: ImportPathConfig,
) -> Option<ModPath> {
hir_def::find_path::find_path(db, item.into().into(), self.into(), prefix_kind, true, cfg)
}
}
fn macro_call_diagnostics(
db: &dyn HirDatabase,
macro_call_id: MacroCallId,
acc: &mut Vec<AnyDiagnostic>,
) {
let Some(e) = db.parse_macro_expansion_error(macro_call_id) else {
return;
};
let ValueResult { value: parse_errors, err } = &*e;
if let Some(err) = err {
let loc = db.lookup_intern_macro_call(macro_call_id);
let file_id = loc.kind.file_id();
let node =
InFile::new(file_id, db.ast_id_map(file_id).get_erased(loc.kind.erased_ast_id()));
let RenderedExpandError { message, error, kind } = err.render_to_string(db.upcast());
let precise_location = if err.span().anchor.file_id == file_id {
Some(
err.span().range
+ db.ast_id_map(err.span().anchor.file_id.into())
.get_erased(err.span().anchor.ast_id)
.text_range()
.start(),
)
} else {
None
};
acc.push(MacroError { node, precise_location, message, error, kind }.into());
}
if !parse_errors.is_empty() {
let loc = db.lookup_intern_macro_call(macro_call_id);
let (node, precise_location) = precise_macro_call_location(&loc.kind, db);
acc.push(
MacroExpansionParseError { node, precise_location, errors: parse_errors.clone() }
.into(),
)
}
}
fn emit_macro_def_diagnostics(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, m: Macro) {
let id = db.macro_def(m.id);
if let hir_expand::db::TokenExpander::DeclarativeMacro(expander) = db.macro_expander(id) {
if let Some(e) = expander.mac.err() {
let Some(ast) = id.ast_id().left() else {
never!("declarative expander for non decl-macro: {:?}", e);
return;
};
let krate = HasModule::krate(&m.id, db.upcast());
let edition = db.crate_graph()[krate].edition;
emit_def_diagnostic_(
db,
acc,
&DefDiagnosticKind::MacroDefError { ast, message: e.to_string() },
edition,
);
}
}
}
fn emit_def_diagnostic(
db: &dyn HirDatabase,
acc: &mut Vec<AnyDiagnostic>,
diag: &DefDiagnostic,
edition: Edition,
) {
emit_def_diagnostic_(db, acc, &diag.kind, edition)
}
fn emit_def_diagnostic_(
db: &dyn HirDatabase,
acc: &mut Vec<AnyDiagnostic>,
diag: &DefDiagnosticKind,
edition: Edition,
) {
match diag {
DefDiagnosticKind::UnresolvedModule { ast: declaration, candidates } => {
let decl = declaration.to_ptr(db.upcast());
acc.push(
UnresolvedModule {
decl: InFile::new(declaration.file_id, decl),
candidates: candidates.clone(),
}
.into(),
)
}
DefDiagnosticKind::UnresolvedExternCrate { ast } => {
let item = ast.to_ptr(db.upcast());
acc.push(UnresolvedExternCrate { decl: InFile::new(ast.file_id, item) }.into());
}
DefDiagnosticKind::MacroError { ast, path, err } => {
let item = ast.to_ptr(db.upcast());
let RenderedExpandError { message, error, kind } = err.render_to_string(db.upcast());
acc.push(
MacroError {
node: InFile::new(ast.file_id, item.syntax_node_ptr()),