Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
attr-set.hh
Go to the documentation of this file.
1#pragma once
3
4#include "nix/expr/nixexpr.hh"
6
7#include <boost/container/static_vector.hpp>
8#include <boost/iterator/function_output_iterator.hpp>
9
10#include <algorithm>
11#include <functional>
12#include <ranges>
13#include <optional>
14
15namespace nix {
16
17class EvalMemory;
18struct Value;
19
23struct Attr
24{
25 /* the placement of `name` and `pos` in this struct is important.
26 both of them are uint32 wrappers, they are next to each other
27 to make sure that Attr has no padding on 64 bit machines. that
28 way we keep Attr size at two words with no wasted space. */
29 Symbol name;
30 PosIdx pos;
31 Value * value = nullptr;
32
33 Attr(Symbol name, Value * value, PosIdx pos = noPos)
34 : name(name)
35 , pos(pos)
36 , value(value)
37 {
38 }
39
40 constexpr Attr() {}
41
42 auto operator<=>(const Attr & a) const
43 {
44 return name <=> a.name;
45 }
46};
47
48static_assert(
49 sizeof(Attr) == 2 * sizeof(uint32_t) + sizeof(Value *),
50 "performance of the evaluator is highly sensitive to the size of Attr. "
51 "avoid introducing any padding into Attr if at all possible, and do not "
52 "introduce new fields that need not be present for almost every instance.");
53
66class Bindings
67{
68public:
69 using size_type = uint32_t;
70
71 PosIdx pos;
72
77 static const constinit Bindings emptyBindings;
78
79private:
83 size_type numAttrs = 0;
84
91 size_type numAttrsInChain = 0;
92
96 uint32_t numLayers = 1;
97
101 const Bindings * baseLayer = nullptr;
102
106 Attr attrs[0];
107
108 constexpr Bindings() = default;
109 Bindings(const Bindings &) = delete;
110 Bindings(Bindings &&) = delete;
111 Bindings & operator=(const Bindings &) = delete;
112 Bindings & operator=(Bindings &&) = delete;
113
114 ~Bindings() = default;
115
116 friend class BindingsBuilder;
117
121 static constexpr unsigned maxLayers = 8;
122
123public:
124 size_type size() const
125 {
126 return numAttrsInChain;
127 }
128
129 bool empty() const
130 {
131 return size() == 0;
132 }
133
134 class iterator
135 {
136 public:
137 using value_type = Attr;
138 using pointer = const value_type *;
139 using reference = const value_type &;
140 using difference_type = std::ptrdiff_t;
141 using iterator_category = std::forward_iterator_tag;
142
143 friend class Bindings;
144
145 private:
146 struct BindingsCursor
147 {
151 pointer current;
152
156 pointer end;
157
162 uint32_t priority;
163
164 pointer operator->() const noexcept
165 {
166 return current;
167 }
168
169 reference get() const noexcept
170 {
171 return *current;
172 }
173
174 bool empty() const noexcept
175 {
176 return current == end;
177 }
178
179 void increment() noexcept
180 {
181 ++current;
182 }
183
184 void consume(Symbol name) noexcept
185 {
186 while (!empty() && current->name <= name)
187 ++current;
188 }
189
190 GENERATE_CMP(BindingsCursor, me->current->name, me->priority)
191 };
192
193 using QueueStorageType = boost::container::static_vector<BindingsCursor, maxLayers>;
194
199 static constexpr auto comp = std::greater<BindingsCursor>();
200
204 QueueStorageType cursorHeap;
205
209 pointer current = nullptr;
210
214 bool doMerge = true;
215
216 void push(BindingsCursor cursor) noexcept
217 {
218 cursorHeap.push_back(cursor);
219 std::ranges::make_heap(cursorHeap, comp);
220 }
221
222 [[nodiscard]] BindingsCursor pop() noexcept
223 {
224 std::ranges::pop_heap(cursorHeap, comp);
225 auto cursor = cursorHeap.back();
226 cursorHeap.pop_back();
227 return cursor;
228 }
229
230 iterator & finished() noexcept
231 {
232 current = nullptr;
233 return *this;
234 }
235
236 void next(BindingsCursor cursor) noexcept
237 {
238 current = &cursor.get();
239 cursor.increment();
240
241 if (!cursor.empty())
242 push(cursor);
243 }
244
245 std::optional<BindingsCursor> consumeAllUntilCurrentName() noexcept
246 {
247 auto cursor = pop();
248 Symbol lastHandledName = current->name;
249
250 while (cursor->name <= lastHandledName) {
251 cursor.consume(lastHandledName);
252 if (!cursor.empty())
253 push(cursor);
254
255 if (cursorHeap.empty())
256 return std::nullopt;
257
258 cursor = pop();
259 }
260
261 return cursor;
262 }
263
264 explicit iterator(const Bindings & attrs) noexcept
265 : doMerge(attrs.baseLayer)
266 {
267 auto pushBindings = [this, priority = unsigned{0}](const Bindings & layer) mutable {
268 auto first = layer.attrs;
269 push(
270 BindingsCursor{
271 .current = first,
272 .end = first + layer.numAttrs,
273 .priority = priority++,
274 });
275 };
276
277 if (!doMerge) {
278 if (attrs.empty())
279 return;
280
281 current = attrs.attrs;
282 pushBindings(attrs);
283
284 return;
285 }
286
287 const Bindings * layer = &attrs;
288 while (layer) {
289 if (layer->numAttrs != 0)
290 pushBindings(*layer);
291 layer = layer->baseLayer;
292 }
293
294 if (cursorHeap.empty())
295 return;
296
297 next(pop());
298 }
299
300 public:
301 iterator() = default;
302
303 reference operator*() const noexcept
304 {
305 return *current;
306 }
307
308 pointer operator->() const noexcept
309 {
310 return current;
311 }
312
313 iterator & operator++() noexcept
314 {
315 if (!doMerge) {
316 ++current;
317 if (current == cursorHeap.front().end)
318 return finished();
319 return *this;
320 }
321
322 if (cursorHeap.empty())
323 return finished();
324
325 auto cursor = consumeAllUntilCurrentName();
326 if (!cursor)
327 return finished();
328
329 next(*cursor);
330 return *this;
331 }
332
333 iterator operator++(int) noexcept
334 {
335 iterator tmp = *this;
336 ++*this;
337 return tmp;
338 }
339
340 bool operator==(const iterator & rhs) const noexcept
341 {
342 return current == rhs.current;
343 }
344 };
345
346 using const_iterator = iterator;
347
348 void push_back(const Attr & attr)
349 {
350 attrs[numAttrs++] = attr;
351 numAttrsInChain = numAttrs;
352 }
353
357 const Attr * get(Symbol name) const noexcept
358 {
359 auto getInChunk = [key = Attr{name, nullptr}](const Bindings & chunk) -> const Attr * {
360 auto first = chunk.attrs;
361 auto last = first + chunk.numAttrs;
362 const Attr * i = std::lower_bound(first, last, key);
363 if (i != last && i->name == key.name)
364 return i;
365 return nullptr;
366 };
367
368 const Bindings * currentChunk = this;
369 while (currentChunk) {
370 const Attr * maybeAttr = getInChunk(*currentChunk);
371 if (maybeAttr)
372 return maybeAttr;
373 currentChunk = currentChunk->baseLayer;
374 }
375
376 return nullptr;
377 }
378
382 bool isLayerListFull() const noexcept
383 {
384 return numLayers == Bindings::maxLayers;
385 }
386
390 bool isLayered() const noexcept
391 {
392 return numLayers > 1;
393 }
394
395 const_iterator begin() const
396 {
397 return const_iterator(*this);
398 }
399
400 const_iterator end() const
401 {
402 return const_iterator();
403 }
404
405 Attr & operator[](size_type pos)
406 {
407 if (isLayered()) [[unlikely]]
408 unreachable();
409 return attrs[pos];
410 }
411
412 const Attr & operator[](size_type pos) const
413 {
414 if (isLayered()) [[unlikely]]
415 unreachable();
416 return attrs[pos];
417 }
418
419 void sort();
420
424 std::vector<const Attr *> lexicographicOrder(const SymbolTable & symbols) const
425 {
426 std::vector<const Attr *> res;
427 res.reserve(size());
428 std::ranges::transform(*this, std::back_inserter(res), [](const Attr & a) { return &a; });
429 std::ranges::sort(res, [&](const Attr * a, const Attr * b) {
430 std::string_view sa = symbols[a->name], sb = symbols[b->name];
431 return sa < sb;
432 });
433 return res;
434 }
435
436 friend class EvalMemory;
437};
438
439static_assert(std::forward_iterator<Bindings::iterator>);
440static_assert(std::ranges::forward_range<Bindings>);
441
447class BindingsBuilder final
448{
449public:
450 // needed by std::back_inserter
451 using value_type = Attr;
452 using size_type = Bindings::size_type;
453
454private:
455 Bindings * bindings;
456 Bindings::size_type capacity_;
457
458 friend class EvalMemory;
459
460 BindingsBuilder(EvalMemory & mem, SymbolTable & symbols, Bindings * bindings, size_type capacity)
461 : bindings(bindings)
462 , capacity_(capacity)
463 , mem(mem)
464 , symbols(symbols)
465 {
466 }
467
468 bool hasBaseLayer() const noexcept
469 {
470 return bindings->baseLayer;
471 }
472
482 void finishSizeIfNecessary()
483 {
484 if (!hasBaseLayer())
485 return;
486
487 auto & base = *bindings->baseLayer;
488 auto attrs = std::span(bindings->attrs, bindings->numAttrs);
489
490 Bindings::size_type duplicates = 0;
491
492 /* If the base bindings is smaller than the newly added attributes
493 iterate using std::set_intersection to run in O(|base| + |attrs|) =
494 O(|attrs|). Otherwise use an O(|attrs| * log(|base|)) per-attr binary
495 search to check for duplicates. Note that if we are in this code path then
496 |attrs| <= bindingsUpdateLayerRhsSizeThreshold, which 16 by default. We are
497 optimizing for the case when a small attribute set gets "layered" on top of
498 a much larger one. When attrsets are already small it's fine to do a linear
499 scan, but we should avoid expensive iterations over large "base" attrsets. */
500 if (attrs.size() > base.size()) {
501 std::set_intersection(
502 base.begin(),
503 base.end(),
504 attrs.begin(),
505 attrs.end(),
506 boost::make_function_output_iterator([&]([[maybe_unused]] auto && _) { ++duplicates; }));
507 } else {
508 for (const auto & attr : attrs) {
509 if (base.get(attr.name))
510 ++duplicates;
511 }
512 }
513
514 bindings->numAttrsInChain = base.numAttrsInChain + attrs.size() - duplicates;
515 }
516
517public:
518 std::reference_wrapper<EvalMemory> mem;
519 std::reference_wrapper<SymbolTable> symbols;
520
521 void insert(Symbol name, Value * value, PosIdx pos = noPos)
522 {
523 insert(Attr(name, value, pos));
524 }
525
526 void insert(const Attr & attr)
527 {
528 push_back(attr);
529 }
530
531 void push_back(const Attr & attr)
532 {
533 assert(bindings->numAttrs < capacity_);
534 bindings->push_back(attr);
535 }
536
547 void layerOnTopOf(const Bindings & base) noexcept
548 {
549 bindings->baseLayer = &base;
550 bindings->numLayers = base.numLayers + 1;
551 }
552
553 Value & alloc(Symbol name, PosIdx pos = noPos);
554
555 Value & alloc(std::string_view name, PosIdx pos = noPos);
556
557 const Bindings * finish()
558 {
559 bindings->sort();
560 finishSizeIfNecessary();
561 return bindings;
562 }
563
564 const Bindings * alreadySorted()
565 {
566 finishSizeIfNecessary();
567 return bindings;
568 }
569
570 size_t capacity() const noexcept
571 {
572 return capacity_;
573 }
574
575 void grow(BindingsBuilder newBindings)
576 {
577 for (auto & i : *bindings)
578 newBindings.push_back(i);
579 std::swap(*this, newBindings);
580 }
581
582 friend struct ExprAttrs;
583};
584
585} // namespace nix
void layerOnTopOf(const Bindings &base) noexcept
Definition attr-set.hh:547
Definition attr-set.hh:135
Definition attr-set.hh:67
static const constinit Bindings emptyBindings
Definition attr-set.hh:77
bool isLayerListFull() const noexcept
Definition attr-set.hh:382
std::vector< const Attr * > lexicographicOrder(const SymbolTable &symbols) const
Definition attr-set.hh:424
const Attr * get(Symbol name) const noexcept
Definition attr-set.hh:357
bool isLayered() const noexcept
Definition attr-set.hh:390
Definition eval.hh:347
Definition pos-idx.hh:10
Definition symbol-table.hh:266
Definition symbol-table.hh:24
#define GENERATE_CMP(args...)
Definition comparator.hh:39
Definition attr-set.hh:24
Definition value.hh:1166