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 for (const auto *WithEnv : WithEnvs) {
161 Def = WithDefs.at(WithEnv->syntax());
162 Def->usedBy(Var);
163 }
164 Results.insert({&Var, LookupResult{LookupResultKind::FromWith, Def}});
165 } else {
166 // Check if this is a primop.
167 switch (lookupGlobalPrimOpInfo(Name)) {
169 assert(false && "primop name should be defined");
170 break;
172 Diagnostic &D =
173 Diags.emplace_back(Diagnostic::DK_PrimOpNeedsPrefix, Var.range());
174 D.fix("use `builtins.` prefix")
175 .edit(TextEdit::mkInsertion(Var.range().lCur(), "builtins."));
176 Results.insert(
177 {&Var, LookupResult{LookupResultKind::Undefined, nullptr}});
178 break;
179 }
181 // Otherwise, this variable is undefined.
182 Results.insert(
183 {&Var, LookupResult{LookupResultKind::Undefined, nullptr}});
184 Diagnostic &Diag =
185 Diags.emplace_back(Diagnostic::DK_UndefinedVariable, Var.range());
186 Diag << Var.id().name();
187 break;
188 }
189 }
190}
191
192void VariableLookupAnalysis::dfs(const ExprLambda &Lambda,
193 const std::shared_ptr<EnvNode> &Env) {
194 // Early exit for in-complete lambda.
195 if (!Lambda.body())
196 return;
197
198 // Create a new EnvNode, as lambdas may have formal & arg.
199 DefBuilder DBuilder(Diags);
200 assert(Lambda.arg());
201 const LambdaArg &Arg = *Lambda.arg();
202
203 // foo: body
204 // ^~~<------- add function argument.
205 if (Arg.id()) {
206 if (!Arg.formals()) {
207 ToDef.insert_or_assign(Arg.id(),
208 DBuilder.add(Arg.id()->name(), Arg.id(),
210 /*IsInheritFromBuiltin=*/false));
211 // Function arg cannot duplicate to it's formal.
212 // If it this unluckily happens, we would like to skip this definition.
213 } else if (!Arg.formals()->dedup().contains(Arg.id()->name())) {
214 ToDef.insert_or_assign(Arg.id(),
215 DBuilder.add(Arg.id()->name(), Arg.id(),
217 /*IsInheritFromBuiltin=*/false));
218 }
219 }
220
221 // { foo, bar, ... } : body
222 // ^~~~~~~~~<-------------- add function formals.
223
224 // This section differentiates between formal parameters with an argument and
225 // without. Example:
226 //
227 // { foo }@arg : use arg
228 //
229 // In this case, the definition of `foo` is not used directly; however, it
230 // might be accessed via arg.foo. Therefore, the severity of an unused formal
231 // parameter is reduced in this scenario.
232 if (Arg.formals()) {
233 for (const auto &[Name, Formal] : Arg.formals()->dedup()) {
237 ToDef.insert_or_assign(Formal->id(),
238 DBuilder.add(Name, Formal->id(), Source,
239 /*IsInheritFromBuiltin=*/false));
240 }
241 }
242
243 auto NewEnv = std::make_shared<EnvNode>(Env, DBuilder.finish(), &Lambda);
244
245 if (Arg.formals()) {
246 for (const auto &Formal : Arg.formals()->members()) {
247 if (const Expr *Def = Formal->defaultExpr()) {
248 dfs(*Def, NewEnv);
249 }
250 }
251 }
252
253 dfs(*Lambda.body(), NewEnv);
254
255 emitEnvLivenessWarning(NewEnv);
256}
257
258void VariableLookupAnalysis::dfsDynamicAttrs(
259 const std::vector<Attribute> &DynamicAttrs,
260 const std::shared_ptr<EnvNode> &Env) {
261 for (const auto &Attr : DynamicAttrs) {
262 if (!Attr.value())
263 continue;
264 dfs(Attr.key(), Env);
265 dfs(*Attr.value(), Env);
266 }
267}
268
269std::shared_ptr<EnvNode> VariableLookupAnalysis::dfsAttrs(
270 const SemaAttrs &SA, const std::shared_ptr<EnvNode> &Env,
271 const Node *Syntax, Definition::DefinitionSource Source) {
272 if (SA.isRecursive()) {
273 // rec { }, or let ... in ...
274 DefBuilder DB(Diags);
275 // For each static names, create a name binding.
276 for (const auto &[Name, Attr] : SA.staticAttrs()) {
277 ToDef.insert_or_assign(
278 &Attr.key(),
279 DB.add(Name, &Attr.key(), Source, checkInheritedFromBuiltin(Attr)));
280 }
281
282 auto NewEnv = std::make_shared<EnvNode>(Env, DB.finish(), Syntax);
283
284 for (const auto &[_, Attr] : SA.staticAttrs()) {
285 if (!Attr.value())
286 continue;
289 dfs(*Attr.value(), NewEnv);
290 } else {
291 assert(Attr.kind() == Attribute::AttributeKind::Inherit);
292 dfs(*Attr.value(), Env);
293 }
294 }
295
296 dfsDynamicAttrs(SA.dynamicAttrs(), NewEnv);
297 return NewEnv;
298 }
299
300 // Non-recursive. Dispatch nested node with old Env
301 for (const auto &[_, Attr] : SA.staticAttrs()) {
302 if (!Attr.value())
303 continue;
304 dfs(*Attr.value(), Env);
305 }
306
307 dfsDynamicAttrs(SA.dynamicAttrs(), Env);
308 return Env;
309};
310
311void VariableLookupAnalysis::dfs(const ExprAttrs &Attrs,
312 const std::shared_ptr<EnvNode> &Env) {
313 const SemaAttrs &SA = Attrs.sema();
314 std::shared_ptr<EnvNode> NewEnv =
315 dfsAttrs(SA, Env, &Attrs, Definition::DS_Rec);
316 if (NewEnv != Env) {
317 assert(Attrs.isRecursive() &&
318 "NewEnv must be created for recursive attrset");
319 if (!NewEnv->isLive()) {
320 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_ExtraRecursive,
321 Attrs.rec()->range());
322 D.fix("remove `rec` keyword")
323 .edit(TextEdit::mkRemoval(Attrs.rec()->range()));
325 }
326 }
327}
328
329void VariableLookupAnalysis::dfs(const ExprLet &Let,
330 const std::shared_ptr<EnvNode> &Env) {
331
332 // Obtain the env object suitable for "in" expression.
333 auto GetLetEnv = [&Env, &Let, this]() -> std::shared_ptr<EnvNode> {
334 // This is an empty let ... in ... expr, definitely anti-pattern in
335 // nix language. Create a trivial env and return.
336 if (!Let.attrs()) {
337 auto NewEnv = std::make_shared<EnvNode>(Env, EnvNode::DefMap{}, &Let);
338 return NewEnv;
339 }
340
341 // If there are some attributes actually, create a new env.
342 const SemaAttrs &SA = Let.attrs()->sema();
343 assert(SA.isRecursive() && "let ... in ... attrset must be recursive");
344 return dfsAttrs(SA, Env, &Let, Definition::DS_Let);
345 };
346
347 auto LetEnv = GetLetEnv();
348
349 if (Let.expr())
350 dfs(*Let.expr(), LetEnv);
351 emitEnvLivenessWarning(LetEnv);
352}
353
354void VariableLookupAnalysis::trivialDispatch(
355 const Node &Root, const std::shared_ptr<EnvNode> &Env) {
356 for (const Node *Ch : Root.children()) {
357 if (!Ch)
358 continue;
359 dfs(*Ch, Env);
360 }
361}
362
363void VariableLookupAnalysis::dfs(const ExprWith &With,
364 const std::shared_ptr<EnvNode> &Env) {
365 auto NewEnv = std::make_shared<EnvNode>(Env, EnvNode::DefMap{}, &With);
366 if (!WithDefs.contains(&With)) {
367 auto NewDef =
368 std::make_shared<Definition>(&With.kwWith(), Definition::DS_With);
369 ToDef.insert_or_assign(&With.kwWith(), NewDef);
370 WithDefs.insert_or_assign(&With, NewDef);
371 }
372
373 if (With.with())
374 dfs(*With.with(), Env);
375
376 if (With.expr())
377 dfs(*With.expr(), NewEnv);
378
379 if (WithDefs.at(&With)->uses().empty()) {
380 Diagnostic &D =
381 Diags.emplace_back(Diagnostic::DK_ExtraWith, With.kwWith().range());
382 Fix &F = D.fix("remove `with` expression")
384 if (With.tokSemi())
386 if (With.with())
387 F.edit(TextEdit::mkRemoval(With.with()->range()));
388 }
389}
390
391bool isBuiltinConstant(const std::string &Name) {
392 if (Name.starts_with("_"))
393 return false;
394 return Constants.contains(Name) || Constants.contains("__" + Name);
395}
396
397void VariableLookupAnalysis::checkBuiltins(const ExprSelect &Sel) {
398 if (!Sel.path())
399 return;
400
401 if (Sel.expr().kind() != Node::NK_ExprVar)
402 return;
403
404 const auto &Builtins = static_cast<const ExprVar &>(Sel.expr());
405 if (Builtins.id().name() != "builtins")
406 return;
407
408 const auto &AP = *Sel.path();
409
410 if (AP.names().size() != 1)
411 return;
412
413 AttrName &First = *AP.names()[0];
414 if (!First.isStatic())
415 return;
416
417 const auto &Name = First.staticName();
418
419 switch (lookupGlobalPrimOpInfo(Name)) {
421 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpRemovablePrefix,
422 Builtins.range());
423 Fix &F =
424 D.fix("remove `builtins.` prefix")
425 .edit(TextEdit::mkRemoval(Builtins.range())); // remove `builtins`
426
427 if (Sel.dot()) {
428 // remove the dot also.
429 F.edit(TextEdit::mkRemoval(Sel.dot()->range()));
430 }
431 return;
432 }
434 return;
436 if (!isBuiltinConstant(Name)) {
437 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpUnknown,
438 AP.names()[0]->range());
439 D << Name;
440 return;
441 }
442 }
443}
444
445void VariableLookupAnalysis::dfs(const Node &Root,
446 const std::shared_ptr<EnvNode> &Env) {
447 Envs.insert({&Root, Env});
448 switch (Root.kind()) {
449 case Node::NK_ExprVar: {
450 const auto &Var = static_cast<const ExprVar &>(Root);
451 lookupVar(Var, Env);
452 break;
453 }
454 case Node::NK_ExprLambda: {
455 const auto &Lambda = static_cast<const ExprLambda &>(Root);
456 dfs(Lambda, Env);
457 break;
458 }
459 case Node::NK_ExprAttrs: {
460 const auto &Attrs = static_cast<const ExprAttrs &>(Root);
461 dfs(Attrs, Env);
462 break;
463 }
464 case Node::NK_ExprLet: {
465 const auto &Let = static_cast<const ExprLet &>(Root);
466 dfs(Let, Env);
467 break;
468 }
469 case Node::NK_ExprWith: {
470 const auto &With = static_cast<const ExprWith &>(Root);
471 dfs(With, Env);
472 break;
473 }
474 case Node::NK_ExprSelect: {
475 trivialDispatch(Root, Env);
476 const auto &Sel = static_cast<const ExprSelect &>(Root);
477 checkBuiltins(Sel);
478 break;
479 }
480 default:
481 trivialDispatch(Root, Env);
482 }
483}
484
486 // Create a basic env
487 DefBuilder DB(Diags);
488
489 for (const auto &[Name, Info] : PrimOpsInfo) {
490 if (!Info.Internal) {
491 // Only add non-internal primops without "__" prefix.
492 DB.addBuiltin(Name);
493 }
494 }
495
496 for (const auto &Builtin : Constants)
497 DB.addBuiltin(Builtin);
498
499 DB.addBuiltin("builtins");
500 // This is an undocumented keyword actually.
501 DB.addBuiltin(std::string("__curPos"));
502
503 auto Env = std::make_shared<EnvNode>(nullptr, DB.finish(), nullptr);
504
505 dfs(Root, Env);
506}
507
509 : Diags(Diags) {}
510
512 if (!Envs.contains(N))
513 return nullptr;
514 return Envs.at(N).get();
515}
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