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()) {
163 std::vector<const ExprWith *> WithScopes;
164 for (
const auto *WithEnv : WithEnvs) {
165 Def = WithDefs.at(WithEnv->syntax());
167 WithScopes.push_back(
static_cast<const ExprWith *
>(WithEnv->syntax()));
169 VarWithScopes.insert({&Var, std::move(WithScopes)});
175 assert(
false &&
"primop name should be defined");
179 Diags.emplace_back(Diagnostic::DK_PrimOpNeedsPrefix, Var.
range());
180 D.
fix(
"use `builtins.` prefix")
191 Diags.emplace_back(Diagnostic::DK_UndefinedVariable, Var.
range());
198void VariableLookupAnalysis::dfs(
const ExprLambda &Lambda,
199 const std::shared_ptr<EnvNode> &Env) {
205 DefBuilder DBuilder(Diags);
206 assert(Lambda.
arg());
207 const LambdaArg &Arg = *Lambda.
arg();
213 ToDef.insert_or_assign(Arg.
id(),
214 DBuilder.add(Arg.
id()->
name(), Arg.
id(),
220 ToDef.insert_or_assign(Arg.
id(),
221 DBuilder.add(Arg.
id()->
name(), Arg.
id(),
239 for (
const auto &[Name, Formal] : Arg.
formals()->
dedup()) {
243 ToDef.insert_or_assign(Formal->id(),
244 DBuilder.add(Name, Formal->id(), Source,
249 auto NewEnv = std::make_shared<EnvNode>(Env, DBuilder.finish(), &Lambda);
253 if (
const Expr *Def = Formal->defaultExpr()) {
259 dfs(*Lambda.
body(), NewEnv);
261 emitEnvLivenessWarning(NewEnv);
264void VariableLookupAnalysis::dfsDynamicAttrs(
265 const std::vector<Attribute> &DynamicAttrs,
266 const std::shared_ptr<EnvNode> &Env) {
267 for (
const auto &Attr : DynamicAttrs) {
270 dfs(Attr.
key(), Env);
271 dfs(*Attr.
value(), Env);
275std::shared_ptr<EnvNode> VariableLookupAnalysis::dfsAttrs(
276 const SemaAttrs &SA,
const std::shared_ptr<EnvNode> &Env,
280 DefBuilder DB(Diags);
282 for (
const auto &[Name, Attr] : SA.
staticAttrs()) {
283 ToDef.insert_or_assign(
285 DB.add(Name, &Attr.
key(), Source, checkInheritedFromBuiltin(Attr)));
288 auto NewEnv = std::make_shared<EnvNode>(Env, DB.finish(), Syntax);
295 dfs(*Attr.
value(), NewEnv);
298 dfs(*Attr.
value(), Env);
310 dfs(*Attr.
value(), Env);
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 =
324 "NewEnv must be created for recursive attrset");
325 if (!NewEnv->isLive()) {
326 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_ExtraRecursive,
328 D.
fix(
"remove `rec` keyword")
335void VariableLookupAnalysis::dfs(
const ExprLet &Let,
336 const std::shared_ptr<EnvNode> &Env) {
339 auto GetLetEnv = [&Env, &Let,
this]() -> std::shared_ptr<EnvNode> {
348 const SemaAttrs &SA = Let.
attrs()->
sema();
349 assert(SA.
isRecursive() &&
"let ... in ... attrset must be recursive");
353 auto LetEnv = GetLetEnv();
356 dfs(*Let.
expr(), LetEnv);
357 emitEnvLivenessWarning(LetEnv);
360void VariableLookupAnalysis::trivialDispatch(
361 const Node &Root,
const std::shared_ptr<EnvNode> &Env) {
362 for (
const Node *Ch : Root.
children()) {
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)) {
375 ToDef.insert_or_assign(&With.
kwWith(), NewDef);
376 WithDefs.insert_or_assign(&With, NewDef);
380 dfs(*With.
with(), Env);
383 dfs(*With.
expr(), NewEnv);
385 if (WithDefs.at(&With)->uses().empty()) {
387 Diags.emplace_back(Diagnostic::DK_ExtraWith, With.
kwWith().
range());
388 Fix &F = D.
fix(
"remove `with` expression")
398 if (Name.starts_with(
"_"))
400 return Constants.contains(Name) || Constants.contains(
"__" + Name);
403void VariableLookupAnalysis::checkBuiltins(
const ExprSelect &Sel) {
407 if (Sel.
expr().
kind() != Node::NK_ExprVar)
410 const auto &Builtins =
static_cast<const ExprVar &
>(Sel.
expr());
411 if (Builtins.id().name() !=
"builtins")
414 const auto &AP = *Sel.
path();
416 if (AP.names().size() != 1)
419 AttrName &First = *AP.
names()[0];
427 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpRemovablePrefix,
430 D.
fix(
"remove `builtins.` prefix")
443 Diagnostic &D = Diags.emplace_back(Diagnostic::DK_PrimOpUnknown,
444 AP.names()[0]->range());
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);
460 case Node::NK_ExprLambda: {
461 const auto &Lambda =
static_cast<const ExprLambda &
>(Root);
465 case Node::NK_ExprAttrs: {
466 const auto &Attrs =
static_cast<const ExprAttrs &
>(Root);
470 case Node::NK_ExprLet: {
471 const auto &Let =
static_cast<const ExprLet &
>(Root);
475 case Node::NK_ExprWith: {
476 const auto &With =
static_cast<const ExprWith &
>(Root);
480 case Node::NK_ExprSelect: {
481 trivialDispatch(Root, Env);
482 const auto &Sel =
static_cast<const ExprSelect &
>(Root);
487 trivialDispatch(Root, Env);
493 DefBuilder DB(Diags);
496 if (!Info.Internal) {
502 for (
const auto &Builtin : Constants)
503 DB.addBuiltin(Builtin);
505 DB.addBuiltin(
"builtins");
507 DB.addBuiltin(std::string(
"__curPos"));
509 auto Env = std::make_shared<EnvNode>(
nullptr, DB.finish(),
nullptr);
518 if (!Envs.contains(N))
520 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.