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
//! **`undefined-field`**: a member access on a type that does not declare that member.
//!
//! ```cpp
//! struct Widget { int size; };
//!
//! Widget w;
//! w.size; // fine
//! w.weight; // `Widget` has no `weight`
//! ```
//!
//! # Only a definite "no"
//!
//! The question "does this type have this member" has three answers, and only one of them is a complaint:
//!
//! ```text
//! Known::Yes the member list was read and holds the name -> nothing to say
//! Known::No the member list was read and does not hold the name -> report
//! Known::Unknown the type is not known, or its members were never read — the ordinary case for a type from a
//! header nobody read -> report NOTHING
//! ```
//!
//! The third is why this check is quiet on almost every file: a member access on `std::string` asks a question
//! whose answer is in a header the index may not hold, and a check that reported it would be reporting that *we*
//! have not read something as though the *program* were wrong. That is the failure mode this layer is written
//! against — see [`super`]'s module documentation.
//!
//! # What is asked, and of whom
//!
//! A `.` or `->` whose object has a type this file can see: the type comes from [`CheckContext::type_of`], the
//! member list from the model. A chain like `a.b.c` therefore asks about `a.b` first, and is only judged when that
//! answer is a type whose member list was read.
use super::{Check, CheckContext, DiagnosticCode};
/// **`undefined-field`** — see the module documentation.
pub struct UndefinedField;
impl Check for UndefinedField {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::UndefinedField];
fn check(context: &mut CheckContext<'_>) {
// **Every member access in this file's own text**, by the sema layer's definition — see
// `CheckContext::member_accesses`. This check used to filter on `MemberExpr`, a kind this grammar does not
// produce for a dot: measured with `cpp_dump`, `w.secret` is an `IndexExpr`. It had therefore never reported
// anything about `a.b` since it was written, while compiling and looking correct.
//
// **The two halves are timed apart, because they fail for different reasons.** Measured on
// `LuaSyntaxTree.cpp`: collecting 74 accesses takes **262 µs** and the loop over them **98
// ms** — so this check is not a tree walk that got slow, it is 74 type questions (`type_of`
// per access, 6 inference questions each), and the work is in the engine.
let traced = crate::probes::timing();
let started = traced.then(std::time::Instant::now);
let accesses = context.member_accesses();
let collected = started.map(|started| started.elapsed());
let mut judged = 0usize;
for (_node, access) in accesses {
// **Nothing after the operator** is a file being typed at — the completion path's business, not this
// layer's: there is no name to have an opinion about yet.
if access.member.is_empty() {
continue;
}
let crate::Known::Yes((object, _)) = context.type_of(&access.object) else {
continue;
};
// **A dependent type has no member list to check against, and asking for one invents an answer.**
//
// `template <class C, class Fn> constexpr int f(Fn op) { C x{42}; op(x); return x.n; }` — `x` has type
// `C`, and `C` is a template parameter. Every step below is individually correct and the conclusion is
// wrong: `members_of("C")` finds nothing written in `C` (a parameter declares no members), then finds a
// declaration whose qualified name is `C` — **the parameter itself**, recorded as `DeclKind::Type`, the
// kind a class gets — and answers "that class was read and has nothing in it". `x.n` is then reported as
// a member of a class with no `n`.
//
// That is the false positive this layer is written against, on the construct a compiler most refuses to
// diagnose: what `C` is, and therefore whether it has an `n`, is decided at instantiation. See
// [`crate::sema::model::SemanticModel::names_a_template_parameter`] for why the question is asked of the
// scope tree rather than of the index.
if object.class_name().is_some_and(|class| {
context
.model
.names_a_template_parameter(class, access.object.text_range().start().into())
}) {
continue;
}
// **An arrow is followed, not skipped.**
//
// Measured on EmmyLuaCodeStyle: `_session->Send(std::move(message))` was reported as "`_session` has no
// member `Send`" — the receiver is a `std::shared_ptr<Session>`, whose member list is `shared_ptr`'s, and
// the member the program means is behind `operator->`. That measurement is why an arrow used to say
// nothing at all. Following it needs the pointee's type, which the engine now answers for completion
// (`ptr->` on a pointer, a smart pointer's `operator->`, a class's `element_type`), so the same rule is
// asked here.
//
// **Only when a pointer was actually followed.** A class that is not pointer-like and declares no
// `operator->` leaves `followed_a_pointer` false — `p->size` on a plain `Widget` is already ill-formed
// code, and a second finding about its members would be noise.
let class = if access.arrow {
match context.model.the_class_after_an_arrow(&object) {
Some((reached, true)) => reached,
_ => continue,
}
} else {
object.class_name().unwrap_or_default().to_string()
};
// **A class template's member list is a pattern, and the specialization's members are not all in it.**
// `Task<T>`'s members are those the template writes, and a member whose declaration depends on `T` — or one
// the pattern's own parse could not place — is missing from the list without being absent from the class.
// Measured: `other.handle_` inside `Task`'s move constructor, twice on `coroutines.cpp` of the C++ corpus.
// The fact's `parameters` are the template's own, so a class fact that has them is a template —
// `pattern` is about `auto` and is empty here.
let is_a_template = context.summary.declarations.iter().any(|fact| {
fact.kind == crate::DeclKind::Type
&& fact.name == class
&& !fact.parameters.is_empty()
});
if is_a_template {
continue;
}
// **Only a class this file declares is judged.** A member list built from another file's summary is the
// one thing this check cannot verify: the summary may have been cooked under a different macro environment
// — a standard header's `#if __cplusplus` branches are exactly that — and "the name is not in the list" is
// then a claim about *our reading* rather than about the program, which is the failure mode the module
// documentation says this check must never have.
//
// Measured on the C++ corpus: `future.get`, `promise.get`, `packaged_task.get` and
// `string_view::starts_with`/`ends_with` were five findings of exactly that kind, while the header's own
// summary answered 79 members for `std::string_view` in a session that read the same files in a different
// order. The scope tree holds precisely the classes whose declaration this file wrote, and those are the
// ones whose evidence is complete.
let declared_here = context
.model
.scopes()
.scope_with_qualified_name(&class)
.and_then(|scope| context.model.scopes().scope(scope))
.is_some_and(|scope| {
matches!(scope.kind, crate::ScopeKind::Class | crate::ScopeKind::Enum)
});
if !declared_here {
continue;
}
let crate::Known::Yes(members) = context.model.members_of(&class) else {
// Not known to be a class, or known and never read — see the module documentation.
continue;
};
judged += 1;
if members
.members
.iter()
.any(|member| member.fact.name == access.member)
{
continue;
}
// **A partial list is not evidence.** `MemberList::unlisted` names the bases whose members could not be
// read — a base out of the index, a base reached through a macro, a base whose own summary was not built —
// and a member inherited from one of those is *missing from the list* without being absent from the class.
//
// Measured on a real project: `std::cin.read(…)` was reported as "`std::cin` has no member `read`", while
// the hover, which asks the same index a different way, found `basic_istream::read` at once. The two
// answered differently because this check treated "not in the part I read" as "not there". The list is
// only an answer when it is complete.
if !members.unlisted.is_empty() {
continue;
}
// **What the list held, and what the index holds about the name** — the pair that separates "the class
// has no such member" from "the index never recorded it". The second number is what showed that
// `std::vector::erase` was missing from the *facts*, not from the check.
if crate::probes::members() {
let index = context.model.index();
eprintln!(
"[undefined-field] `{}` -> `{}` ({} member(s), {} unlisted) — index: {} posting(s) of \
`{}`, {} in scope `{}`",
object.class_name().unwrap_or("?"),
access.member,
members.members.len(),
members.unlisted.len(),
index.name_postings(&access.member),
access.member,
index.scope_postings(object.class_name().unwrap_or("")),
object.class_name().unwrap_or("?"),
);
}
// The message names what the reader wrote rather than a rendering of the type: `w.weight` is what is on
// their screen, and a type pretty-printed by this layer would be a second spelling to disagree with.
context.add(
DiagnosticCode::UndefinedField,
access.member_range,
access.member.clone(),
t!(
"`%{object}` has no member `%{member}`",
object = access.object.text().to_string().trim(),
member = access.member
),
);
}
if let (true, Some(started), Some(collected)) = (traced, started, collected) {
eprintln!(
"[undefined-field] collected {collected:?}, judged {judged} access(es) with a list, \
loop took {:?}",
started.elapsed() - collected
);
}
}
}