• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rieske / trans / 29685161107

19 Jul 2026 11:27AM UTC coverage: 90.789% (+0.3%) from 90.53%
29685161107

push

github

rieske
Experimental parser generator optimization

489 of 497 new or added lines in 16 files covered. (98.39%)

5283 of 5819 relevant lines covered (90.79%)

275386.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.89
/src/parser/CanonicalCollection.cpp
1
#include "CanonicalCollection.h"
2

3
#include "util/LogManager.h"
4
#include "util/Logger.h"
5

6
#include <algorithm>
7
#include <cstdint>
8
#include <deque>
9
#include <unordered_map>
10
#include <utility>
11
#include <vector>
12

13
namespace {
14

15
Logger& logger = LogManager::getComponentLogger(Component::PARSER);
16

17
using namespace parser;
18

19

20
void closeItemSet(
113,346✔
21
        const FirstTable& first,
22
        const Grammar& grammar,
23
        GenerationBuffers& buffers,
24
        std::vector<LR1Item>& items) {
25
    auto& coreIndex = buffers.coreIndex;
113,346✔
26
    auto& worklist = buffers.worklist;
113,346✔
27
    buffers.prepareClosure(items.size());
113,346✔
28

29
    for (std::size_t i = 0; i < items.size(); ++i) {
304,860✔
30
        coreIndex.emplace(items[i].coreKey(), i);
191,514✔
31
        worklist.push_back(i);
191,514✔
32
    }
33
    items.reserve(std::max(items.capacity(), items.size() + 64));
113,346✔
34

35
    std::size_t head = 0;
113,346✔
36
    while (head < worklist.size()) {
3,039,418✔
37
        const std::size_t index = worklist[head++];
2,926,072✔
38
        if (!items[index].hasUnvisitedSymbols() || grammar.isTerminal(items[index].nextUnvisitedSymbol())) {
2,926,072✔
39
            continue;
896,562✔
40
        }
41

42
        const int B = items[index].nextUnvisitedSymbol();
2,029,510✔
43
        const LR1Item::LookaheadSet propagated = items[index].hasSymbolsAfterNext()
2,029,510✔
44
                ? first.firstBits(items[index].symbolAfterNext())
2,029,510✔
45
                : items[index].lookaheads();
568,156✔
46

47
        for (const auto& production : grammar.getProductionsOfSymbol(B)) {
12,826,582✔
48
            const std::uint64_t key =
49
                    (static_cast<std::uint64_t>(static_cast<std::uint32_t>(production.getId())) << 32);
10,797,072✔
50
            const auto existing = coreIndex.find(key);
10,797,072✔
51
            if (existing == coreIndex.end()) {
10,797,072✔
52
                items.emplace_back(production, propagated);
991,300✔
53
                const std::size_t newIndex = items.size() - 1;
991,300✔
54
                coreIndex.emplace(key, newIndex);
991,300✔
55
                worklist.push_back(newIndex);
991,300✔
56
            } else if (items[existing->second].mergeLookaheads(propagated)) {
9,805,772✔
57
                worklist.push_back(existing->second);
1,743,258✔
58
            }
59
        }
60
    }
61
}
113,346✔
62

63
std::unordered_map<int, std::vector<LR1Item>> gotoAllFrom(
12,004✔
64
        const std::vector<LR1Item>& I,
65
        const FirstTable& first,
66
        const Grammar& grammar,
67
        GenerationBuffers& buffers) {
68
    std::unordered_map<int, std::vector<LR1Item>> bySymbol;
12,004✔
69
    bySymbol.reserve(I.size());
12,004✔
70
    for (const auto& item : I) {
210,548✔
71
        if (item.hasUnvisitedSymbols()) {
198,544✔
72
            bySymbol[item.nextUnvisitedSymbol()].push_back(item.advance());
191,488✔
73
        }
74
    }
75
    for (auto& entry : bySymbol) {
125,324✔
76
        entry.second.reserve(entry.second.size() + 16);
113,320✔
77
        closeItemSet(first, grammar, buffers, entry.second);
113,320✔
78
    }
79
    return bySymbol;
12,004✔
NEW
80
}
×
81

82
// --- LALR(1) ---
83

84
std::vector<std::uint64_t> makeCoreSignature(const std::vector<LR1Item>& items, GenerationBuffers& buffers) {
54,632✔
85
    auto& signature = buffers.coreSignature;
54,632✔
86
    signature.clear();
54,632✔
87
    signature.reserve(items.size());
54,632✔
88
    for (const auto& item : items) {
646,946✔
89
        signature.push_back(item.coreKey());
592,314✔
90
    }
91
    std::sort(signature.begin(), signature.end());
54,632✔
92
    return signature;
54,632✔
93
}
94

95
struct CoreSignatureHash {
96
    std::size_t operator()(const std::vector<std::uint64_t>& signature) const noexcept {
74,586✔
97
        std::size_t hash = signature.size();
74,586✔
98
        for (const std::uint64_t key : signature) {
890,124✔
99
            hash ^= std::hash<std::uint64_t>{}(key) + 0x9e3779b97f4a7c15ULL + (hash << 6) + (hash >> 2);
815,538✔
100
        }
101
        return hash;
74,586✔
102
    }
103
};
104

105
bool mergeLookaheadsByCore(
51,370✔
106
        std::vector<LR1Item>& existing,
107
        const std::vector<LR1Item>& incoming,
108
        GenerationBuffers& buffers) {
109
    buffers.prepareMerge(existing.size());
51,370✔
110
    auto& index = buffers.mergeIndexByCore;
51,370✔
111
    for (std::size_t i = 0; i < existing.size(); ++i) {
592,620✔
112
        index.emplace(existing[i].coreKey(), i);
541,250✔
113
    }
114
    bool merged = false;
51,370✔
115
    for (const auto& item : incoming) {
592,620✔
116
        merged |= existing[index.at(item.coreKey())].mergeLookaheads(item.lookaheads());
541,250✔
117
    }
118
    return merged;
51,370✔
119
}
120

121
void computeLALR1(
16✔
122
        std::vector<std::vector<LR1Item>>& canonicalCollection,
123
        GotoMap& computedGotos,
124
        const std::vector<int>& symbolOrder,
125
        const FirstTable& first,
126
        const Grammar& grammar,
127
        GenerationBuffers& buffers) {
128
    std::unordered_map<std::vector<std::uint64_t>, std::size_t, CoreSignatureHash> stateByCores;
16✔
129
    stateByCores.reserve(512);
16✔
130
    stateByCores.emplace(makeCoreSignature(canonicalCollection[0], buffers), 0);
16✔
131
    computedGotos.reserve(symbolOrder.size() * 8);
16✔
132

133
    std::deque<std::size_t> worklist { 0 };
48✔
134
    std::vector<char> inQueue(1, 1);
16✔
135

136
    auto enqueue = [&](std::size_t state) {
6,470✔
137
        if (state >= inQueue.size()) {
6,470✔
138
            inQueue.resize(state + 1, 0);
3,246✔
139
        }
140
        if (!inQueue[state]) {
6,470✔
141
            inQueue[state] = 1;
5,550✔
142
            worklist.push_back(state);
5,550✔
143
        }
144
    };
6,470✔
145

146
    while (!worklist.empty()) {
5,582✔
147
        const std::size_t state = worklist.front();
5,566✔
148
        worklist.pop_front();
5,566✔
149
        inQueue[state] = 0;
5,566✔
150

151
        auto gotos = gotoAllFrom(canonicalCollection[state], first, grammar, buffers);
5,566✔
152
        // Walk symbols in stable grammar order; only process non-empty gotos.
153
        for (const int X : symbolOrder) {
783,300✔
154
            const auto git = gotos.find(X);
777,734✔
155
            if (git == gotos.end() || git->second.empty()) {
777,734✔
156
                continue;
723,118✔
157
            }
158
            auto& gotoSet = git->second;
54,616✔
159
            auto signature = makeCoreSignature(gotoSet, buffers);
54,616✔
160
            const auto existing = stateByCores.find(signature);
54,616✔
161
            if (existing == stateByCores.end()) {
54,616✔
162
                const std::size_t newState = canonicalCollection.size();
3,246✔
163
                canonicalCollection.push_back(std::move(gotoSet));
3,246✔
164
                stateByCores.emplace(std::move(signature), newState);
3,246✔
165
                computedGotos[{ state, X }] = newState;
3,246✔
166
                enqueue(newState);
3,246✔
167
            } else {
168
                const std::size_t target = existing->second;
51,370✔
169
                computedGotos[{ state, X }] = target;
51,370✔
170
                if (mergeLookaheadsByCore(canonicalCollection[target], gotoSet, buffers)) {
51,370✔
171
                    enqueue(target);
3,224✔
172
                }
173
            }
174
        }
54,616✔
175
    }
5,566✔
176
}
16✔
177

178
// --- LR(1) ---
179

180
using ItemSetSignature = std::vector<std::pair<std::uint64_t, LR1Item::LookaheadSet>>;
181

182
ItemSetSignature makeItemSetSignature(const std::vector<LR1Item>& items) {
58,714✔
183
    ItemSetSignature signature;
58,714✔
184
    signature.reserve(items.size());
58,714✔
185
    for (const auto& item : items) {
649,214✔
186
        signature.emplace_back(item.coreKey(), item.lookaheads());
590,500✔
187
    }
188
    // Cores are unique within a closed item set; sort by core only.
189
    std::sort(signature.begin(), signature.end(),
58,714✔
190
            [](const auto& left, const auto& right) {
3,577,638✔
191
                return left.first < right.first;
3,577,638✔
192
            });
193
    return signature;
58,714✔
NEW
194
}
×
195

196
struct ItemSetSignatureHash {
197
    std::size_t operator()(const ItemSetSignature& signature) const noexcept {
104,314✔
198
        std::size_t hash = signature.size();
104,314✔
199
        for (const auto& entry : signature) {
1,282,006✔
200
            hash ^= std::hash<std::uint64_t>{}(entry.first) + 0x9e3779b97f4a7c15ULL + (hash << 6) + (hash >> 2);
1,177,692✔
201
            for (std::size_t i = 0; i < entry.second.size(); i += 64) {
3,533,076✔
202
                unsigned long long word = 0;
2,355,384✔
203
                for (std::size_t b = 0; b < 64 && i + b < entry.second.size(); ++b) {
153,099,960✔
204
                    if (entry.second.test(i + b)) {
150,744,576✔
205
                        word |= 1ULL << b;
23,600,556✔
206
                    }
207
                }
208
                hash ^= std::hash<unsigned long long>{}(word) + 0x9e3779b97f4a7c15ULL + (hash << 6) + (hash >> 2);
2,355,384✔
209
            }
210
        }
211
        return hash;
104,314✔
212
    }
213
};
214

215
void computeLR1(
10✔
216
        std::vector<std::vector<LR1Item>>& canonicalCollection,
217
        GotoMap& computedGotos,
218
        const std::vector<int>& symbolOrder,
219
        const FirstTable& first,
220
        const Grammar& grammar,
221
        GenerationBuffers& buffers) {
222
    std::unordered_map<ItemSetSignature, std::size_t, ItemSetSignatureHash> stateByItems;
10✔
223
    stateByItems.reserve(256);
10✔
224
    stateByItems.emplace(makeItemSetSignature(canonicalCollection[0]), 0);
10✔
225

226
    for (std::size_t i = 0; i < canonicalCollection.size(); ++i) {
6,448✔
227
        auto gotos = gotoAllFrom(canonicalCollection[i], first, grammar, buffers);
6,438✔
228
        for (const int X : symbolOrder) {
839,604✔
229
            const auto git = gotos.find(X);
833,166✔
230
            if (git == gotos.end() || git->second.empty()) {
833,166✔
231
                continue;
774,462✔
232
            }
233
            auto& gotoSet = git->second;
58,704✔
234
            auto signature = makeItemSetSignature(gotoSet);
58,704✔
235
            const auto existing = stateByItems.find(signature);
58,704✔
236
            if (existing == stateByItems.end()) {
58,704✔
237
                const std::size_t newState = canonicalCollection.size();
6,428✔
238
                canonicalCollection.push_back(std::move(gotoSet));
6,428✔
239
                stateByItems.emplace(std::move(signature), newState);
6,428✔
240
                computedGotos[{ i, X }] = newState;
6,428✔
241
            } else {
242
                computedGotos[{ i, X }] = existing->second;
52,276✔
243
            }
244
        }
58,704✔
245
    }
6,438✔
246
}
10✔
247

248
} // namespace
249

250
namespace parser {
251

252
CanonicalCollection::CanonicalCollection(
26✔
253
        const FirstTable& firstTable,
254
        const Grammar& grammar,
255
        AutomatonKind kind) :
26✔
256
        firstTable { firstTable }
26✔
257
{
258
    // Nonterminals then terminals — stable order for state numbering / table identity.
259
    std::vector<int> symbolOrder = grammar.getNonterminalIDs();
26✔
260
    const auto& terminals = grammar.getTerminalIDs();
26✔
261
    symbolOrder.insert(symbolOrder.end(), terminals.begin(), terminals.end());
26✔
262

263
    std::vector<LR1Item> initialSet {
264
        LR1Item { grammar.getTopRule(), std::vector<int>{ grammar.getEndSymbol() }, grammar }
52✔
265
    };
104✔
266
    closeItemSet(firstTable, grammar, buffers, initialSet);
26✔
267
    canonicalCollection.push_back(std::move(initialSet));
26✔
268

269
    if (kind == AutomatonKind::LALR1) {
26✔
270
        computeLALR1(canonicalCollection, computedGotos, symbolOrder, firstTable, grammar, buffers);
16✔
271
    } else {
272
        computeLR1(canonicalCollection, computedGotos, symbolOrder, firstTable, grammar, buffers);
10✔
273
    }
274

275
    logCollection(grammar);
26✔
276
}
26✔
277

278
std::size_t CanonicalCollection::stateCount() const noexcept {
42✔
279
    return canonicalCollection.size();
42✔
280
}
281

282
const std::vector<LR1Item>& CanonicalCollection::setOfItemsAtState(size_t state) const {
3,492✔
283
    return canonicalCollection.at(state);
3,492✔
284
}
285

286
std::size_t CanonicalCollection::goTo(std::size_t stateFrom, int symbol) const {
21,276✔
287
    return computedGotos.at({ stateFrom, symbol });
21,276✔
288
}
289

290
std::optional<std::size_t> CanonicalCollection::findGoTo(std::size_t stateFrom, int symbol) const noexcept {
188,684✔
291
    const auto it = computedGotos.find({ stateFrom, symbol });
188,684✔
292
    return it != computedGotos.end() ? std::optional<std::size_t>{ it->second } : std::nullopt;
188,684✔
293
}
294

295
void CanonicalCollection::logCollection(const Grammar& grammar) const {
26✔
296
    if (logger.isNull()) {
26✔
297
        return;
24✔
298
    }
299
    logger << "\n*********************\nCanonical collection:\n*********************\n";
2✔
300
    int setNo = 0;
2✔
301
    for (const auto& setOfItems : canonicalCollection) {
16✔
302
        logger << "Set " << setNo++ << ":\n";
14✔
303
        for (const auto& item : setOfItems) {
42✔
304
            logger << item.str(grammar);
28✔
305
        }
306
        logger << "\n";
14✔
307
    }
308
    logger << "Computed GOTOs:\n";
2✔
309
    for (const auto& g : computedGotos) {
22✔
310
        logger << g.first.first << "\t" << g.first.second << "\t" << g.second << "\n";
20✔
311
    }
312
}
313

314
} // namespace parser
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc