1 //===-- lib/Parser/basic-parsers.h ------------------------------*- 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 #ifndef FORTRAN_PARSER_BASIC_PARSERS_H_
10 #define FORTRAN_PARSER_BASIC_PARSERS_H_
11 
12 // Let a "parser" be an instance of any class that supports this
13 // type definition and member (or static) function:
14 //
15 //   using resultType = ...;
16 //   std::optional<resultType> Parse(ParseState &) const;
17 //
18 // which either returns a value to signify a successful recognition or else
19 // returns {} to signify failure.  On failure, the state cannot be assumed
20 // to still be valid, in general -- see below for exceptions.
21 //
22 // This header defines the fundamental parser class templates and helper
23 // template functions.  See parser-combinators.txt for documentation.
24 
25 #include "flang/Common/Fortran-features.h"
26 #include "flang/Common/idioms.h"
27 #include "flang/Common/indirection.h"
28 #include "flang/Parser/char-block.h"
29 #include "flang/Parser/message.h"
30 #include "flang/Parser/parse-state.h"
31 #include "flang/Parser/provenance.h"
32 #include "flang/Parser/user-state.h"
33 #include <cstring>
34 #include <functional>
35 #include <list>
36 #include <memory>
37 #include <optional>
38 #include <string>
39 #include <tuple>
40 #include <type_traits>
41 #include <utility>
42 
43 namespace Fortran::parser {
44 
45 // fail<A>("..."_err_en_US) returns a parser that never succeeds.  It reports an
46 // error message at the current position.  The result type is unused,
47 // but might have to be specified at the point of call to satisfy
48 // the type checker.  The state remains valid.
49 template <typename A> class FailParser {
50 public:
51   using resultType = A;
52   constexpr FailParser(const FailParser &) = default;
53   constexpr explicit FailParser(MessageFixedText t) : text_{t} {}
54   std::optional<A> Parse(ParseState &state) const {
55     state.Say(text_);
56     return std::nullopt;
57   }
58 
59 private:
60   const MessageFixedText text_;
61 };
62 
63 template <typename A = Success> inline constexpr auto fail(MessageFixedText t) {
64   return FailParser<A>{t};
65 }
66 
67 // pure(x) returns a parser that always succeeds, does not advance the
68 // parse, and returns a captured value whose type must be copy-constructible.
69 template <typename A> class PureParser {
70 public:
71   using resultType = A;
72   constexpr PureParser(const PureParser &) = default;
73   constexpr explicit PureParser(A &&x) : value_(std::move(x)) {}
74   std::optional<A> Parse(ParseState &) const { return value_; }
75 
76 private:
77   const A value_;
78 };
79 
80 template <typename A> inline constexpr auto pure(A x) {
81   return PureParser<A>(std::move(x));
82 }
83 
84 // If a is a parser, attempt(a) is the same parser, but on failure
85 // the ParseState is guaranteed to have been restored to its initial value.
86 template <typename A> class BacktrackingParser {
87 public:
88   using resultType = typename A::resultType;
89   constexpr BacktrackingParser(const BacktrackingParser &) = default;
90   constexpr BacktrackingParser(const A &parser) : parser_{parser} {}
91   std::optional<resultType> Parse(ParseState &state) const {
92     Messages messages{std::move(state.messages())};
93     ParseState backtrack{state};
94     std::optional<resultType> result{parser_.Parse(state)};
95     if (result) {
96       state.messages().Restore(std::move(messages));
97     } else {
98       state = std::move(backtrack);
99       state.messages() = std::move(messages);
100     }
101     return result;
102   }
103 
104 private:
105   const A parser_;
106 };
107 
108 template <typename A> inline constexpr auto attempt(const A &parser) {
109   return BacktrackingParser<A>{parser};
110 }
111 
112 // For any parser x, the parser returned by !x is one that succeeds when
113 // x fails, returning a useless (but present) result.  !x fails when x succeeds.
114 template <typename PA> class NegatedParser {
115 public:
116   using resultType = Success;
117   constexpr NegatedParser(const NegatedParser &) = default;
118   constexpr NegatedParser(PA p) : parser_{p} {}
119   std::optional<Success> Parse(ParseState &state) const {
120     ParseState forked{state};
121     forked.set_deferMessages(true);
122     if (parser_.Parse(forked)) {
123       return std::nullopt;
124     }
125     return Success{};
126   }
127 
128 private:
129   const PA parser_;
130 };
131 
132 template <typename PA, typename = typename PA::resultType>
133 constexpr auto operator!(PA p) {
134   return NegatedParser<PA>(p);
135 }
136 
137 // For any parser x, the parser returned by lookAhead(x) is one that succeeds
138 // or fails if x does, but the state is not modified.
139 template <typename PA> class LookAheadParser {
140 public:
141   using resultType = Success;
142   constexpr LookAheadParser(const LookAheadParser &) = default;
143   constexpr LookAheadParser(PA p) : parser_{p} {}
144   std::optional<Success> Parse(ParseState &state) const {
145     ParseState forked{state};
146     forked.set_deferMessages(true);
147     if (parser_.Parse(forked)) {
148       return Success{};
149     }
150     return std::nullopt;
151   }
152 
153 private:
154   const PA parser_;
155 };
156 
157 template <typename PA> inline constexpr auto lookAhead(PA p) {
158   return LookAheadParser<PA>{p};
159 }
160 
161 // If a is a parser, inContext("..."_en_US, a) runs it in a nested message
162 // context.
163 template <typename PA> class MessageContextParser {
164 public:
165   using resultType = typename PA::resultType;
166   constexpr MessageContextParser(const MessageContextParser &) = default;
167   constexpr MessageContextParser(MessageFixedText t, PA p)
168       : text_{t}, parser_{p} {}
169   std::optional<resultType> Parse(ParseState &state) const {
170     state.PushContext(text_);
171     std::optional<resultType> result{parser_.Parse(state)};
172     state.PopContext();
173     return result;
174   }
175 
176 private:
177   const MessageFixedText text_;
178   const PA parser_;
179 };
180 
181 template <typename PA>
182 inline constexpr auto inContext(MessageFixedText context, PA parser) {
183   return MessageContextParser{context, parser};
184 }
185 
186 // If a is a parser, withMessage("..."_en_US, a) runs it unchanged if it
187 // succeeds, and overrides its messages with a specific one if it fails and
188 // has matched no tokens.
189 template <typename PA> class WithMessageParser {
190 public:
191   using resultType = typename PA::resultType;
192   constexpr WithMessageParser(const WithMessageParser &) = default;
193   constexpr WithMessageParser(MessageFixedText t, PA p)
194       : text_{t}, parser_{p} {}
195   std::optional<resultType> Parse(ParseState &state) const {
196     Messages messages{std::move(state.messages())};
197     ParseState backtrack{state};
198     state.set_anyTokenMatched(false);
199     std::optional<resultType> result{parser_.Parse(state)};
200     bool emitMessage{false};
201     if (result) {
202       messages.Annex(std::move(state.messages()));
203       if (backtrack.anyTokenMatched()) {
204         state.set_anyTokenMatched();
205       }
206     } else if (state.anyTokenMatched()) {
207       emitMessage = state.messages().empty();
208       messages.Annex(std::move(state.messages()));
209       backtrack.set_anyTokenMatched();
210       if (state.anyDeferredMessages()) {
211         backtrack.set_anyDeferredMessages(true);
212       }
213       state = std::move(backtrack);
214     } else {
215       emitMessage = true;
216     }
217     state.messages() = std::move(messages);
218     if (emitMessage) {
219       state.Say(text_);
220     }
221     return result;
222   }
223 
224 private:
225   const MessageFixedText text_;
226   const PA parser_;
227 };
228 
229 template <typename PA>
230 inline constexpr auto withMessage(MessageFixedText msg, PA parser) {
231   return WithMessageParser{msg, parser};
232 }
233 
234 // If a and b are parsers, then a >> b returns a parser that succeeds when
235 // b succeeds after a does so, but fails when either a or b does.  The
236 // result is taken from b.  Similarly, a / b also succeeds if both a and b
237 // do so, but the result is that returned by a.
238 template <typename PA, typename PB> class SequenceParser {
239 public:
240   using resultType = typename PB::resultType;
241   constexpr SequenceParser(const SequenceParser &) = default;
242   constexpr SequenceParser(PA pa, PB pb) : pa_{pa}, pb_{pb} {}
243   std::optional<resultType> Parse(ParseState &state) const {
244     if (pa_.Parse(state)) {
245       return pb_.Parse(state);
246     } else {
247       return std::nullopt;
248     }
249   }
250 
251 private:
252   const PA pa_;
253   const PB pb_;
254 };
255 
256 template <typename PA, typename PB>
257 inline constexpr auto operator>>(PA pa, PB pb) {
258   return SequenceParser<PA, PB>{pa, pb};
259 }
260 
261 template <typename PA, typename PB> class FollowParser {
262 public:
263   using resultType = typename PA::resultType;
264   constexpr FollowParser(const FollowParser &) = default;
265   constexpr FollowParser(PA pa, PB pb) : pa_{pa}, pb_{pb} {}
266   std::optional<resultType> Parse(ParseState &state) const {
267     if (std::optional<resultType> ax{pa_.Parse(state)}) {
268       if (pb_.Parse(state)) {
269         return ax;
270       }
271     }
272     return std::nullopt;
273   }
274 
275 private:
276   const PA pa_;
277   const PB pb_;
278 };
279 
280 template <typename PA, typename PB>
281 inline constexpr auto operator/(PA pa, PB pb) {
282   return FollowParser<PA, PB>{pa, pb};
283 }
284 
285 template <typename PA, typename... Ps> class AlternativesParser {
286 public:
287   using resultType = typename PA::resultType;
288   constexpr AlternativesParser(PA pa, Ps... ps) : ps_{pa, ps...} {}
289   constexpr AlternativesParser(const AlternativesParser &) = default;
290   std::optional<resultType> Parse(ParseState &state) const {
291     Messages messages{std::move(state.messages())};
292     ParseState backtrack{state};
293     std::optional<resultType> result{std::get<0>(ps_).Parse(state)};
294     if constexpr (sizeof...(Ps) > 0) {
295       if (!result) {
296         ParseRest<1>(result, state, backtrack);
297       }
298     }
299     state.messages().Restore(std::move(messages));
300     return result;
301   }
302 
303 private:
304   template <int J>
305   void ParseRest(std::optional<resultType> &result, ParseState &state,
306       ParseState &backtrack) const {
307     ParseState prevState{std::move(state)};
308     state = backtrack;
309     result = std::get<J>(ps_).Parse(state);
310     if (!result) {
311       state.CombineFailedParses(std::move(prevState));
312       if constexpr (J < sizeof...(Ps)) {
313         ParseRest<J + 1>(result, state, backtrack);
314       }
315     }
316   }
317 
318   const std::tuple<PA, Ps...> ps_;
319 };
320 
321 template <typename... Ps> inline constexpr auto first(Ps... ps) {
322   return AlternativesParser<Ps...>{ps...};
323 }
324 
325 template <typename PA, typename PB>
326 inline constexpr auto operator||(PA pa, PB pb) {
327   return AlternativesParser<PA, PB>{pa, pb};
328 }
329 
330 // If a and b are parsers, then recovery(a,b) returns a parser that succeeds if
331 // a does so, or if a fails and b succeeds.  If a succeeds, b is not attempted.
332 // All messages from the first parse are retained.
333 // The two parsers must return values of the same type.
334 template <typename PA, typename PB> class RecoveryParser {
335 public:
336   using resultType = typename PA::resultType;
337   static_assert(std::is_same_v<resultType, typename PB::resultType>);
338   constexpr RecoveryParser(const RecoveryParser &) = default;
339   constexpr RecoveryParser(PA pa, PB pb) : pa_{pa}, pb_{pb} {}
340   std::optional<resultType> Parse(ParseState &state) const {
341     bool originallyDeferred{state.deferMessages()};
342     ParseState backtrack{state};
343     if (!originallyDeferred && state.messages().empty() &&
344         !state.anyErrorRecovery()) {
345       // Fast path.  There are no messages or recovered errors in the incoming
346       // state.  Attempt to parse with messages deferred, expecting that the
347       // parse will succeed silently.
348       state.set_deferMessages(true);
349       if (std::optional<resultType> ax{pa_.Parse(state)}) {
350         if (!state.anyDeferredMessages() && !state.anyErrorRecovery()) {
351           state.set_deferMessages(false);
352           return ax;
353         }
354       }
355       state = backtrack;
356     }
357     Messages messages{std::move(state.messages())};
358     if (std::optional<resultType> ax{pa_.Parse(state)}) {
359       state.messages().Restore(std::move(messages));
360       return ax;
361     }
362     messages.Annex(std::move(state.messages()));
363     bool hadDeferredMessages{state.anyDeferredMessages()};
364     bool anyTokenMatched{state.anyTokenMatched()};
365     state = std::move(backtrack);
366     state.set_deferMessages(true);
367     std::optional<resultType> bx{pb_.Parse(state)};
368     state.messages() = std::move(messages);
369     state.set_deferMessages(originallyDeferred);
370     if (anyTokenMatched) {
371       state.set_anyTokenMatched();
372     }
373     if (hadDeferredMessages) {
374       state.set_anyDeferredMessages();
375     }
376     if (bx) {
377       // Error recovery situations must also produce messages.
378       CHECK(state.anyDeferredMessages() || state.messages().AnyFatalError());
379       state.set_anyErrorRecovery();
380     }
381     return bx;
382   }
383 
384 private:
385   const PA pa_;
386   const PB pb_;
387 };
388 
389 template <typename PA, typename PB>
390 inline constexpr auto recovery(PA pa, PB pb) {
391   return RecoveryParser<PA, PB>{pa, pb};
392 }
393 
394 // If x is a parser, then many(x) returns a parser that always succeeds
395 // and whose value is a list, possibly empty, of the values returned from
396 // repeated application of x until it fails or does not advance the parse.
397 template <typename PA> class ManyParser {
398   using paType = typename PA::resultType;
399 
400 public:
401   using resultType = std::list<paType>;
402   constexpr ManyParser(const ManyParser &) = default;
403   constexpr ManyParser(PA parser) : parser_{parser} {}
404   std::optional<resultType> Parse(ParseState &state) const {
405     resultType result;
406     auto at{state.GetLocation()};
407     while (std::optional<paType> x{parser_.Parse(state)}) {
408       result.emplace_back(std::move(*x));
409       if (state.GetLocation() <= at) {
410         break; // no forward progress, don't loop
411       }
412       at = state.GetLocation();
413     }
414     return {std::move(result)};
415   }
416 
417 private:
418   const BacktrackingParser<PA> parser_;
419 };
420 
421 template <typename PA> inline constexpr auto many(PA parser) {
422   return ManyParser<PA>{parser};
423 }
424 
425 // If x is a parser, then some(x) returns a parser that succeeds if x does
426 // and whose value is a nonempty list of the values returned from repeated
427 // application of x until it fails or does not advance the parse.  In other
428 // words, some(x) is a variant of many(x) that has to succeed at least once.
429 template <typename PA> class SomeParser {
430   using paType = typename PA::resultType;
431 
432 public:
433   using resultType = std::list<paType>;
434   constexpr SomeParser(const SomeParser &) = default;
435   constexpr SomeParser(PA parser) : parser_{parser} {}
436   std::optional<resultType> Parse(ParseState &state) const {
437     auto start{state.GetLocation()};
438     if (std::optional<paType> first{parser_.Parse(state)}) {
439       resultType result;
440       result.emplace_back(std::move(*first));
441       if (state.GetLocation() > start) {
442         result.splice(result.end(), many(parser_).Parse(state).value());
443       }
444       return {std::move(result)};
445     }
446     return std::nullopt;
447   }
448 
449 private:
450   const PA parser_;
451 };
452 
453 template <typename PA> inline constexpr auto some(PA parser) {
454   return SomeParser<PA>{parser};
455 }
456 
457 // If x is a parser, skipMany(x) is equivalent to many(x) but with no result.
458 template <typename PA> class SkipManyParser {
459 public:
460   using resultType = Success;
461   constexpr SkipManyParser(const SkipManyParser &) = default;
462   constexpr SkipManyParser(PA parser) : parser_{parser} {}
463   std::optional<Success> Parse(ParseState &state) const {
464     for (auto at{state.GetLocation()};
465          parser_.Parse(state) && state.GetLocation() > at;
466          at = state.GetLocation()) {
467     }
468     return Success{};
469   }
470 
471 private:
472   const BacktrackingParser<PA> parser_;
473 };
474 
475 template <typename PA> inline constexpr auto skipMany(PA parser) {
476   return SkipManyParser<PA>{parser};
477 }
478 
479 // If x is a parser, skipManyFast(x) is equivalent to skipMany(x).
480 // The parser x must always advance on success and never invalidate the
481 // state on failure.
482 template <typename PA> class SkipManyFastParser {
483 public:
484   using resultType = Success;
485   constexpr SkipManyFastParser(const SkipManyFastParser &) = default;
486   constexpr SkipManyFastParser(PA parser) : parser_{parser} {}
487   std::optional<Success> Parse(ParseState &state) const {
488     while (parser_.Parse(state)) {
489     }
490     return Success{};
491   }
492 
493 private:
494   const PA parser_;
495 };
496 
497 template <typename PA> inline constexpr auto skipManyFast(PA parser) {
498   return SkipManyFastParser<PA>{parser};
499 }
500 
501 // If x is a parser returning some type A, then maybe(x) returns a
502 // parser that returns std::optional<A>, always succeeding.
503 template <typename PA> class MaybeParser {
504   using paType = typename PA::resultType;
505 
506 public:
507   using resultType = std::optional<paType>;
508   constexpr MaybeParser(const MaybeParser &) = default;
509   constexpr MaybeParser(PA parser) : parser_{parser} {}
510   std::optional<resultType> Parse(ParseState &state) const {
511     if (resultType result{parser_.Parse(state)}) {
512       // permit optional<optional<...>>
513       return {std::move(result)};
514     }
515     return resultType{};
516   }
517 
518 private:
519   const BacktrackingParser<PA> parser_;
520 };
521 
522 template <typename PA> inline constexpr auto maybe(PA parser) {
523   return MaybeParser<PA>{parser};
524 }
525 
526 // If x is a parser, then defaulted(x) returns a parser that always
527 // succeeds.  When x succeeds, its result is that of x; otherwise, its
528 // result is a default-constructed value of x's result type.
529 template <typename PA> class DefaultedParser {
530 public:
531   using resultType = typename PA::resultType;
532   constexpr DefaultedParser(const DefaultedParser &) = default;
533   constexpr DefaultedParser(PA p) : parser_{p} {}
534   std::optional<resultType> Parse(ParseState &state) const {
535     std::optional<std::optional<resultType>> ax{maybe(parser_).Parse(state)};
536     if (ax.value()) { // maybe() always succeeds
537       return std::move(*ax);
538     }
539     return resultType{};
540   }
541 
542 private:
543   const BacktrackingParser<PA> parser_;
544 };
545 
546 template <typename PA> inline constexpr auto defaulted(PA p) {
547   return DefaultedParser<PA>(p);
548 }
549 
550 // If a is a parser, and f is a function mapping an rvalue of a's result type
551 // to some other type T, then applyFunction(f, a) returns a parser that succeeds
552 // iff a does, and whose result value ax has been passed through the function;
553 // the final result is that returned by the call f(std::move(ax)).
554 //
555 // Function application is generalized to functions with more than one
556 // argument with applyFunction(f, a, b, ...) succeeding if all of the parsers
557 // a, b, &c. do so, and the result is the value of applying f to their
558 // results.
559 //
560 // applyLambda(f, ...) is the same concept extended to std::function<> functors.
561 // It is not constexpr.
562 //
563 // Member function application is supported by applyMem(f, a).  If the
564 // parser a succeeds and returns some value ax, the result is that returned
565 // by ax.f().  Additional parser arguments can be specified to supply their
566 // results to the member function call, so applyMem(f, a, b) succeeds if
567 // both a and b do so and returns the result of calling ax.f(std::move(bx)).
568 
569 // Runs a sequence of parsers until one fails or all have succeeded.
570 // Collects their results in a std::tuple<std::optional<>...>.
571 template <typename... PARSER>
572 using ApplyArgs = std::tuple<std::optional<typename PARSER::resultType>...>;
573 
574 template <typename... PARSER, std::size_t... J>
575 inline bool ApplyHelperArgs(const std::tuple<PARSER...> &parsers,
576     ApplyArgs<PARSER...> &args, ParseState &state, std::index_sequence<J...>) {
577   return (... &&
578       (std::get<J>(args) = std::get<J>(parsers).Parse(state),
579           std::get<J>(args).has_value()));
580 }
581 
582 // Applies a function to the arguments collected by ApplyHelperArgs.
583 template <typename RESULT, typename... PARSER>
584 using ApplicableFunctionPointer = RESULT (*)(typename PARSER::resultType &&...);
585 template <typename RESULT, typename... PARSER>
586 using ApplicableFunctionObject =
587     const std::function<RESULT(typename PARSER::resultType &&...)> &;
588 
589 template <template <typename...> class FUNCTION, typename RESULT,
590     typename... PARSER, std::size_t... J>
591 inline RESULT ApplyHelperFunction(FUNCTION<RESULT, PARSER...> f,
592     ApplyArgs<PARSER...> &&args, std::index_sequence<J...>) {
593   return f(std::move(*std::get<J>(args))...);
594 }
595 
596 template <template <typename...> class FUNCTION, typename RESULT,
597     typename... PARSER>
598 class ApplyFunction {
599   using funcType = FUNCTION<RESULT, PARSER...>;
600 
601 public:
602   using resultType = RESULT;
603   constexpr ApplyFunction(const ApplyFunction &) = default;
604   constexpr ApplyFunction(funcType f, PARSER... p)
605       : function_{f}, parsers_{p...} {}
606   std::optional<resultType> Parse(ParseState &state) const {
607     ApplyArgs<PARSER...> results;
608     using Sequence = std::index_sequence_for<PARSER...>;
609     if (ApplyHelperArgs(parsers_, results, state, Sequence{})) {
610       return ApplyHelperFunction<FUNCTION, RESULT, PARSER...>(
611           function_, std::move(results), Sequence{});
612     } else {
613       return std::nullopt;
614     }
615   }
616 
617 private:
618   const funcType function_;
619   const std::tuple<PARSER...> parsers_;
620 };
621 
622 template <typename RESULT, typename... PARSER>
623 inline constexpr auto applyFunction(
624     ApplicableFunctionPointer<RESULT, PARSER...> f, const PARSER &... parser) {
625   return ApplyFunction<ApplicableFunctionPointer, RESULT, PARSER...>{
626       f, parser...};
627 }
628 
629 template <typename RESULT, typename... PARSER>
630 inline /* not constexpr */ auto applyLambda(
631     ApplicableFunctionObject<RESULT, PARSER...> f, const PARSER &... parser) {
632   return ApplyFunction<ApplicableFunctionObject, RESULT, PARSER...>{
633       f, parser...};
634 }
635 
636 // Member function application
637 template <typename OBJPARSER, typename... PARSER> class AMFPHelper {
638   using resultType = typename OBJPARSER::resultType;
639 
640 public:
641   using type = void (resultType::*)(typename PARSER::resultType &&...);
642 };
643 template <typename OBJPARSER, typename... PARSER>
644 using ApplicableMemberFunctionPointer =
645     typename AMFPHelper<OBJPARSER, PARSER...>::type;
646 
647 template <typename OBJPARSER, typename... PARSER, std::size_t... J>
648 inline auto ApplyHelperMember(
649     ApplicableMemberFunctionPointer<OBJPARSER, PARSER...> mfp,
650     ApplyArgs<OBJPARSER, PARSER...> &&args, std::index_sequence<J...>) ->
651     typename OBJPARSER::resultType {
652   ((*std::get<0>(args)).*mfp)(std::move(*std::get<J + 1>(args))...);
653   return std::get<0>(std::move(args));
654 }
655 
656 template <typename OBJPARSER, typename... PARSER> class ApplyMemberFunction {
657   using funcType = ApplicableMemberFunctionPointer<OBJPARSER, PARSER...>;
658 
659 public:
660   using resultType = typename OBJPARSER::resultType;
661   constexpr ApplyMemberFunction(const ApplyMemberFunction &) = default;
662   constexpr ApplyMemberFunction(funcType f, OBJPARSER o, PARSER... p)
663       : function_{f}, parsers_{o, p...} {}
664   std::optional<resultType> Parse(ParseState &state) const {
665     ApplyArgs<OBJPARSER, PARSER...> results;
666     using Sequence1 = std::index_sequence_for<OBJPARSER, PARSER...>;
667     using Sequence2 = std::index_sequence_for<PARSER...>;
668     if (ApplyHelperArgs(parsers_, results, state, Sequence1{})) {
669       return ApplyHelperMember<OBJPARSER, PARSER...>(
670           function_, std::move(results), Sequence2{});
671     } else {
672       return std::nullopt;
673     }
674   }
675 
676 private:
677   const funcType function_;
678   const std::tuple<OBJPARSER, PARSER...> parsers_;
679 };
680 
681 template <typename OBJPARSER, typename... PARSER>
682 inline constexpr auto applyMem(
683     ApplicableMemberFunctionPointer<OBJPARSER, PARSER...> mfp,
684     const OBJPARSER &objParser, PARSER... parser) {
685   return ApplyMemberFunction<OBJPARSER, PARSER...>{mfp, objParser, parser...};
686 }
687 
688 // As is done with function application via applyFunction() above, class
689 // instance construction can also be based upon the results of successful
690 // parses.  For some type T and zero or more parsers a, b, &c., the call
691 // construct<T>(a, b, ...) returns a parser that succeeds if all of
692 // its argument parsers do so in succession, and whose result is an
693 // instance of T constructed upon the values they returned.
694 // With a single argument that is a parser with no usable value,
695 // construct<T>(p) invokes T's default nullary constructor (T(){}).
696 // (This means that "construct<T>(Foo >> Bar >> ok)" is functionally
697 // equivalent to "Foo >> Bar >> construct<T>()", but I'd like to hold open
698 // the opportunity to make construct<> capture source provenance all of the
699 // time, and the first form will then lead to better error positioning.)
700 
701 template <typename RESULT, typename... PARSER, std::size_t... J>
702 inline RESULT ApplyHelperConstructor(
703     ApplyArgs<PARSER...> &&args, std::index_sequence<J...>) {
704   return RESULT{std::move(*std::get<J>(args))...};
705 }
706 
707 template <typename RESULT, typename... PARSER> class ApplyConstructor {
708 public:
709   using resultType = RESULT;
710   constexpr ApplyConstructor(const ApplyConstructor &) = default;
711   constexpr explicit ApplyConstructor(PARSER... p) : parsers_{p...} {}
712   std::optional<resultType> Parse(ParseState &state) const {
713     if constexpr (sizeof...(PARSER) == 0) {
714       return RESULT{};
715     } else {
716       if constexpr (sizeof...(PARSER) == 1) {
717         if constexpr (std::is_same_v<Success, typename PARSER::resultType...>) {
718           if (std::get<0>(parsers_).Parse(state)) {
719             return RESULT{};
720           }
721         } else if (auto arg{std::get<0>(parsers_).Parse(state)}) {
722           return RESULT{std::move(*arg)};
723         }
724       } else {
725         ApplyArgs<PARSER...> results;
726         using Sequence = std::index_sequence_for<PARSER...>;
727         if (ApplyHelperArgs(parsers_, results, state, Sequence{})) {
728           return ApplyHelperConstructor<RESULT, PARSER...>(
729               std::move(results), Sequence{});
730         }
731       }
732       return std::nullopt;
733     }
734   }
735 
736 private:
737   const std::tuple<PARSER...> parsers_;
738 };
739 
740 template <typename RESULT, typename... PARSER>
741 inline constexpr auto construct(PARSER... p) {
742   return ApplyConstructor<RESULT, PARSER...>{p...};
743 }
744 
745 // For a parser p, indirect(p) returns a parser that builds an indirect
746 // reference to p's return type.
747 template <typename PA> inline constexpr auto indirect(PA p) {
748   return construct<common::Indirection<typename PA::resultType>>(p);
749 }
750 
751 // If a and b are parsers, then nonemptySeparated(a, b) returns a parser
752 // that succeeds if a does.  If a succeeds, it then applies many(b >> a).
753 // The result is the list of the values returned from all of the applications
754 // of a.
755 template <typename T>
756 common::IfNoLvalue<std::list<T>, T> prepend(T &&head, std::list<T> &&rest) {
757   rest.push_front(std::move(head));
758   return std::move(rest);
759 }
760 
761 template <typename PA, typename PB> class NonemptySeparated {
762 private:
763   using paType = typename PA::resultType;
764 
765 public:
766   using resultType = std::list<paType>;
767   constexpr NonemptySeparated(const NonemptySeparated &) = default;
768   constexpr NonemptySeparated(PA p, PB sep) : parser_{p}, separator_{sep} {}
769   std::optional<resultType> Parse(ParseState &state) const {
770     return applyFunction(prepend<paType>, parser_, many(separator_ >> parser_))
771         .Parse(state);
772   }
773 
774 private:
775   const PA parser_;
776   const PB separator_;
777 };
778 
779 template <typename PA, typename PB>
780 inline constexpr auto nonemptySeparated(PA p, PB sep) {
781   return NonemptySeparated<PA, PB>{p, sep};
782 }
783 
784 // ok is a parser that always succeeds.  It is useful when a parser
785 // must discard its result in order to be compatible in type with other
786 // parsers in an alternative, e.g. "x >> ok || y >> ok" is type-safe even
787 // when x and y have distinct result types.
788 //
789 // cut is a parser that always fails.  It is useful when a parser must
790 // have its type implicitly set; one use is the idiom "defaulted(cut >> x)",
791 // which is essentially what "pure(T{})" would be able to do for x's
792 // result type T, but without requiring that T have a default constructor
793 // or a non-trivial destructor.  The state is preserved.
794 template <bool pass> struct FixedParser {
795   using resultType = Success;
796   constexpr FixedParser() {}
797   static constexpr std::optional<Success> Parse(ParseState &) {
798     if constexpr (pass) {
799       return Success{};
800     } else {
801       return std::nullopt;
802     }
803   }
804 };
805 
806 constexpr FixedParser<true> ok;
807 constexpr FixedParser<false> cut;
808 
809 // A variant of recovery() above for convenience.
810 template <typename PA, typename PB>
811 inline constexpr auto localRecovery(MessageFixedText msg, PA pa, PB pb) {
812   return recovery(withMessage(msg, pa), pb >> defaulted(cut >> pa));
813 }
814 
815 // nextCh is a parser that succeeds if the parsing state is not
816 // at the end of its input, returning the next character location and
817 // advancing the parse when it does so.
818 struct NextCh {
819   using resultType = const char *;
820   constexpr NextCh() {}
821   std::optional<const char *> Parse(ParseState &state) const {
822     if (std::optional<const char *> result{state.GetNextChar()}) {
823       return result;
824     }
825     state.Say("end of file"_err_en_US);
826     return std::nullopt;
827   }
828 };
829 
830 constexpr NextCh nextCh;
831 
832 // If a is a parser for some nonstandard language feature LF, extension<LF>(a)
833 // is a parser that optionally enabled, sets a strict conformance violation
834 // flag, and may emit a warning message, if those are enabled.
835 template <LanguageFeature LF, typename PA> class NonstandardParser {
836 public:
837   using resultType = typename PA::resultType;
838   constexpr NonstandardParser(const NonstandardParser &) = default;
839   constexpr NonstandardParser(PA parser) : parser_{parser} {}
840   std::optional<resultType> Parse(ParseState &state) const {
841     if (UserState * ustate{state.userState()}) {
842       if (!ustate->features().IsEnabled(LF)) {
843         return std::nullopt;
844       }
845     }
846     auto at{state.GetLocation()};
847     auto result{parser_.Parse(state)};
848     if (result) {
849       state.Nonstandard(
850           CharBlock{at, state.GetLocation()}, LF, "nonstandard usage"_en_US);
851     }
852     return result;
853   }
854 
855 private:
856   const PA parser_;
857 };
858 
859 template <LanguageFeature LF, typename PA>
860 inline constexpr auto extension(PA parser) {
861   return NonstandardParser<LF, PA>(parser);
862 }
863 
864 // If a is a parser for some deprecated or deleted language feature LF,
865 // deprecated<LF>(a) is a parser that is optionally enabled, sets a strict
866 // conformance violation flag, and may emit a warning message, if enabled.
867 template <LanguageFeature LF, typename PA> class DeprecatedParser {
868 public:
869   using resultType = typename PA::resultType;
870   constexpr DeprecatedParser(const DeprecatedParser &) = default;
871   constexpr DeprecatedParser(PA parser) : parser_{parser} {}
872   std::optional<resultType> Parse(ParseState &state) const {
873     if (UserState * ustate{state.userState()}) {
874       if (!ustate->features().IsEnabled(LF)) {
875         return std::nullopt;
876       }
877     }
878     auto at{state.GetLocation()};
879     auto result{parser_.Parse(state)};
880     if (result) {
881       state.Nonstandard(
882           CharBlock{at, state.GetLocation()}, LF, "deprecated usage"_en_US);
883     }
884     return result;
885   }
886 
887 private:
888   const PA parser_;
889 };
890 
891 template <LanguageFeature LF, typename PA>
892 inline constexpr auto deprecated(PA parser) {
893   return DeprecatedParser<LF, PA>(parser);
894 }
895 
896 // Parsing objects with "source" members.
897 template <typename PA> class SourcedParser {
898 public:
899   using resultType = typename PA::resultType;
900   constexpr SourcedParser(const SourcedParser &) = default;
901   constexpr SourcedParser(PA parser) : parser_{parser} {}
902   std::optional<resultType> Parse(ParseState &state) const {
903     const char *start{state.GetLocation()};
904     auto result{parser_.Parse(state)};
905     if (result) {
906       const char *end{state.GetLocation()};
907       for (; start < end && start[0] == ' '; ++start) {
908       }
909       for (; start < end && end[-1] == ' '; --end) {
910       }
911       result->source = CharBlock{start, end};
912     }
913     return result;
914   }
915 
916 private:
917   const PA parser_;
918 };
919 
920 template <typename PA> inline constexpr auto sourced(PA parser) {
921   return SourcedParser<PA>{parser};
922 }
923 } // namespace Fortran::parser
924 #endif // FORTRAN_PARSER_BASIC_PARSERS_H_
925