Skip to content

Commit

Permalink
nixd-lint: add an option that prints nix AST
Browse files Browse the repository at this point in the history
  • Loading branch information
inclyc committed Sep 22, 2023
1 parent 1599094 commit b994f59
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions nixd/tools/nixd-lint/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ nixd_lint = executable('nixd-lint'
, dependencies: [ boost
, nixdSyntax
, nixdSema
, nixdExpr
] + nix_all
, install: true
)
Expand Down
37 changes: 36 additions & 1 deletion nixd/tools/nixd-lint/nixd-lint.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "nixd/Expr/Expr.h"
#include "nixd/Sema/EvalContext.h"
#include "nixd/Sema/Lowering.h"
#include "nixd/Syntax/Diagnostic.h"
Expand Down Expand Up @@ -25,6 +26,9 @@ opt<std::string> Filename(Positional, desc("<input file>"), init("-"),

const OptionCategory *Cat[] = {&Misc};

opt<bool> DumpNixAST("dump-nix-ast", init(false),
desc("Dump the lowered nix AST"), cat(Misc));

static void printCodeLines(std::ostream &Out, const std::string &Prefix,
std::shared_ptr<nix::AbstractPos> BeginPos,
std::shared_ptr<nix::AbstractPos> EndPos,
Expand Down Expand Up @@ -74,6 +78,32 @@ static void printCodeLines(std::ostream &Out, const std::string &Prefix,
}
}

struct ASTDump : nixd::RecursiveASTVisitor<ASTDump> {
nix::SymbolTable &STable;
int Depth = 0;

bool traverseExpr(const nix::Expr *E) {
Depth++;
if (!nixd::RecursiveASTVisitor<ASTDump>::traverseExpr(E))
return false;
Depth--;
return true;
}

bool visitExpr(const nix::Expr *E) const {
if (!E)
return true;
for (int I = 0; I < Depth; I++) {
std::cout << " ";
}
std::cout << nixd::getExprName(E) << ": ";
E->show(STable, std::cout);
std::cout << " ";
std::cout << "\n";
return true;
}
};

int main(int argc, char *argv[]) {
HideUnrelatedOptions(Cat);
ParseCommandLineOptions(argc, argv, "nixd linter", nullptr,
Expand Down Expand Up @@ -102,7 +132,12 @@ int main(int argc, char *argv[]) {
nixd::EvalContext Ctx;
nixd::Lowering Lowering{
.STable = *STable, .PTable = *PTable, .Diags = Data.Diags, .Ctx = Ctx};
Lowering.lower(Data.Result);
nix::Expr *NixTree = Lowering.lower(Data.Result);

if (DumpNixAST) {
ASTDump D{.STable = *STable};
D.traverseExpr(NixTree);
}

for (const auto &Diag : Data.Diags) {
auto BeginPos = (*PTable)[Diag.Range.Begin];
Expand Down

0 comments on commit b994f59

Please sign in to comment.