Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
parser-state.hh
Go to the documentation of this file.
1#pragma once
3
4#include <limits>
5
6#include "nix/expr/eval.hh"
7#include "nix/expr/value.hh"
9
10namespace nix {
11
18{
19 const char * p;
20 size_t l;
21 bool hasIndentation;
22
23 operator std::string_view() const
24 {
25 return {p, l};
26 }
27};
28
30{
31 int beginOffset;
32 int endOffset;
33
34 // backup to recover from yyless(0)
35 int stashedBeginOffset, stashedEndOffset;
36
37 void stash()
38 {
39 stashedBeginOffset = beginOffset;
40 stashedEndOffset = endOffset;
41 }
42
43 void unstash()
44 {
45 beginOffset = stashedBeginOffset;
46 endOffset = stashedEndOffset;
47 }
48};
49
63class ToBeStringyExpr
64{
65private:
66 using Raw = std::variant<std::monostate, std::string_view, Expr *>;
67 Raw raw;
68
69public:
70 ToBeStringyExpr() = default;
71
72 ToBeStringyExpr(std::string_view v)
73 : raw(v)
74 {
75 }
76
77 ToBeStringyExpr(Expr * expr)
78 : raw(expr)
79 {
80 assert(expr);
81 }
82
91 template<class F>
92 void visit(const F & f)
93 {
94 std::visit(
96 [&](std::string_view str) { f(str); },
97 [&](Expr * expr) {
98 ExprString * str = dynamic_cast<ExprString *>(expr);
99 if (str)
100 f(str->v.string_view());
101 else
102 f(expr);
103 },
104 [](std::monostate) { unreachable(); }},
105 raw);
106 }
107
112 Expr * toExpr(Exprs & exprs)
113 {
114 return std::visit(
116 [&](std::string_view str) -> Expr * { return exprs.add<ExprString>(exprs.alloc, str); },
117 [&](Expr * expr) { return expr; },
118 [](std::monostate) -> Expr * { unreachable(); }},
119 raw);
120 }
121};
122
124{
133 int docCommentDistance = std::numeric_limits<int>::max();
134
141
145 DocCommentMap & positionToDocComment;
146
147 PosTable & positions;
148 PosTable::Origin origin;
149
150 PosIdx at(const ParserLocation & loc);
151};
152
154{
155 const LexerState & lexerState;
156 Exprs & exprs;
157 SymbolTable & symbols;
158 PosTable & positions;
159 Expr * result;
160 SourcePath basePath;
161 PosTable::Origin origin;
162 const ref<SourceAccessor> rootFS;
163 static constexpr Expr::AstSymbols s = StaticEvalSymbols::create().exprSymbols;
164 const EvalSettings & settings;
165
166 void dupAttr(const AttrSelectionPath & attrPath, const PosIdx pos, const PosIdx prevPos);
167 void dupAttr(Symbol attr, const PosIdx pos, const PosIdx prevPos);
168 void addAttr(
169 ExprAttrs * attrs,
170 AttrSelectionPath && attrPath,
171 const ParserLocation & loc,
172 Expr * e,
173 const ParserLocation & exprLoc);
174 void addAttr(ExprAttrs * attrs, AttrSelectionPath & attrPath, const Symbol & symbol, ExprAttrs::AttrDef && def);
175 void validateFormals(FormalsBuilder & formals, PosIdx pos = noPos, Symbol arg = {});
176 Expr * stripIndentation(const PosIdx pos, std::span<std::pair<PosIdx, std::variant<Expr *, StringToken>>> es);
177 PosIdx at(const ParserLocation & loc);
178};
179
180inline void ParserState::dupAttr(const AttrSelectionPath & attrPath, const PosIdx pos, const PosIdx prevPos)
181{
182 throw ParseError(
183 {.msg = HintFmt(
184 "attribute '%1%' already defined at %2%", showAttrSelectionPath(symbols, attrPath), positions[prevPos]),
185 .pos = positions[pos]});
186}
187
188inline void ParserState::dupAttr(Symbol attr, const PosIdx pos, const PosIdx prevPos)
189{
190 throw ParseError(
191 {.msg = HintFmt("attribute '%1%' already defined at %2%", symbols[attr], positions[prevPos]),
192 .pos = positions[pos]});
193}
194
195inline void ParserState::addAttr(
196 ExprAttrs * attrs,
197 AttrSelectionPath && attrPath,
198 const ParserLocation & loc,
199 Expr * e,
200 const ParserLocation & exprLoc)
201{
202 AttrSelectionPath::iterator i;
203 // All attrpaths have at least one attr
204 assert(!attrPath.empty());
205 auto pos = at(loc);
206 // Checking attrPath validity.
207 // ===========================
208 for (i = attrPath.begin(); i + 1 < attrPath.end(); i++) {
209 ExprAttrs * nested;
210 if (i->symbol) {
211 ExprAttrs::AttrDefs::iterator j = attrs->attrs->find(i->symbol);
212 if (j != attrs->attrs->end()) {
213 nested = dynamic_cast<ExprAttrs *>(j->second.e);
214 if (!nested) {
215 attrPath.erase(i + 1, attrPath.end());
216 dupAttr(attrPath, pos, j->second.pos);
217 }
218 } else {
219 nested = exprs.add<ExprAttrs>();
220 (*attrs->attrs)[i->symbol] = ExprAttrs::AttrDef(nested, pos);
221 }
222 } else {
223 nested = exprs.add<ExprAttrs>();
224 attrs->dynamicAttrs->push_back(ExprAttrs::DynamicAttrDef(i->expr, nested, pos));
225 }
226 attrs = nested;
227 }
228 // Expr insertion.
229 // ==========================
230 if (i->symbol) {
231 addAttr(attrs, attrPath, i->symbol, ExprAttrs::AttrDef(e, pos));
232 } else {
233 attrs->dynamicAttrs->push_back(ExprAttrs::DynamicAttrDef(i->expr, e, pos));
234 }
235
236 auto it = lexerState.positionToDocComment.find(pos);
237 if (it != lexerState.positionToDocComment.end()) {
238 e->setDocComment(it->second);
239 lexerState.positionToDocComment.emplace(at(exprLoc), it->second);
240 }
241}
242
247inline void
248ParserState::addAttr(ExprAttrs * attrs, AttrSelectionPath & attrPath, const Symbol & symbol, ExprAttrs::AttrDef && def)
249{
250 ExprAttrs::AttrDefs::iterator j = attrs->attrs->find(symbol);
251 if (j != attrs->attrs->end()) {
252 // This attr path is already defined. However, if both
253 // e and the expr pointed by the attr path are two attribute sets,
254 // we want to merge them.
255 // Otherwise, throw an error.
256 auto ae = dynamic_cast<ExprAttrs *>(def.e);
257 auto jAttrs = dynamic_cast<ExprAttrs *>(j->second.e);
258
259 // N.B. In a world in which we are less bound by our past mistakes, we
260 // would also test that jAttrs and ae are not recursive. The effect of
261 // not doing so is that any `rec` marker on ae is discarded, and any
262 // `rec` marker on jAttrs will apply to the attributes in ae.
263 // See https://github.com/NixOS/nix/issues/9020.
264 if (jAttrs && ae) {
265 if (ae->inheritFromExprs && !jAttrs->inheritFromExprs)
266 jAttrs->inheritFromExprs = std::make_unique<std::pmr::vector<Expr *>>();
267 for (auto & ad : *ae->attrs) {
268 if (ad.second.kind == ExprAttrs::AttrDef::Kind::InheritedFrom) {
269 auto & sel = dynamic_cast<ExprSelect &>(*ad.second.e);
270 auto & from = dynamic_cast<ExprInheritFrom &>(*sel.e);
271 from.displ += jAttrs->inheritFromExprs->size();
272 }
273 attrPath.emplace_back(AttrName(ad.first));
274 addAttr(jAttrs, attrPath, ad.first, std::move(ad.second));
275 attrPath.pop_back();
276 }
277 ae->attrs->clear();
278 jAttrs->dynamicAttrs->insert(
279 jAttrs->dynamicAttrs->end(),
280 std::make_move_iterator(ae->dynamicAttrs->begin()),
281 std::make_move_iterator(ae->dynamicAttrs->end()));
282 ae->dynamicAttrs->clear();
283 if (ae->inheritFromExprs) {
284 jAttrs->inheritFromExprs->insert(
285 jAttrs->inheritFromExprs->end(),
286 std::make_move_iterator(ae->inheritFromExprs->begin()),
287 std::make_move_iterator(ae->inheritFromExprs->end()));
288 ae->inheritFromExprs = nullptr;
289 }
290 } else {
291 dupAttr(attrPath, def.pos, j->second.pos);
292 }
293 } else {
294 // This attr path is not defined. Let's create it.
295 attrs->attrs->emplace(symbol, def);
296 def.e->setName(symbol);
297 }
298}
299
300inline void ParserState::validateFormals(FormalsBuilder & formals, PosIdx pos, Symbol arg)
301{
302 std::sort(formals.formals.begin(), formals.formals.end(), [](const auto & a, const auto & b) {
303 return std::tie(a.name, a.pos) < std::tie(b.name, b.pos);
304 });
305
306 std::optional<std::pair<Symbol, PosIdx>> duplicate;
307 for (size_t i = 0; i + 1 < formals.formals.size(); i++) {
308 if (formals.formals[i].name != formals.formals[i + 1].name)
309 continue;
310 std::pair thisDup{formals.formals[i].name, formals.formals[i + 1].pos};
311 duplicate = std::min(thisDup, duplicate.value_or(thisDup));
312 }
313 if (duplicate)
314 throw ParseError(
315 {.msg = HintFmt("duplicate formal function argument '%1%'", symbols[duplicate->first]),
316 .pos = positions[duplicate->second]});
317
318 if (arg && formals.has(arg))
319 throw ParseError(
320 {.msg = HintFmt("duplicate formal function argument '%1%'", symbols[arg]), .pos = positions[pos]});
321}
322
323inline Expr *
324ParserState::stripIndentation(const PosIdx pos, std::span<std::pair<PosIdx, std::variant<Expr *, StringToken>>> es)
325{
326 if (es.empty())
327 return exprs.add<ExprString>(""_sds);
328
329 /* Figure out the minimum indentation. Note that by design
330 whitespace-only final lines are not taken into account. (So
331 the " " in "\n ''" is ignored, but the " " in "\n foo''" is.) */
332 bool atStartOfLine = true; /* = seen only whitespace in the current line */
333 size_t minIndent = 1000000;
334 size_t curIndent = 0;
335 for (auto & [i_pos, i] : es) {
336 auto * str = std::get_if<StringToken>(&i);
337 if (!str || !str->hasIndentation) {
338 /* Anti-quotations and escaped characters end the current start-of-line whitespace. */
339 if (atStartOfLine) {
340 atStartOfLine = false;
341 if (curIndent < minIndent)
342 minIndent = curIndent;
343 }
344 continue;
345 }
346 for (size_t j = 0; j < str->l; ++j) {
347 if (atStartOfLine) {
348 if (str->p[j] == ' ')
349 curIndent++;
350 else if (str->p[j] == '\n') {
351 /* Empty line, doesn't influence minimum
352 indentation. */
353 curIndent = 0;
354 } else {
355 atStartOfLine = false;
356 if (curIndent < minIndent)
357 minIndent = curIndent;
358 }
359 } else if (str->p[j] == '\n') {
360 atStartOfLine = true;
361 curIndent = 0;
362 }
363 }
364 }
365
366 /* Strip spaces from each line. */
367 std::vector<std::pair<PosIdx, Expr *>> es2{};
368 atStartOfLine = true;
369 size_t curDropped = 0;
370 size_t n = es.size();
371 auto i = es.begin();
372 const auto trimExpr = [&](Expr * e) {
373 atStartOfLine = false;
374 curDropped = 0;
375 es2.emplace_back(i->first, e);
376 };
377 const auto trimString = [&](const StringToken & t) {
378 std::string s2;
379 for (size_t j = 0; j < t.l; ++j) {
380 if (atStartOfLine) {
381 if (t.p[j] == ' ') {
382 if (curDropped++ >= minIndent)
383 s2 += t.p[j];
384 } else if (t.p[j] == '\n') {
385 curDropped = 0;
386 s2 += t.p[j];
387 } else {
388 atStartOfLine = false;
389 curDropped = 0;
390 s2 += t.p[j];
391 }
392 } else {
393 s2 += t.p[j];
394 if (t.p[j] == '\n')
395 atStartOfLine = true;
396 }
397 }
398
399 /* Remove the last line if it is empty and consists only of
400 spaces. */
401 if (n == 1) {
402 std::string::size_type p = s2.find_last_of('\n');
403 if (p != std::string::npos && s2.find_first_not_of(' ', p + 1) == std::string::npos)
404 s2 = std::string(s2, 0, p + 1);
405 }
406
407 // Ignore empty strings for a minor optimisation and AST simplification
408 if (s2 != "") {
409 es2.emplace_back(i->first, exprs.add<ExprString>(exprs.alloc, s2));
410 }
411 };
412 for (; i != es.end(); ++i, --n) {
413 std::visit(overloaded{trimExpr, trimString}, i->second);
414 }
415
416 // If there is nothing at all, return the empty string directly.
417 // This also ensures that equivalent empty strings result in the same ast, which is helpful when testing formatters.
418 if (es2.size() == 0) {
419 auto * const result = exprs.add<ExprString>(""_sds);
420 return result;
421 }
422
423 /* If this is a single string, then don't do a concatenation. */
424 if (es2.size() == 1 && dynamic_cast<ExprString *>((es2)[0].second)) {
425 auto * const result = (es2)[0].second;
426 return result;
427 }
428 return exprs.add<ExprConcatStrings>(exprs.alloc, pos, true, es2);
429}
430
431inline PosIdx LexerState::at(const ParserLocation & loc)
432{
433 return positions.add(origin, loc.beginOffset);
434}
435
436inline PosIdx ParserState::at(const ParserLocation & loc)
437{
438 return positions.add(origin, loc.beginOffset);
439}
440
441} // namespace nix
Definition nixexpr.hh:836
HintFmt(const std::string &literal)
Definition fmt.hh:178
Definition eval-error.hh:61
Definition pos-idx.hh:10
Definition pos-table.hh:18
Definition pos-table.hh:15
Definition symbol-table.hh:266
Definition symbol-table.hh:24
void visit(const F &f)
Definition parser-state.hh:92
Expr * toExpr(Exprs &exprs)
Definition parser-state.hh:112
Definition ref.hh:58
Definition nixexpr.hh:80
Definition eval-settings.hh:50
Definition nixexpr.hh:370
@ InheritedFrom
Definition nixexpr.hh:377
Definition nixexpr.hh:365
std::optional< AttrDefs > attrs
Definition nixexpr.hh:410
Definition nixexpr.hh:273
Definition nixexpr.hh:286
Definition nixexpr.hh:188
Definition nixexpr.hh:102
Definition nixexpr.hh:100
Definition nixexpr.hh:478
Formals_ formals
Definition nixexpr.hh:483
Definition parser-state.hh:124
int docCommentDistance
Definition parser-state.hh:133
DocCommentMap & positionToDocComment
Maps some positions to a DocComment, where the comment is relevant to the location.
Definition parser-state.hh:145
ParserLocation lastDocCommentLoc
Definition parser-state.hh:140
Definition parser-state.hh:30
Definition parser-state.hh:154
Definition source-path.hh:22
Definition parser-state.hh:18
Definition util.hh:444