nixd
Loading...
Searching...
No Matches
VariableLookup.cpp
Go to the documentation of this file.
7
8#include <set>
9
10using namespace nixf;
11
12namespace {
13
14std::set<std::string> Constants{
15 "true", "false", "null",
16 "__currentTime", "__currentSystem", "__nixVersion",
17 "__storeDir", "__langVersion", "__importNative",
18 "__traceVerbose", "__nixPath", "derivation",
19};
20
21/// Builder a map of definitions. If there are something overlapped, maybe issue
22/// a diagnostic.
23class DefBuilder {
25 std::vector<Diagnostic> &Diags;
26
27 std::shared_ptr<Definition> addSimple(std::string Name, const Node *Entry,
29 assert(!Def.contains(Name));
30 auto NewDef = std::make_shared<Definition>(Entry, Source);
31 Def.insert({std::move(Name), NewDef});
32 return NewDef;
33 }
34
35public:
36 DefBuilder(std::vector<Diagnostic> &Diags) : Diags(Diags) {}
37
38 void addBuiltin(std::string Name) {
39 // Don't need to record def map for builtins.
40 auto _ = addSimple(std::move(Name), nullptr, Definition::DS_Builtin);
41 }
42
43 [[nodiscard("Record ToDef Map!")]] std::shared_ptr<Definition>
44 add(std::string Name, const Node *Entry, Definition::DefinitionSource Source,
45 bool IsInheritFromBuiltin) {
46 auto PrimOpLookup = lookupGlobalPrimOpInfo(Name);
47 if (PrimOpLookup == PrimopLookupResult::Found && !IsInheritFromBuiltin) {
48 // Overriding a builtin primop is discouraged.
49 Diagnostic &D =
50 Diags.emplace_back(Diagnostic::DK_PrimOpOverridden, Entry->range());
51 D << Name;
52 }
53
54 // Lookup constants
55 if (Constants.contains(Name)) {
56 Diagnostic &D =
57 Diags.emplace_back(Diagnostic::DK_ConstantOverridden, Entry->range());
58 D << Name;
59 }
60
61 return addSimple(std::move(Name), Entry, Source);
62 }
63
64 EnvNode::DefMap finish() { return std::move(Def); }
65};
66
67/// Special check for inherited from builtins attribute.
68/// e.g. inherit (builtins) foo bar;
69/// Returns true if the attribute is inherited from builtins.
70///
71/// Suppress warnings for overriding primops in this case.
72bool checkInheritedFromBuiltin(const Attribute &Attr) {
74 return false;
75
76 assert(Attr.value() &&
77 "select expr desugared from inherit should not be null");
78 assert(Attr.value()->kind() == Node::NK_ExprSelect &&
79 "desugared inherited from should be a select expr");
80 const auto &Select = static_cast<const ExprSelect &>(*Attr.value());
81 if (Select.expr().kind() == Node::NK_ExprVar) {
82 const auto &Var = static_cast<const ExprVar &>(Select.expr());
83 return Var.id().name() == "builtins";
84 }
85 return false;
86}
87
88} // namespace
89
90bool EnvNode::isLive() const {
91 for (const auto &[_, D] : Defs) {
92 if (!D->uses().empty())
93 return true;
94 }
95 return false;
96}
97
98void VariableLookupAnalysis::emitEnvLivenessWarning(
99 const std::shared_ptr<EnvNode> &NewEnv) {
100 for (const auto &[Name, Def] : NewEnv->defs()) {
101 // If the definition comes from lambda arg, omit the diagnostic
102 // because there is no elegant way to "fix" this trivially & keep
103 // the lambda signature.
104 if (Def->source() == Definition::DS_LambdaArg)
105 continue;
106 // Ignore builtins usage.
107 if (!Def->syntax())
108 continue;
109 if (Def->uses().empty()) {
110 Diagnostic::DiagnosticKind Kind = [&]() {
111 switch (Def->source()) {
113 return Diagnostic::DK_UnusedDefLet;
115 return Diagnostic::DK_UnusedDefLambdaNoArg_Formal;
117 return Diagnostic::DK_UnusedDefLambdaWithArg_Formal;
119 return Diagnostic::DK_UnusedDefLambdaWithArg_Arg;
120 default:
121 assert(false && "liveness diagnostic encountered an unknown source!");
122 __builtin_unreachable();
123 }
124 }();
125 Diagnostic &D = Diags.emplace_back(Kind, Def->syntax()->range());
126 D << Name;
128 }
129 }
130}
131
132void VariableLookupAnalysis::lookupVar(const ExprVar &Var,
133 const std::shared_ptr<EnvNode> &Env) {
134 const auto &Name = Var.id().name();
135 const auto *CurEnv = Env.get();
136 std::shared_ptr<Definition> Def;
137 std::vector<const EnvNode *> WithEnvs;
138 for (; CurEnv; CurEnv = CurEnv->parent()) {
139 if (CurEnv->defs().contains(Name)) {
140 Def = CurEnv->defs().at(Name);
141 break;
142 }
143 // Find all nested "with" expression, variables potentially come from those.
144 // For example
145 // with lib;
146 // with builtins;
147 // generators <--- this variable may come from "lib" | "builtins"
148 //
149 // We cannot determine where it precisely come from, thus mark all Envs
150 // alive.
151 if (CurEnv->isWith()) {
152 WithEnvs.emplace_back(CurEnv);
153 }
154 }
155
156 if (Def) {
157 Def->usedBy(Var);
158 Results.insert({&Var, LookupResult{LookupResultKind::Defined, Def}});
159 } else if (!WithEnvs.empty()) { // comes from enclosed "with" expressions.
160 // Collect all `with` expressions that could provide this variable's
161 // binding. This is stored for later queries (e.g., by code actions that
162 // need to determine if converting a `with` to `let/inherit` is safe).
163 std::vector<const ExprWith *> WithScopes;
164 for (const auto *WithEnv : WithEnvs) {
165 Def = WithDefs.at(WithEnv->syntax());
166 Def->usedBy(Var);
167 WithScopes.push_back(static_cast<const ExprWith *>(WithEnv->syntax()));
168 }
169 VarWithScopes.insert({&Var, std::move(WithScopes)});
170 Results.insert({&Var, LookupResult{LookupResultKind::FromWith, Def}});
171 } else {
172 // Check if this is a primop.
173 switch (lookupGlobalPrimOpInfo(Name)) {
175 assert(false && "primop name should be defined");
176 break;
178 Diagnostic &D =
179 Diags.emplace_back(Diagnostic::DK_PrimOpNeedsPrefix, Var.range());
180 D.fix("use `builtins.` prefix")
181 .edit(TextEdit::mkInsertion(Var.range().lCur(), "builtins."));
182 Results.insert(
183 {&Var, LookupResult{LookupResultKind::Undefined, nullptr}});
184 break;
185 }
187 // Otherwise, this variable is undefined.
188 Results.insert(
189 {&Var, LookupResult{LookupResultKind::Undefined, nullptr}});
190 Diagnostic &Diag =
191 Diags.emplace_back(Diagnostic::DK_UndefinedVariable, Var.range());
192 Diag << Var.id().name();
193 break;
194 }
195 }
196}
197
198void VariableLookupAnalysis::dfs(const ExprLambda &Lambda,
199 const std::shared_ptr<EnvNode> &Env) {
200 // Early exit for in-complete lambda.
201 if (!Lambda.body())
202 return;
203
204 // Create a new EnvNode, as lambdas may have formal & arg.
205 DefBuilder DBuilder(Diags);
206 assert(Lambda.arg());
207 const LambdaArg &Arg = *Lambda.arg();
208
209 // foo: body
210 // ^~~<------- add function argument.
211 if (Arg.id()) {
212 if (!Arg.formals()) {
213 ToDef.insert_or_assign(Arg.id(),
214 DBuilder.add(Arg.id()->name(), Arg.id(),
216 /*IsInheritFromBuiltin=*/false));
217 // Function arg cannot duplicate to it's formal.
218 // If it this unluckily happens, we would like to skip this definition.
219 } else if (!Arg.formals()->dedup().contains(Arg.id()->name())) {
220 ToDef.insert_or_assign(Arg.id(),
221 DBuilder.add(Arg.id()->name(), Arg.id(),
223 /*IsInheritFromBuiltin=*/false));
224 }
225 }
226
227 // { foo, bar, ... } : body
228 // ^~~~~~~~~<-------------- add function formals.
229
230 // This section differentiates between formal parameters with an argument and
231 // without. Example:
232 //
233 // { foo }@arg : use arg
234 //
235 // In this case, the definition of `foo` is not used directly; however, it
236 // might be accessed via arg.foo. Therefore, the severity of an unused formal
237 // parameter is reduced in this scenario.
238 if (Arg.formals()) {
239 for (const auto &[Name, Formal] : Arg.formals()->dedup()) {
243 ToDef.insert_or_assign(Formal->id(),
244 DBuilder.add(Name, Formal->id(), Source,
245 /*IsInheritFromBuiltin=*/false));
246 }
247 }
248
249 auto NewEnv = std::make_shared<EnvNode>(Env, DBuilder.finish(), &Lambda);
250
251 if (Arg.formals()) {
252 for (const auto &Formal : Arg.formals()->members()) {
253 if (const Expr *Def = Formal->defaultExpr()) {
254 dfs(*Def, NewEnv);
255 }
256 }
257 }
258
259 dfs(*Lambda.body(), NewEnv);
260
261 emitEnvLivenessWarning(NewEnv);
262}
263
264void VariableLookupAnalysis::dfsDynamicAttrs(
265 const std::vector<Attribute> &DynamicAttrs,
266 const std::shared_ptr<EnvNode> &Env) {
267 for (const auto &Attr : DynamicAttrs) {
268 if (!Attr.value())
269 continue;
270 dfs(Attr.key(), Env);
271 dfs(*Attr.value(), Env);
272 }
273}
274
275std::shared_ptr<EnvNode> VariableLookupAnalysis::dfsAttrs(
276 const SemaAttrs &SA, const std::shared_ptr<EnvNode> &Env,
277 const Node *Syntax, Definition::DefinitionSource Source) {
278 if (SA.isRecursive()) {
279 // rec { }, or let ... in ...
280 DefBuilder DB(Diags);
281 // For each static names, create a name binding.
282 for (const auto &[Name, Attr] : SA.staticAttrs()) {
283 ToDef.insert_or_assign(
284 &Attr.key(),
285 DB.add(Name, &Attr.key(), Source, checkInheritedFromBuiltin(Attr)));
286 }
287
288 auto NewEnv = std::make_shared<EnvNode>(Env, DB.finish(), Syntax);
289
290 for (const auto &[_, Attr] : SA.staticAttrs()) {
291 if (!Attr.value())
292 continue;
295 dfs(*Attr.value(), NewEnv);
296 } else {
297 assert(Attr.kind() == Attribute::AttributeKind::Inherit);
298 dfs(*Attr.value(), Env);
299 }
300 }
301
302 dfsDynamicAttrs(SA.dynamicAttrs(), NewEnv);
303 return NewEnv;
304 }
305
306 // Non-recursive. Dispatch nested node with old Env
307 for (const auto &[_, Attr] : SA.staticAttrs()) {
308 if (!Attr.value())
309 continue;
310 dfs(*Attr.value(), Env);
311 }
312
313 dfsDynamicAttrs(SA.dynamicAttrs(), Env);
314 return Env;
315};
316
317void VariableLookupAnalysis::dfs(const ExprAttrs &Attrs,
318 const std::shared_ptr<EnvNode> &Env) {
319 const SemaAttrs &SA = Attrs.sema();
320 std::shared_ptr<EnvNode> NewEnv =
321 dfsAttrs(SA, Env, &Attrs, Definition::DS_Rec);
322 if (NewEnv != Env) {
323 assert(Attrs.isRecursive() &&
324 "NewEnv must be created for recursive attrset");
325 if (!NewEnv->isLive()) {
326 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_ExtraRecursive,
327 Attrs.rec()->range());
328 D.fix("remove `rec` keyword")
329 .edit(TextEdit::mkRemoval(Attrs.rec()->range()));
331 }
332 }
333}
334
335void VariableLookupAnalysis::dfs(const ExprLet &Let,
336 const std::shared_ptr<EnvNode> &Env) {
337
338 // Obtain the env object suitable for "in" expression.
339 auto GetLetEnv = [&Env, &Let, this]() -> std::shared_ptr<EnvNode> {
340 // This is an empty let ... in ... expr, definitely anti-pattern in
341 // nix language. Create a trivial env and return.
342 if (!Let.attrs()) {
343 auto NewEnv = std::make_shared<EnvNode>(Env, EnvNode::DefMap{}, &Let);
344 return NewEnv;
345 }
346
347 // If there are some attributes actually, create a new env.
348 const SemaAttrs &SA = Let.attrs()->sema();
349 assert(SA.isRecursive() && "let ... in ... attrset must be recursive");
350 return dfsAttrs(SA, Env, &Let, Definition::DS_Let);
351 };
352
353 auto LetEnv = GetLetEnv();
354
355 if (Let.expr())
356 dfs(*Let.expr(), LetEnv);
357 emitEnvLivenessWarning(LetEnv);
358}
359
360void VariableLookupAnalysis::trivialDispatch(
361 const Node &Root, const std::shared_ptr<EnvNode> &Env) {
362 for (const Node *Ch : Root.children()) {
363 if (!Ch)
364 continue;
365 dfs(*Ch, Env);
366 }
367}
368
369void VariableLookupAnalysis::dfs(const ExprWith &With,
370 const std::shared_ptr<EnvNode> &Env) {
371 auto NewEnv = std::make_shared<EnvNode>(Env, EnvNode::DefMap{}, &With);
372 if (!WithDefs.contains(&With)) {
373 auto NewDef =
374 std::make_shared<Definition>(&With.kwWith(), Definition::DS_With);
375 ToDef.insert_or_assign(&With.kwWith(), NewDef);
376 WithDefs.insert_or_assign(&With, NewDef);
377 }
378
379 if (With.with())
380 dfs(*With.with(), Env);
381
382 if (With.expr())
383 dfs(*With.expr(), NewEnv);
384
385 if (WithDefs.at(&With)->uses().empty()) {
386 Diagnostic &D =
387 Diags.emplace_back(Diagnostic::DK_ExtraWith, With.kwWith().range());
388 Fix &F = D.fix("remove `with` expression")
390 if (With.tokSemi())
392 if (With.with())
393 F.edit(TextEdit::mkRemoval(With.with()->range()));
394 }
395}
396
397bool isBuiltinConstant(const std::string &Name) {
398 if (Name.starts_with("_"))
399 return false;
400 return Constants.contains(Name) || Constants.contains("__" + Name);
401}
402
403void VariableLookupAnalysis::checkBuiltins(const ExprSelect &Sel) {
404 if (!Sel.path())
405 return;
406
407 if (Sel.expr().kind() != Node::NK_ExprVar)
408 return;
409
410 const auto &Builtins = static_cast<const ExprVar &>(Sel.expr());
411 if (Builtins.id().name() != "builtins")
412 return;
413
414 const auto &AP = *Sel.path();
415
416 if (AP.names().size() != 1)
417 return;
418
419 AttrName &First = *AP.names()[0];
420 if (!First.isStatic())
421 return;
422
423 const auto &Name = First.staticName();
424
425 switch (lookupGlobalPrimOpInfo(Name)) {
427 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpRemovablePrefix,
428 Builtins.range());
429 Fix &F =
430 D.fix("remove `builtins.` prefix")
431 .edit(TextEdit::mkRemoval(Builtins.range())); // remove `builtins`
432
433 if (Sel.dot()) {
434 // remove the dot also.
435 F.edit(TextEdit::mkRemoval(Sel.dot()->range()));
436 }
437 return;
438 }
440 return;
442 if (!isBuiltinConstant(Name)) {
443 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpUnknown,
444 AP.names()[0]->range());
445 D << Name;
446 return;
447 }
448 }
449}
450
451void VariableLookupAnalysis::dfs(const Node &Root,
452 const std::shared_ptr<EnvNode> &Env) {
453 Envs.insert({&Root, Env});
454 switch (Root.kind()) {
455 case Node::NK_ExprVar: {
456 const auto &Var = static_cast<const ExprVar &>(Root);
457 lookupVar(Var, Env);
458 break;
459 }
460 case Node::NK_ExprLambda: {
461 const auto &Lambda = static_cast<const ExprLambda &>(Root);
462 dfs(Lambda, Env);
463 break;
464 }
465 case Node::NK_ExprAttrs: {
466 const auto &Attrs = static_cast<const ExprAttrs &>(Root);
467 dfs(Attrs, Env);
468 break;
469 }
470 case Node::NK_ExprLet: {
471 const auto &Let = static_cast<const ExprLet &>(Root);
472 dfs(Let, Env);
473 break;
474 }
475 case Node::NK_ExprWith: {
476 const auto &With = static_cast<const ExprWith &>(Root);
477 dfs(With, Env);
478 break;
479 }
480 case Node::NK_ExprSelect: {
481 trivialDispatch(Root, Env);
482 const auto &Sel = static_cast<const ExprSelect &>(Root);
483 checkBuiltins(Sel);
484 break;
485 }
486 default:
487 trivialDispatch(Root, Env);
488 }
489}
490
492 // Create a basic env
493 DefBuilder DB(Diags);
494
495 for (const auto &[Name, Info] : PrimOpsInfo) {
496 if (!Info.Internal) {
497 // Only add non-internal primops without "__" prefix.
498 DB.addBuiltin(Name);
499 }
500 }
501
502 for (const auto &Builtin : Constants)
503 DB.addBuiltin(Builtin);
504
505 DB.addBuiltin("builtins");
506 // This is an undocumented keyword actually.
507 DB.addBuiltin(std::string("__curPos"));
508
509 auto Env = std::make_shared<EnvNode>(nullptr, DB.finish(), nullptr);
510
511 dfs(Root, Env);
512}
513
515 : Diags(Diags) {}
516
518 if (!Envs.contains(N))
519 return nullptr;
520 return Envs.at(N).get();
521}
bool isBuiltinConstant(const std::string &Name)
Lookup variable names, from it's parent scope.
const std::string & staticName() const
Definition Attrs.h:50
bool isStatic() const
Definition Attrs.h:40
const std::vector< std::shared_ptr< AttrName > > & names() const
Definition Attrs.h:100
Node & key() const
Definition Attrs.h:217
Expr * value() const
Definition Attrs.h:219
AttributeKind kind() const
Definition Attrs.h:221
@ InheritFrom
inherit (expr) a b c
Definition Attrs.h:202
@ Inherit
inherit a b c;
Definition Attrs.h:200
DefinitionSource
"Source" information so we can know where the def comes from.
@ DS_Rec
From recursive attribute set. e.g. rec { }.
@ DS_LambdaArg
From ambda arg e.g. a: a + 1.
@ DS_LambdaNoArg_Formal
From lambda (noarg) formal, e.g. { a }: a + 1.
@ DS_Builtin
Builtin names.
@ DS_LambdaWithArg_Arg
From lambda (with @arg) arg, e.g. a in { foo }@a: foo + 1.
@ DS_With
From with <expr>;.
@ DS_LambdaWithArg_Formal
From lambda (with @arg) formal, e.g. foo in { foo }@a: foo + 1.
@ DS_Let
From let ... in ...
Fix & fix(std::string Message)
Definition Diagnostic.h:203
A set of variable definitions, which may inherit parent environment.
bool isLive() const
std::map< std::string, std::shared_ptr< Definition > > DefMap
bool isRecursive() const
Definition Attrs.h:287
const SemaAttrs & sema() const
Definition Attrs.h:289
const Misc * rec() const
Definition Attrs.h:285
Expr * body() const
Definition Lambda.h:119
LambdaArg * arg() const
Definition Lambda.h:118
const ExprAttrs * attrs() const
Definition Expr.h:151
const Expr * expr() const
Definition Expr.h:152
Expr & expr() const
Definition Expr.h:22
AttrPath * path() const
Definition Expr.h:31
Dot * dot() const
Definition Expr.h:27
const Identifier & id() const
Definition Simple.h:200
const Misc & kwWith() const
Definition Expr.h:174
Expr * with() const
Definition Expr.h:176
const Misc * tokSemi() const
Definition Expr.h:175
Expr * expr() const
Definition Expr.h:177
Fix & edit(TextEdit Edit)
Definition Diagnostic.h:65
const FormalVector & members() const
Definition Lambda.h:71
const std::map< std::string, const Formal * > & dedup()
Deduplicated formals.
Definition Lambda.h:74
const std::string & name() const
Definition Basic.h:120
Formals * formals() const
Definition Lambda.h:101
Identifier * id() const
Definition Lambda.h:99
LexerCursor lCur() const
Definition Range.h:116
NodeKind kind() const
Definition Basic.h:34
LexerCursorRange range() const
Definition Basic.h:35
virtual ChildVector children() const =0
void tag(DiagnosticTag Tag)
Definition Diagnostic.h:96
Attribute set after deduplication.
Definition Attrs.h:236
bool isRecursive() const
If the attribute set is rec.
Definition Attrs.h:269
const std::vector< Attribute > & dynamicAttrs() const
Dynamic attributes, require evaluation to get the key.
Definition Attrs.h:264
const std::map< std::string, Attribute > & staticAttrs() const
Static attributes, do not require evaluation to get the key.
Definition Attrs.h:257
static TextEdit mkRemoval(LexerCursorRange RemovingRange)
Definition Diagnostic.h:39
static TextEdit mkInsertion(LexerCursor P, std::string NewText)
Definition Diagnostic.h:35
const EnvNode * env(const Node *N) const
void runOnAST(const Node &Root)
Perform variable lookup analysis (def-use) on AST.
VariableLookupAnalysis(std::vector< Diagnostic > &Diags)
PrimopLookupResult lookupGlobalPrimOpInfo(const std::string &Name)
Look up information about a global primop by name.
std::map< std::string, nixf::PrimOpInfo > PrimOpsInfo
@ PrefixedFound
The primop was found, but needs "builtin." prefix.
Definition PrimOpInfo.h:44
@ NotFound
The primop was not found.
Definition PrimOpInfo.h:46
@ Found
The primop was found with an exact match.
Definition PrimOpInfo.h:42