14std::set<std::string> Constants{
15 "true",
"false",
"null",
16 "__currentTime",
"__currentSystem",
"__nixVersion",
17 "__storeDir",
"__langVersion",
"__importNative",
18 "__traceVerbose",
"__nixPath",
"derivation",
25 std::vector<Diagnostic> &Diags;
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});
36 DefBuilder(std::vector<Diagnostic> &Diags) : Diags(Diags) {}
38 void addBuiltin(std::string Name) {
43 [[nodiscard(
"Record ToDef Map!")]] std::shared_ptr<Definition>
45 bool IsInheritFromBuiltin) {
47 if (PrimOpLookup == PrimopLookupResult::Found && !IsInheritFromBuiltin) {
50 Diags.emplace_back(Diagnostic::DK_PrimOpOverridden, Entry->
range());
55 if (Constants.contains(Name)) {
57 Diags.emplace_back(Diagnostic::DK_ConstantOverridden, Entry->
range());
61 return addSimple(std::move(Name), Entry, Source);
72bool checkInheritedFromBuiltin(
const Attribute &Attr) {
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");
81 if (Select.expr().kind() == Node::NK_ExprVar) {
82 const auto &Var =
static_cast<const ExprVar &
>(Select.expr());
83 return Var.
id().
name() ==
"builtins";
91 for (
const auto &[_, D] : Defs) {
92 if (!D->uses().empty())
98void VariableLookupAnalysis::emitEnvLivenessWarning(
99 const std::shared_ptr<EnvNode> &NewEnv) {
100 for (
const auto &[Name, Def] : NewEnv->defs()) {
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;
121 assert(
false &&
"liveness diagnostic encountered an unknown source!");
122 __builtin_unreachable();
125 Diagnostic &D = Diags.emplace_back(Kind, Def->syntax()->range());
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);
151 if (CurEnv->isWith()) {
152 WithEnvs.emplace_back(CurEnv);
159 }
else if (!WithEnvs.empty()) {
160 for (
const auto *WithEnv : WithEnvs) {
161 Def = WithDefs.at(WithEnv->syntax());
169 assert(
false &&
"primop name should be defined");
173 Diags.emplace_back(Diagnostic::DK_PrimOpNeedsPrefix, Var.
range());
174 D.
fix(
"use `builtins.` prefix")
185 Diags.emplace_back(Diagnostic::DK_UndefinedVariable, Var.
range());
192void VariableLookupAnalysis::dfs(
const ExprLambda &Lambda,
193 const std::shared_ptr<EnvNode> &Env) {
199 DefBuilder DBuilder(Diags);
200 assert(Lambda.
arg());
201 const LambdaArg &Arg = *Lambda.
arg();
207 ToDef.insert_or_assign(Arg.
id(),
208 DBuilder.add(Arg.
id()->
name(), Arg.
id(),
214 ToDef.insert_or_assign(Arg.
id(),
215 DBuilder.add(Arg.
id()->
name(), Arg.
id(),
233 for (
const auto &[Name, Formal] : Arg.
formals()->
dedup()) {
237 ToDef.insert_or_assign(Formal->id(),
238 DBuilder.add(Name, Formal->id(), Source,
243 auto NewEnv = std::make_shared<EnvNode>(Env, DBuilder.finish(), &Lambda);
247 if (
const Expr *Def = Formal->defaultExpr()) {
253 dfs(*Lambda.
body(), NewEnv);
255 emitEnvLivenessWarning(NewEnv);
258void VariableLookupAnalysis::dfsDynamicAttrs(
259 const std::vector<Attribute> &DynamicAttrs,
260 const std::shared_ptr<EnvNode> &Env) {
261 for (
const auto &Attr : DynamicAttrs) {
264 dfs(Attr.
key(), Env);
265 dfs(*Attr.
value(), Env);
269std::shared_ptr<EnvNode> VariableLookupAnalysis::dfsAttrs(
270 const SemaAttrs &SA,
const std::shared_ptr<EnvNode> &Env,
274 DefBuilder DB(Diags);
276 for (
const auto &[Name, Attr] : SA.
staticAttrs()) {
277 ToDef.insert_or_assign(
279 DB.add(Name, &Attr.
key(), Source, checkInheritedFromBuiltin(Attr)));
282 auto NewEnv = std::make_shared<EnvNode>(Env, DB.finish(), Syntax);
289 dfs(*Attr.
value(), NewEnv);
292 dfs(*Attr.
value(), Env);
304 dfs(*Attr.
value(), Env);
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 =
318 "NewEnv must be created for recursive attrset");
319 if (!NewEnv->isLive()) {
320 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_ExtraRecursive,
322 D.
fix(
"remove `rec` keyword")
329void VariableLookupAnalysis::dfs(
const ExprLet &Let,
330 const std::shared_ptr<EnvNode> &Env) {
333 auto GetLetEnv = [&Env, &Let,
this]() -> std::shared_ptr<EnvNode> {
342 const SemaAttrs &SA = Let.
attrs()->
sema();
343 assert(SA.
isRecursive() &&
"let ... in ... attrset must be recursive");
347 auto LetEnv = GetLetEnv();
350 dfs(*Let.
expr(), LetEnv);
351 emitEnvLivenessWarning(LetEnv);
354void VariableLookupAnalysis::trivialDispatch(
355 const Node &Root,
const std::shared_ptr<EnvNode> &Env) {
356 for (
const Node *Ch : Root.
children()) {
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)) {
369 ToDef.insert_or_assign(&With.
kwWith(), NewDef);
370 WithDefs.insert_or_assign(&With, NewDef);
374 dfs(*With.
with(), Env);
377 dfs(*With.
expr(), NewEnv);
379 if (WithDefs.at(&With)->uses().empty()) {
381 Diags.emplace_back(Diagnostic::DK_ExtraWith, With.
kwWith().
range());
382 Fix &F = D.
fix(
"remove `with` expression")
392 if (Name.starts_with(
"_"))
394 return Constants.contains(Name) || Constants.contains(
"__" + Name);
397void VariableLookupAnalysis::checkBuiltins(
const ExprSelect &Sel) {
401 if (Sel.
expr().
kind() != Node::NK_ExprVar)
404 const auto &Builtins =
static_cast<const ExprVar &
>(Sel.
expr());
405 if (Builtins.id().name() !=
"builtins")
408 const auto &AP = *Sel.
path();
410 if (AP.names().size() != 1)
413 AttrName &First = *AP.
names()[0];
421 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpRemovablePrefix,
424 D.
fix(
"remove `builtins.` prefix")
437 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpUnknown,
438 AP.names()[0]->range());
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);
454 case Node::NK_ExprLambda: {
455 const auto &Lambda =
static_cast<const ExprLambda &
>(Root);
459 case Node::NK_ExprAttrs: {
460 const auto &Attrs =
static_cast<const ExprAttrs &
>(Root);
464 case Node::NK_ExprLet: {
465 const auto &Let =
static_cast<const ExprLet &
>(Root);
469 case Node::NK_ExprWith: {
470 const auto &With =
static_cast<const ExprWith &
>(Root);
474 case Node::NK_ExprSelect: {
475 trivialDispatch(Root, Env);
476 const auto &Sel =
static_cast<const ExprSelect &
>(Root);
481 trivialDispatch(Root, Env);
487 DefBuilder DB(Diags);
490 if (!Info.Internal) {
496 for (
const auto &Builtin : Constants)
497 DB.addBuiltin(Builtin);
499 DB.addBuiltin(
"builtins");
501 DB.addBuiltin(std::string(
"__curPos"));
503 auto Env = std::make_shared<EnvNode>(
nullptr, DB.finish(),
nullptr);
512 if (!Envs.contains(N))
514 return Envs.at(N).get();
bool isBuiltinConstant(const std::string &Name)
Lookup variable names, from it's parent scope.
const std::string & staticName() const
const std::vector< std::shared_ptr< AttrName > > & names() const
AttributeKind kind() const
@ InheritFrom
inherit (expr) a b c
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)
A set of variable definitions, which may inherit parent environment.
std::map< std::string, std::shared_ptr< Definition > > DefMap
const SemaAttrs & sema() const
const ExprAttrs * attrs() const
const Expr * expr() const
const Identifier & id() const
const Misc & kwWith() const
const Misc * tokSemi() const
Fix & edit(TextEdit Edit)
const std::string & name() const
Formals * formals() const
LexerCursorRange range() const
virtual ChildVector children() const =0
void tag(DiagnosticTag Tag)
Attribute set after deduplication.
bool isRecursive() const
If the attribute set is rec.
const std::vector< Attribute > & dynamicAttrs() const
Dynamic attributes, require evaluation to get the key.
const std::map< std::string, Attribute > & staticAttrs() const
Static attributes, do not require evaluation to get the key.
static TextEdit mkRemoval(LexerCursorRange RemovingRange)
static TextEdit mkInsertion(LexerCursor P, std::string NewText)
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.
@ NotFound
The primop was not found.
@ Found
The primop was found with an exact match.