1 //===--- GLR.cpp   -----------------------------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang-pseudo/GLR.h"
10 #include "clang-pseudo/Language.h"
11 #include "clang-pseudo/grammar/Grammar.h"
12 #include "clang-pseudo/grammar/LRTable.h"
13 #include "clang/Basic/TokenKinds.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FormatVariadic.h"
20 #include <algorithm>
21 #include <memory>
22 #include <queue>
23 
24 #define DEBUG_TYPE "GLR.cpp"
25 
26 namespace clang {
27 namespace pseudo {
28 namespace {
29 
30 Token::Index findRecoveryEndpoint(ExtensionID Strategy, Token::Index Begin,
31                                   const TokenStream &Tokens,
32                                   const Language &Lang) {
33   assert(Strategy != 0);
34   assert(Begin > 0);
35   if (auto S = Lang.RecoveryStrategies.lookup(Strategy))
36     return S(Begin, Tokens);
37   return Token::Invalid;
38 }
39 
40 } // namespace
41 
42 void glrRecover(llvm::ArrayRef<const GSS::Node *> OldHeads,
43                 unsigned &TokenIndex, const ParseParams &Params,
44                 const Language &Lang,
45                 std::vector<const GSS::Node *> &NewHeads) {
46   LLVM_DEBUG(llvm::dbgs() << "Recovery at token " << TokenIndex << "...\n");
47   // Describes a possibility to recover by forcibly interpreting a range of
48   // tokens around the cursor as a nonterminal that we expected to see.
49   struct PlaceholderRecovery {
50     // The token prior to the nonterminal which is being recovered.
51     // This starts of the region we're skipping, so higher Position is better.
52     Token::Index Position;
53     // The nonterminal which will be created in order to recover.
54     SymbolID Symbol;
55     // The heuristic used to choose the bounds of the nonterminal to recover.
56     ExtensionID Strategy;
57 
58     // The GSS head where we are expecting the recovered nonterminal.
59     const GSS::Node *RecoveryNode;
60     // Payload of nodes on the way back from the OldHead to the recovery node.
61     // These represent the partial parse that is being discarded.
62     // They should become the children of the opaque recovery node.
63     // FIXME: internal structure of opaque nodes is not implemented.
64     //
65     // There may be multiple paths leading to the same recovery node, we choose
66     // one arbitrarily.
67     std::vector<const ForestNode *> DiscardedParse;
68   };
69   std::vector<PlaceholderRecovery> Options;
70 
71   // Find recovery options by walking up the stack.
72   //
73   // This is similar to exception handling: we walk up the "frames" of nested
74   // rules being parsed until we find one that has a "handler" which allows us
75   // to determine the node bounds without parsing it.
76   //
77   // Unfortunately there's a significant difference: the stack contains both
78   // "upward" nodes (ancestor parses) and "leftward" ones.
79   // e.g. when parsing `{ if (1) ? }` as compound-stmt, the stack contains:
80   //   stmt := IF ( expr ) . stmt      - current state, we should recover here!
81   //   stmt := IF ( expr . ) stmt      - (left, no recovery here)
82   //   stmt := IF ( . expr ) stmt      - left, we should NOT recover here!
83   //   stmt := IF . ( expr ) stmt      - (left, no recovery here)
84   //   stmt-seq := . stmt              - up, we might recover here
85   //   compound-stmt := { . stmt-seq } - up, we should recover here!
86   //
87   // It's not obvious how to avoid collecting "leftward" recovery options.
88   // I think the distinction is ill-defined after merging items into states.
89   // For now, we have to take this into account when defining recovery rules.
90   // (e.g. in the expr recovery above, stay inside the parentheses).
91   // FIXME: find a more satisfying way to avoid such false recovery.
92   // FIXME: Add a test for spurious recovery once tests can define strategies.
93   std::vector<const ForestNode *> Path;
94   llvm::DenseSet<const GSS::Node *> Seen;
95   auto WalkUp = [&](const GSS::Node *N, Token::Index NextTok, auto &WalkUp) {
96     if (!Seen.insert(N).second)
97       return;
98     for (auto Strategy : Lang.Table.getRecovery(N->State)) {
99       Options.push_back(PlaceholderRecovery{
100           NextTok,
101           Strategy.Result,
102           Strategy.Strategy,
103           N,
104           Path,
105       });
106       LLVM_DEBUG(llvm::dbgs()
107                  << "Option: recover " << Lang.G.symbolName(Strategy.Result)
108                  << " at token " << NextTok << "\n");
109     }
110     Path.push_back(N->Payload);
111     for (const GSS::Node *Parent : N->parents())
112       WalkUp(Parent, N->Payload->startTokenIndex(), WalkUp);
113     Path.pop_back();
114   };
115   for (auto *N : OldHeads)
116     WalkUp(N, TokenIndex, WalkUp);
117 
118   // Now we select the option(s) we will use to recover.
119   //
120   // We prefer options starting further right, as these discard less code
121   // (e.g. we prefer to recover inner scopes rather than outer ones).
122   // The options also need to agree on an endpoint, so the parser has a
123   // consistent position afterwards.
124   //
125   // So conceptually we're sorting by the tuple (start, end), though we avoid
126   // computing `end` for options that can't be winners.
127 
128   // Consider options starting further right first.
129   // Don't drop the others yet though, we may still use them if preferred fails.
130   llvm::stable_sort(Options, [&](const auto &L, const auto &R) {
131     return L.Position > R.Position;
132   });
133 
134   // We may find multiple winners, but they will have the same range.
135   llvm::Optional<Token::Range> RecoveryRange;
136   std::vector<const PlaceholderRecovery *> BestOptions;
137   for (const PlaceholderRecovery &Option : Options) {
138     // If this starts further left than options we've already found, then
139     // we'll never find anything better. Skip computing End for the rest.
140     if (RecoveryRange && Option.Position < RecoveryRange->Begin)
141       break;
142 
143     auto End = findRecoveryEndpoint(Option.Strategy, Option.Position,
144                                     Params.Code, Lang);
145     // Recovery may not take the parse backwards.
146     if (End == Token::Invalid || End < TokenIndex)
147       continue;
148     if (RecoveryRange) {
149       // If this is worse than our previous options, ignore it.
150       if (RecoveryRange->End < End)
151         continue;
152       // If this is an improvement over our previous options, then drop them.
153       if (RecoveryRange->End > End)
154         BestOptions.clear();
155     }
156     // Create recovery nodes and heads for them in the GSS. These may be
157     // discarded if a better recovery is later found, but this path isn't hot.
158     RecoveryRange = {Option.Position, End};
159     BestOptions.push_back(&Option);
160   }
161 
162   if (BestOptions.empty()) {
163     LLVM_DEBUG(llvm::dbgs() << "Recovery failed after trying " << Options.size()
164                             << " strategies\n");
165     return;
166   }
167 
168   // We've settled on a set of recovery options, so create their nodes and
169   // advance the cursor.
170   LLVM_DEBUG({
171     llvm::dbgs() << "Recovered range=" << *RecoveryRange << ":";
172     for (const auto *Option : BestOptions)
173       llvm::dbgs() << " " << Lang.G.symbolName(Option->Symbol);
174     llvm::dbgs() << "\n";
175   });
176   // FIXME: in general, we might have the same Option->Symbol multiple times,
177   // and we risk creating redundant Forest and GSS nodes.
178   // We also may inadvertently set up the next glrReduce to create a sequence
179   // node duplicating an opaque node that we're creating here.
180   // There are various options, including simply breaking ties between options.
181   // For now it's obscure enough to ignore.
182   for (const PlaceholderRecovery *Option : BestOptions) {
183     const ForestNode &Placeholder =
184         Params.Forest.createOpaque(Option->Symbol, RecoveryRange->Begin);
185     const GSS::Node *NewHead = Params.GSStack.addNode(
186         *Lang.Table.getGoToState(Option->RecoveryNode->State, Option->Symbol),
187         &Placeholder, {Option->RecoveryNode});
188     NewHeads.push_back(NewHead);
189   }
190   TokenIndex = RecoveryRange->End;
191 }
192 
193 using StateID = LRTable::StateID;
194 
195 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const GSS::Node &N) {
196   std::vector<std::string> ParentStates;
197   for (const auto *Parent : N.parents())
198     ParentStates.push_back(llvm::formatv("{0}", Parent->State));
199   OS << llvm::formatv("state {0}, parsed symbol {1}, parents {3}", N.State,
200                       N.Payload ? N.Payload->symbol() : 0,
201                       llvm::join(ParentStates, ", "));
202   return OS;
203 }
204 
205 // Apply all pending shift actions.
206 // In theory, LR parsing doesn't have shift/shift conflicts on a single head.
207 // But we may have multiple active heads, and each head has a shift action.
208 //
209 // We merge the stack -- if multiple heads will reach the same state after
210 // shifting a token, we shift only once by combining these heads.
211 //
212 // E.g. we have two heads (2, 3) in the GSS, and will shift both to reach 4:
213 //   0---1---2
214 //       └---3
215 // After the shift action, the GSS is:
216 //   0---1---2---4
217 //       └---3---┘
218 void glrShift(llvm::ArrayRef<const GSS::Node *> OldHeads,
219               const ForestNode &NewTok, const ParseParams &Params,
220               const Language &Lang, std::vector<const GSS::Node *> &NewHeads) {
221   assert(NewTok.kind() == ForestNode::Terminal);
222   LLVM_DEBUG(llvm::dbgs() << llvm::formatv("  Shift {0} ({1} active heads):\n",
223                                            Lang.G.symbolName(NewTok.symbol()),
224                                            OldHeads.size()));
225 
226   // We group pending shifts by their target state so we can merge them.
227   llvm::SmallVector<std::pair<StateID, const GSS::Node *>, 8> Shifts;
228   for (const auto *H : OldHeads)
229     if (auto S = Lang.Table.getShiftState(H->State, NewTok.symbol()))
230       Shifts.push_back({*S, H});
231   llvm::stable_sort(Shifts, llvm::less_first{});
232 
233   auto Rest = llvm::makeArrayRef(Shifts);
234   llvm::SmallVector<const GSS::Node *> Parents;
235   while (!Rest.empty()) {
236     // Collect the batch of PendingShift that have compatible shift states.
237     // Their heads become TempParents, the parents of the new GSS node.
238     StateID NextState = Rest.front().first;
239 
240     Parents.clear();
241     for (const auto &Base : Rest) {
242       if (Base.first != NextState)
243         break;
244       Parents.push_back(Base.second);
245     }
246     Rest = Rest.drop_front(Parents.size());
247 
248     LLVM_DEBUG(llvm::dbgs() << llvm::formatv("    --> S{0} ({1} heads)\n",
249                                              NextState, Parents.size()));
250     NewHeads.push_back(Params.GSStack.addNode(NextState, &NewTok, Parents));
251   }
252 }
253 
254 namespace {
255 // A KeyedQueue yields pairs of keys and values in order of the keys.
256 template <typename Key, typename Value>
257 using KeyedQueue =
258     std::priority_queue<std::pair<Key, Value>,
259                         std::vector<std::pair<Key, Value>>, llvm::less_first>;
260 
261 template <typename T> void sortAndUnique(std::vector<T> &Vec) {
262   llvm::sort(Vec);
263   Vec.erase(std::unique(Vec.begin(), Vec.end()), Vec.end());
264 }
265 
266 // Perform reduces until no more are possible.
267 //
268 // Generally this means walking up from the heads gathering ForestNodes that
269 // will match the RHS of the rule we're reducing into a sequence ForestNode,
270 // and ending up at a base node.
271 // Then we push a new GSS node onto that base, taking care to:
272 //  - pack alternative sequence ForestNodes into an ambiguous ForestNode.
273 //  - use the same GSS node for multiple heads if the parse state matches.
274 //
275 // Examples of reduction:
276 //   Before (simple):
277 //     0--1(expr)--2(semi)
278 //   After reducing 2 by `stmt := expr semi`:
279 //     0--3(stmt)                // 3 is goto(0, stmt)
280 //
281 //   Before (splitting due to R/R conflict):
282 //     0--1(IDENTIFIER)
283 //   After reducing 1 by `class-name := IDENTIFIER` & `enum-name := IDENTIFIER`:
284 //     0--2(class-name)          // 2 is goto(0, class-name)
285 //     └--3(enum-name)           // 3 is goto(0, enum-name)
286 //
287 //   Before (splitting due to multiple bases):
288 //     0--2(class-name)--4(STAR)
289 //     └--3(enum-name)---┘
290 //   After reducing 4 by `ptr-operator := STAR`:
291 //     0--2(class-name)--5(ptr-operator)    // 5 is goto(2, ptr-operator)
292 //     └--3(enum-name)---6(ptr-operator)    // 6 is goto(3, ptr-operator)
293 //
294 //   Before (joining due to same goto state, multiple bases):
295 //     0--1(cv-qualifier)--3(class-name)
296 //     └--2(cv-qualifier)--4(enum-name)
297 //   After reducing 3 by `type-name := class-name` and
298 //                  4 by `type-name := enum-name`:
299 //     0--1(cv-qualifier)--5(type-name)  // 5 is goto(1, type-name) and
300 //     └--2(cv-qualifier)--┘             //      goto(2, type-name)
301 //
302 //   Before (joining due to same goto state, the same base):
303 //     0--1(class-name)--3(STAR)
304 //     └--2(enum-name)--4(STAR)
305 //   After reducing 3 by `pointer := class-name STAR` and
306 //                  2 by`enum-name := class-name STAR`:
307 //     0--5(pointer)       // 5 is goto(0, pointer)
308 //
309 // (This is a functor rather than a function to allow it to reuse scratch
310 // storage across calls).
311 class GLRReduce {
312   const ParseParams &Params;
313   const Language& Lang;
314   // There are two interacting complications:
315   // 1.  Performing one reduce can unlock new reduces on the newly-created head.
316   // 2a. The ambiguous ForestNodes must be complete (have all sequence nodes).
317   //     This means we must have unlocked all the reduces that contribute to it.
318   // 2b. Similarly, the new GSS nodes must be complete (have all parents).
319   //
320   // We define a "family" of reduces as those that produce the same symbol and
321   // cover the same range of tokens. These are exactly the set of reductions
322   // whose sequence nodes would be covered by the same ambiguous node.
323   // We wish to process a whole family at a time (to satisfy complication 2),
324   // and can address complication 1 by carefully ordering the families:
325   // - Process families covering fewer tokens first.
326   //   A reduce can't depend on a longer reduce!
327   // - For equal token ranges: if S := T, process T families before S families.
328   //   Parsing T can't depend on an equal-length S, as the grammar is acyclic.
329   //
330   // This isn't quite enough: we don't know the token length of the reduction
331   // until we walk up the stack to perform the pop.
332   // So we perform the pop part upfront, and place the push specification on
333   // priority queues such that we can retrieve a family at a time.
334 
335   // A reduction family is characterized by its token range and symbol produced.
336   // It is used as a key in the priority queues to group pushes by family.
337   struct Family {
338     // The start of the token range of the reduce.
339     Token::Index Start;
340     SymbolID Symbol;
341     // Rule must produce Symbol and can otherwise be arbitrary.
342     // RuleIDs have the topological order based on the acyclic grammar.
343     // FIXME: should SymbolIDs be so ordered instead?
344     RuleID Rule;
345 
346     bool operator==(const Family &Other) const {
347       return Start == Other.Start && Symbol == Other.Symbol;
348     }
349     // The larger Family is the one that should be processed first.
350     bool operator<(const Family &Other) const {
351       if (Start != Other.Start)
352         return Start < Other.Start;
353       if (Symbol != Other.Symbol)
354         return Rule > Other.Rule;
355       assert(*this == Other);
356       return false;
357     }
358   };
359 
360   // A sequence is the ForestNode payloads of the GSS nodes we are reducing.
361   using Sequence = llvm::SmallVector<const ForestNode *, Rule::MaxElements>;
362   // Like ArrayRef<const ForestNode*>, but with the missing operator<.
363   // (Sequences are big to move by value as the collections gets rearranged).
364   struct SequenceRef {
365     SequenceRef(const Sequence &S) : S(S) {}
366     llvm::ArrayRef<const ForestNode *> S;
367     friend bool operator==(SequenceRef A, SequenceRef B) { return A.S == B.S; }
368     friend bool operator<(const SequenceRef &A, const SequenceRef &B) {
369       return std::lexicographical_compare(A.S.begin(), A.S.end(), B.S.begin(),
370                                           B.S.end());
371     }
372   };
373   // Underlying storage for sequences pointed to by stored SequenceRefs.
374   std::deque<Sequence> SequenceStorage;
375   // We don't actually destroy the sequences between calls, to reuse storage.
376   // Everything SequenceStorage[ >=SequenceStorageCount ] is reusable scratch.
377   unsigned SequenceStorageCount;
378 
379   // Halfway through a reduction (after the pop, before the push), we have
380   // collected nodes for the RHS of a rule, and reached a base node.
381   // They specify a sequence ForestNode we may build (but we dedup first).
382   // (The RuleID is not stored here, but rather in the Family).
383   struct PushSpec {
384     // The last node popped before pushing. Its parent is the reduction base(s).
385     // (Base is more fundamental, but this is cheaper to store).
386     const GSS::Node* LastPop = nullptr;
387     Sequence *Seq = nullptr;
388   };
389   KeyedQueue<Family, PushSpec> Sequences; // FIXME: rename => PendingPushes?
390 
391   // We treat Heads as a queue of Pop operations still to be performed.
392   // PoppedHeads is our position within it.
393   std::vector<const GSS::Node *> *Heads;
394   unsigned NextPopHead;
395   SymbolID Lookahead;
396 
397   Sequence TempSequence;
398 public:
399   GLRReduce(const ParseParams &Params, const Language &Lang)
400       : Params(Params), Lang(Lang) {}
401 
402   void operator()(std::vector<const GSS::Node *> &Heads, SymbolID Lookahead) {
403     assert(isToken(Lookahead));
404 
405     NextPopHead = 0;
406     this->Heads = &Heads;
407     this->Lookahead = Lookahead;
408     assert(Sequences.empty());
409     SequenceStorageCount = 0;
410 
411     popPending();
412     while (!Sequences.empty()) {
413       pushNext();
414       popPending();
415     }
416   }
417 
418 private:
419   bool canReduce(ExtensionID GuardID, RuleID RID,
420                  llvm::ArrayRef<const ForestNode *> RHS) const {
421     if (!GuardID)
422       return true;
423     if (auto Guard = Lang.Guards.lookup(GuardID))
424       return Guard(RHS, Params.Code);
425     LLVM_DEBUG(llvm::dbgs()
426                << llvm::formatv("missing guard implementation for rule {0}\n",
427                                 Lang.G.dumpRule(RID)));
428     return true;
429   }
430   // pop walks up the parent chain(s) for a reduction from Head by to Rule.
431   // Once we reach the end, record the bases and sequences.
432   void pop(const GSS::Node *Head, RuleID RID, const Rule &Rule) {
433     LLVM_DEBUG(llvm::dbgs() << "  Pop " << Lang.G.dumpRule(RID) << "\n");
434     Family F{/*Start=*/0, /*Symbol=*/Rule.Target, /*Rule=*/RID};
435     TempSequence.resize_for_overwrite(Rule.Size);
436     auto DFS = [&](const GSS::Node *N, unsigned I, auto &DFS) {
437       TempSequence[Rule.Size - 1 - I] = N->Payload;
438       if (I + 1 == Rule.Size) {
439         F.Start = TempSequence.front()->startTokenIndex();
440         LLVM_DEBUG({
441           for (const auto *B : N->parents())
442             llvm::dbgs() << "    --> base at S" << B->State << "\n";
443         });
444         if (!canReduce(Rule.Guard, RID, TempSequence))
445           return;
446         // Copy the chain to stable storage so it can be enqueued.
447         if (SequenceStorageCount == SequenceStorage.size())
448           SequenceStorage.emplace_back();
449         SequenceStorage[SequenceStorageCount] = TempSequence;
450         Sequence *Seq = &SequenceStorage[SequenceStorageCount++];
451 
452         Sequences.emplace(F, PushSpec{N, Seq});
453         return;
454       }
455       for (const GSS::Node *Parent : N->parents())
456         DFS(Parent, I + 1, DFS);
457     };
458     DFS(Head, 0, DFS);
459   }
460 
461   // popPending pops every available reduction.
462   void popPending() {
463     for (; NextPopHead < Heads->size(); ++NextPopHead) {
464       // In trivial cases, we perform the complete reduce here!
465       if (popAndPushTrivial())
466         continue;
467       for (RuleID RID :
468            Lang.Table.getReduceRules((*Heads)[NextPopHead]->State)) {
469         const auto &Rule = Lang.G.lookupRule(RID);
470         if (Lang.Table.canFollow(Rule.Target, Lookahead))
471           pop((*Heads)[NextPopHead], RID, Rule);
472       }
473     }
474   }
475 
476   // Storage reused by each call to pushNext.
477   std::vector<std::pair</*Goto*/ StateID, const GSS::Node *>> FamilyBases;
478   std::vector<std::pair<RuleID, SequenceRef>> FamilySequences;
479   std::vector<const GSS::Node *> Parents;
480   std::vector<const ForestNode *> SequenceNodes;
481 
482   // Process one push family, forming a forest node.
483   // This produces new GSS heads which may enable more pops.
484   void pushNext() {
485     assert(!Sequences.empty());
486     Family F = Sequences.top().first;
487 
488     LLVM_DEBUG(llvm::dbgs() << "  Push " << Lang.G.symbolName(F.Symbol)
489                             << " from token " << F.Start << "\n");
490 
491     // Grab the sequences and bases for this family.
492     // We don't care which rule yielded each base. If Family.Symbol is S, the
493     // base includes an item X := ... • S ... and since the grammar is
494     // context-free, *all* parses of S are valid here.
495     FamilySequences.clear();
496     FamilyBases.clear();
497     do {
498       const PushSpec &Push = Sequences.top().second;
499       FamilySequences.emplace_back(Sequences.top().first.Rule, *Push.Seq);
500       for (const GSS::Node *Base : Push.LastPop->parents()) {
501         auto NextState = Lang.Table.getGoToState(Base->State, F.Symbol);
502         assert(NextState.has_value() && "goto must succeed after reduce!");
503         FamilyBases.emplace_back(*NextState, Base);
504       }
505 
506       Sequences.pop();
507     } while (!Sequences.empty() && Sequences.top().first == F);
508     // Build a forest node for each unique sequence.
509     sortAndUnique(FamilySequences);
510     SequenceNodes.clear();
511     for (const auto &SequenceSpec : FamilySequences)
512       SequenceNodes.push_back(&Params.Forest.createSequence(
513           F.Symbol, SequenceSpec.first, SequenceSpec.second.S));
514     // Wrap in an ambiguous node if needed.
515     const ForestNode *Parsed =
516         SequenceNodes.size() == 1
517             ? SequenceNodes.front()
518             : &Params.Forest.createAmbiguous(F.Symbol, SequenceNodes);
519     LLVM_DEBUG(llvm::dbgs() << "    --> " << Parsed->dump(Lang.G) << "\n");
520 
521     // Bases for this family, deduplicate them, and group by the goTo State.
522     sortAndUnique(FamilyBases);
523     // Create a GSS node for each unique goto state.
524     llvm::ArrayRef<decltype(FamilyBases)::value_type> BasesLeft = FamilyBases;
525     while (!BasesLeft.empty()) {
526       StateID NextState = BasesLeft.front().first;
527       Parents.clear();
528       for (const auto &Base : BasesLeft) {
529         if (Base.first != NextState)
530           break;
531         Parents.push_back(Base.second);
532       }
533       BasesLeft = BasesLeft.drop_front(Parents.size());
534       Heads->push_back(Params.GSStack.addNode(NextState, Parsed, Parents));
535     }
536   }
537 
538   // In general we split a reduce into a pop/push, so concurrently-available
539   // reductions can run in the correct order. The data structures are expensive.
540   //
541   // When only one reduction is possible at a time, we can skip this:
542   // we pop and immediately push, as an LR parser (as opposed to GLR) would.
543   // This is valid whenever there's only one concurrent PushSpec.
544   //
545   // This function handles a trivial but common subset of these cases:
546   //  - there must be no pending pushes, and only one poppable head
547   //  - the head must have only one reduction rule
548   //  - the reduction path must be a straight line (no multiple parents)
549   // (Roughly this means there's no local ambiguity, so the LR algorithm works).
550   //
551   // Returns true if we successfully consumed the next unpopped head.
552   bool popAndPushTrivial() {
553     if (!Sequences.empty() || Heads->size() != NextPopHead + 1)
554       return false;
555     const GSS::Node *Head = Heads->back();
556     llvm::Optional<RuleID> RID;
557     for (RuleID R : Lang.Table.getReduceRules(Head->State)) {
558       if (RID.has_value())
559         return false;
560       RID = R;
561     }
562     if (!RID)
563       return true; // no reductions available, but we've processed the head!
564     const auto &Rule = Lang.G.lookupRule(*RID);
565     if (!Lang.Table.canFollow(Rule.Target, Lookahead))
566       return true; // reduction is not available
567     const GSS::Node *Base = Head;
568     TempSequence.resize_for_overwrite(Rule.Size);
569     for (unsigned I = 0; I < Rule.Size; ++I) {
570       if (Base->parents().size() != 1)
571         return false;
572       TempSequence[Rule.Size - 1 - I] = Base->Payload;
573       Base = Base->parents().front();
574     }
575     if (!canReduce(Rule.Guard, *RID, TempSequence))
576       return true; // reduction is not available
577     const ForestNode *Parsed =
578         &Params.Forest.createSequence(Rule.Target, *RID, TempSequence);
579     auto NextState = Lang.Table.getGoToState(Base->State, Rule.Target);
580     assert(NextState.has_value() && "goto must succeed after reduce!");
581     Heads->push_back(Params.GSStack.addNode(*NextState, Parsed, {Base}));
582     return true;
583   }
584 };
585 
586 } // namespace
587 
588 const ForestNode &glrParse(const ParseParams &Params, SymbolID StartSymbol,
589                            const Language &Lang) {
590   GLRReduce Reduce(Params, Lang);
591   assert(isNonterminal(StartSymbol) && "Start symbol must be a nonterminal");
592   llvm::ArrayRef<ForestNode> Terminals = Params.Forest.createTerminals(Params.Code);
593   auto &GSS = Params.GSStack;
594 
595   StateID StartState = Lang.Table.getStartState(StartSymbol);
596   // Heads correspond to the parse of tokens [0, I), NextHeads to [0, I+1).
597   std::vector<const GSS::Node *> Heads = {GSS.addNode(/*State=*/StartState,
598                                                       /*ForestNode=*/nullptr,
599                                                       {})};
600   std::vector<const GSS::Node *> NextHeads;
601   auto MaybeGC = [&, Roots(std::vector<const GSS::Node *>{}), I(0u)]() mutable {
602     assert(NextHeads.empty() && "Running GC at the wrong time!");
603     if (++I != 20) // Run periodically to balance CPU and memory usage.
604       return;
605     I = 0;
606 
607     // We need to copy the list: Roots is consumed by the GC.
608     Roots = Heads;
609     GSS.gc(std::move(Roots));
610   };
611   // Each iteration fully processes a single token.
612   for (unsigned I = 0; I < Terminals.size();) {
613     LLVM_DEBUG(llvm::dbgs() << llvm::formatv(
614                    "Next token {0} (id={1})\n",
615                   Lang.G.symbolName(Terminals[I].symbol()), Terminals[I].symbol()));
616     // Consume the token.
617     glrShift(Heads, Terminals[I], Params, Lang, NextHeads);
618 
619     // If we weren't able to consume the token, try to skip over some tokens
620     // so we can keep parsing.
621     if (NextHeads.empty()) {
622       // FIXME: Heads may not be fully reduced, because our reductions were
623       // constrained by lookahead (but lookahead is meaningless to recovery).
624       glrRecover(Heads, I, Params, Lang, NextHeads);
625       if (NextHeads.empty())
626         // FIXME: Ensure the `_ := start-symbol` rules have a fallback
627         // error-recovery strategy attached. Then this condition can't happen.
628         return Params.Forest.createOpaque(StartSymbol, /*Token::Index=*/0);
629     } else
630       ++I;
631 
632     // Form nonterminals containing the token we just consumed.
633     SymbolID Lookahead =
634         I == Terminals.size() ? tokenSymbol(tok::eof) : Terminals[I].symbol();
635     Reduce(NextHeads, Lookahead);
636     // Prepare for the next token.
637     std::swap(Heads, NextHeads);
638     NextHeads.clear();
639     MaybeGC();
640   }
641   LLVM_DEBUG(llvm::dbgs() << llvm::formatv("Reached eof\n"));
642 
643   // The parse was successful if we're in state `_ := start-symbol .`
644   auto AcceptState = Lang.Table.getGoToState(StartState, StartSymbol);
645   assert(AcceptState.has_value() && "goto must succeed after start symbol!");
646   auto SearchForAccept = [&](llvm::ArrayRef<const GSS::Node *> Heads) {
647     const ForestNode *Result = nullptr;
648     for (const auto *Head : Heads) {
649       if (Head->State == *AcceptState) {
650         assert(Head->Payload->symbol() == StartSymbol);
651         assert(Result == nullptr && "multiple results!");
652         Result = Head->Payload;
653       }
654     }
655     return Result;
656   };
657   if (auto *Result = SearchForAccept(Heads))
658     return *Result;
659   // Failed to parse the input, attempt to run recovery.
660   // FIXME: this awkwardly repeats the recovery in the loop, when shift fails.
661   // More elegant is to include EOF in the token stream, and make the
662   // augmented rule: `_ := translation-unit EOF`. In this way recovery at EOF
663   // would not be a special case: it show up as a failure to shift the EOF
664   // token.
665   unsigned I = Terminals.size();
666   glrRecover(Heads, I, Params, Lang, NextHeads);
667   Reduce(NextHeads, tokenSymbol(tok::eof));
668   if (auto *Result = SearchForAccept(NextHeads))
669     return *Result;
670 
671   // We failed to parse the input, returning an opaque forest node for recovery.
672   // FIXME: as above, we can add fallback error handling so this is impossible.
673   return Params.Forest.createOpaque(StartSymbol, /*Token::Index=*/0);
674 }
675 
676 void glrReduce(std::vector<const GSS::Node *> &Heads, SymbolID Lookahead,
677                const ParseParams &Params, const Language &Lang) {
678   // Create a new GLRReduce each time for tests, performance doesn't matter.
679   GLRReduce{Params, Lang}(Heads, Lookahead);
680 }
681 
682 const GSS::Node *GSS::addNode(LRTable::StateID State, const ForestNode *Symbol,
683 
684                               llvm::ArrayRef<const Node *> Parents) {
685   Node *Result = new (allocate(Parents.size()))
686       Node({State, GCParity, static_cast<uint16_t>(Parents.size())});
687   Alive.push_back(Result);
688   ++NodesCreated;
689   Result->Payload = Symbol;
690   if (!Parents.empty())
691     llvm::copy(Parents, reinterpret_cast<const Node **>(Result + 1));
692   return Result;
693 }
694 
695 GSS::Node *GSS::allocate(unsigned Parents) {
696   if (FreeList.size() <= Parents)
697     FreeList.resize(Parents + 1);
698   auto &SizedList = FreeList[Parents];
699   if (!SizedList.empty()) {
700     auto *Result = SizedList.back();
701     SizedList.pop_back();
702     return Result;
703   }
704   return static_cast<Node *>(
705       Arena.Allocate(sizeof(Node) + Parents * sizeof(Node *), alignof(Node)));
706 }
707 
708 void GSS::destroy(Node *N) {
709   unsigned ParentCount = N->ParentCount;
710   N->~Node();
711   assert(FreeList.size() > ParentCount && "established on construction!");
712   FreeList[ParentCount].push_back(N);
713 }
714 
715 unsigned GSS::gc(std::vector<const Node *> &&Queue) {
716 #ifndef NDEBUG
717   auto ParityMatches = [&](const Node *N) { return N->GCParity == GCParity; };
718   assert("Before GC" && llvm::all_of(Alive, ParityMatches));
719   auto Deferred = llvm::make_scope_exit(
720       [&] { assert("After GC" && llvm::all_of(Alive, ParityMatches)); });
721   assert(llvm::all_of(
722       Queue, [&](const Node *R) { return llvm::is_contained(Alive, R); }));
723 #endif
724   unsigned InitialCount = Alive.size();
725 
726   // Mark
727   GCParity = !GCParity;
728   while (!Queue.empty()) {
729     Node *N = const_cast<Node *>(Queue.back()); // Safe: we created these nodes.
730     Queue.pop_back();
731     if (N->GCParity != GCParity) { // Not seen yet
732       N->GCParity = GCParity;      // Mark as seen
733       for (const Node *P : N->parents()) // And walk parents
734         Queue.push_back(P);
735     }
736   }
737   // Sweep
738   llvm::erase_if(Alive, [&](Node *N) {
739     if (N->GCParity == GCParity) // Walk reached this node.
740       return false;
741     destroy(N);
742     return true;
743   });
744 
745   LLVM_DEBUG(llvm::dbgs() << "GC pruned " << (InitialCount - Alive.size())
746                           << "/" << InitialCount << " GSS nodes\n");
747   return InitialCount - Alive.size();
748 }
749 
750 } // namespace pseudo
751 } // namespace clang
752