common.h 25.9 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35
// Parser combinator framework!
//
// This file declares several functions which construct parsers, usually taking other parsers as
// input, thus making them parser combinators.
//
// A valid parser is any functor which takes a reference to an input cursor (defined below) as its
// input and returns a Maybe.  The parser returns null on parse failure, or returns the parsed
// result on success.
//
// An "input cursor" is any type which implements the same interface as IteratorInput, below.  Such
// a type acts as a pointer to the current input location.  When a parser returns successfully, it
// will have updated the input cursor to point to the position just past the end of what was parsed.
// On failure, the cursor position is unspecified.

36
#pragma once
37

38 39 40 41
#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
#pragma GCC system_header
#endif

42 43 44 45 46
#include "../common.h"
#include "../memory.h"
#include "../array.h"
#include "../tuple.h"
#include "../vector.h"
47
#if _MSC_VER && !__clang__
48 49
#include <type_traits>  // result_of_t
#endif
50 51 52 53 54 55

namespace kj {
namespace parse {

template <typename Element, typename Iterator>
class IteratorInput {
56 57
  // A parser input implementation based on an iterator range.

58 59 60
public:
  IteratorInput(Iterator begin, Iterator end)
      : parent(nullptr), pos(begin), end(end), best(begin) {}
61
  explicit IteratorInput(IteratorInput& parent)
62 63 64 65 66 67
      : parent(&parent), pos(parent.pos), end(parent.end), best(parent.pos) {}
  ~IteratorInput() {
    if (parent != nullptr) {
      parent->best = kj::max(kj::max(pos, best), parent->best);
    }
  }
68
  KJ_DISALLOW_COPY(IteratorInput);
69 70 71 72

  void advanceParent() {
    parent->pos = pos;
  }
73 74 75
  void forgetParent() {
    parent = nullptr;
  }
76 77

  bool atEnd() { return pos == end; }
78
  auto current() -> decltype(*instance<Iterator>()) {
79 80 81
    KJ_IREQUIRE(!atEnd());
    return *pos;
  }
82
  auto consume() -> decltype(*instance<Iterator>()) {
83
    KJ_IREQUIRE(!atEnd());
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    return *pos++;
  }
  void next() {
    KJ_IREQUIRE(!atEnd());
    ++pos;
  }

  Iterator getBest() { return kj::max(pos, best); }

  Iterator getPosition() { return pos; }

private:
  IteratorInput* parent;
  Iterator pos;
  Iterator end;
  Iterator best;  // furthest we got with any sub-input
};

102 103 104
template <typename T> struct OutputType_;
template <typename T> struct OutputType_<Maybe<T>> { typedef T Type; };
template <typename Parser, typename Input>
105
using OutputType = typename OutputType_<
106
#if _MSC_VER && !__clang__
107 108 109 110 111 112 113
    std::result_of_t<Parser(Input)>
    // The instance<T&>() based version below results in:
    //   C2064: term does not evaluate to a function taking 1 arguments
#else
    decltype(instance<Parser&>()(instance<Input&>()))
#endif
    >::Type;
114
// Synonym for the output type of a parser, given the parser type and the input type.
115 116 117 118

// =======================================================================================

template <typename Input, typename Output>
119 120 121 122 123
class ParserRef {
  // Acts as a reference to some other parser, with simplified type.  The referenced parser
  // is polymorphic by virtual call rather than templates.  For grammars of non-trivial size,
  // it is important to inject refs into the grammar here and there to prevent the parser types
  // from becoming ridiculous.  Using too many of them can hurt performance, though.
124 125

public:
126 127 128 129 130 131
  ParserRef(): parser(nullptr), wrapper(nullptr) {}
  ParserRef(const ParserRef&) = default;
  ParserRef(ParserRef&&) = default;
  ParserRef& operator=(const ParserRef& other) = default;
  ParserRef& operator=(ParserRef&& other) = default;

132
  template <typename Other>
133 134
  constexpr ParserRef(Other&& other)
      : parser(&other), wrapper(&WrapperImplInstance<Decay<Other>>::instance) {
135
    static_assert(kj::isReference<Other>(), "ParserRef should not be assigned to a temporary.");
136 137 138 139
  }

  template <typename Other>
  inline ParserRef& operator=(Other&& other) {
140
    static_assert(kj::isReference<Other>(), "ParserRef should not be assigned to a temporary.");
141 142 143 144
    parser = &other;
    wrapper = &WrapperImplInstance<Decay<Other>>::instance;
    return *this;
  }
145

146 147 148
  KJ_ALWAYS_INLINE(Maybe<Output> operator()(Input& input) const) {
    // Always inline in the hopes that this allows branch prediction to kick in so the virtual call
    // doesn't hurt so much.
149
    return wrapper->parse(parser, input);
150 151 152
  }

private:
153 154 155 156 157 158 159
  struct Wrapper {
    virtual Maybe<Output> parse(const void* parser, Input& input) const = 0;
  };
  template <typename ParserImpl>
  struct WrapperImpl: public Wrapper {
    Maybe<Output> parse(const void* parser, Input& input) const override {
      return (*reinterpret_cast<const ParserImpl*>(parser))(input);
160
    }
Kenton Varda's avatar
Kenton Varda committed
161 162 163
  };
  template <typename ParserImpl>
  struct WrapperImplInstance {
164
#if _MSC_VER && !__clang__
165
    // TODO(msvc): MSVC currently fails to initialize vtable pointers for constexpr values so
Harris Hancock's avatar
Harris Hancock committed
166
    //   we have to make this just const instead.
167 168
    static const WrapperImpl<ParserImpl> instance;
#else
Kenton Varda's avatar
Kenton Varda committed
169
    static constexpr WrapperImpl<ParserImpl> instance = WrapperImpl<ParserImpl>();
170
#endif
171 172
  };

173
  const void* parser;
174
  const Wrapper* wrapper;
175 176
};

Kenton Varda's avatar
Kenton Varda committed
177 178
template <typename Input, typename Output>
template <typename ParserImpl>
179
#if _MSC_VER && !__clang__
180 181 182
const typename ParserRef<Input, Output>::template WrapperImpl<ParserImpl>
ParserRef<Input, Output>::WrapperImplInstance<ParserImpl>::instance = WrapperImpl<ParserImpl>();
#else
183
constexpr typename ParserRef<Input, Output>::template WrapperImpl<ParserImpl>
Kenton Varda's avatar
Kenton Varda committed
184
ParserRef<Input, Output>::WrapperImplInstance<ParserImpl>::instance;
185
#endif
Kenton Varda's avatar
Kenton Varda committed
186

187
template <typename Input, typename ParserImpl>
Kenton Varda's avatar
Kenton Varda committed
188
constexpr ParserRef<Input, OutputType<ParserImpl, Input>> ref(ParserImpl& impl) {
189 190
  // Constructs a ParserRef.  You must specify the input type explicitly, e.g.
  // `ref<MyInput>(myParser)`.
191

192 193
  return ParserRef<Input, OutputType<ParserImpl, Input>>(impl);
}
194

195
// -------------------------------------------------------------------
196
// any
197 198 199 200 201
// Output = one token

class Any_ {
public:
  template <typename Input>
202
  Maybe<Decay<decltype(instance<Input>().consume())>> operator()(Input& input) const {
203 204 205
    if (input.atEnd()) {
      return nullptr;
    } else {
206
      return input.consume();
207 208 209 210
    }
  }
};

211 212
constexpr Any_ any = Any_();
// A parser which matches any token and simply returns it.
213

214
// -------------------------------------------------------------------
215
// exactly()
216
// Output = Tuple<>
217

218 219
template <typename T>
class Exactly_ {
220
public:
Kenton Varda's avatar
Kenton Varda committed
221
  explicit constexpr Exactly_(T&& expected): expected(expected) {}
222

223 224
  template <typename Input>
  Maybe<Tuple<>> operator()(Input& input) const {
225 226 227 228
    if (input.atEnd() || input.current() != expected) {
      return nullptr;
    } else {
      input.next();
229
      return Tuple<>();
230 231 232 233
    }
  }

private:
234
  T expected;
235 236
};

237
template <typename T>
Kenton Varda's avatar
Kenton Varda committed
238
constexpr Exactly_<T> exactly(T&& expected) {
239 240 241 242
  // Constructs a parser which succeeds when the input is exactly the token specified.  The
  // result is always the empty tuple.

  return Exactly_<T>(kj::fwd<T>(expected));
243 244
}

Kenton Varda's avatar
Kenton Varda committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
// -------------------------------------------------------------------
// exactlyConst()
// Output = Tuple<>

template <typename T, T expected>
class ExactlyConst_ {
public:
  explicit constexpr ExactlyConst_() {}

  template <typename Input>
  Maybe<Tuple<>> operator()(Input& input) const {
    if (input.atEnd() || input.current() != expected) {
      return nullptr;
    } else {
      input.next();
      return Tuple<>();
    }
  }
};

template <typename T, T expected>
constexpr ExactlyConst_<T, expected> exactlyConst() {
  // Constructs a parser which succeeds when the input is exactly the token specified.  The
  // result is always the empty tuple.  This parser is templated on the token value which may cause
  // it to perform better -- or worse.  Be sure to measure.

  return ExactlyConst_<T, expected>();
}

// -------------------------------------------------------------------
// constResult()

template <typename SubParser, typename Result>
class ConstResult_ {
public:
  explicit constexpr ConstResult_(SubParser&& subParser, Result&& result)
      : subParser(kj::fwd<SubParser>(subParser)), result(kj::fwd<Result>(result)) {}

  template <typename Input>
  Maybe<Result> operator()(Input& input) const {
    if (subParser(input) == nullptr) {
      return nullptr;
    } else {
      return result;
    }
  }

private:
  SubParser subParser;
  Result result;
};

template <typename SubParser, typename Result>
constexpr ConstResult_<SubParser, Result> constResult(SubParser&& subParser, Result&& result) {
  // Constructs a parser which returns exactly `result` if `subParser` is successful.
  return ConstResult_<SubParser, Result>(kj::fwd<SubParser>(subParser), kj::fwd<Result>(result));
}

303 304 305 306 307 308
template <typename SubParser>
constexpr ConstResult_<SubParser, Tuple<>> discard(SubParser&& subParser) {
  // Constructs a parser which wraps `subParser` but discards the result.
  return constResult(kj::fwd<SubParser>(subParser), Tuple<>());
}

309
// -------------------------------------------------------------------
310
// sequence()
311 312
// Output = Flattened Tuple of outputs of sub-parsers.

313
template <typename... SubParsers> class Sequence_;
314

315 316
template <typename FirstSubParser, typename... SubParsers>
class Sequence_<FirstSubParser, SubParsers...> {
317 318
public:
  template <typename T, typename... U>
Kenton Varda's avatar
Kenton Varda committed
319
  explicit constexpr Sequence_(T&& firstSubParser, U&&... rest)
320 321
      : first(kj::fwd<T>(firstSubParser)), rest(kj::fwd<U>(rest)...) {}

322 323 324 325 326 327 328 329 330
  // TODO(msvc): The trailing return types on `operator()` and `parseNext()` expose at least two
  //   bugs in MSVC:
  //
  //     1. An ICE.
  //     2. 'error C2672: 'operator __surrogate_func': no matching overloaded function found)',
  //        which crops up in numerous places when trying to build the capnp command line tools.
  //
  //   The only workaround I found for both bugs is to omit the trailing return types and instead
  //   rely on C++14's return type deduction.
331

332
  template <typename Input>
333
  auto operator()(Input& input) const
334
#if !_MSC_VER || __clang__
335
      -> Maybe<decltype(tuple(
336
          instance<OutputType<FirstSubParser, Input>>(),
337 338 339
          instance<OutputType<SubParsers, Input>>()...))>
#endif
  {
340 341 342
    return parseNext(input);
  }

343
  template <typename Input, typename... InitialParams>
344
  auto parseNext(Input& input, InitialParams&&... initialParams) const
345
#if !_MSC_VER || __clang__
346
      -> Maybe<decltype(tuple(
347
          kj::fwd<InitialParams>(initialParams)...,
348
          instance<OutputType<FirstSubParser, Input>>(),
349 350 351
          instance<OutputType<SubParsers, Input>>()...))>
#endif
  {
352 353 354 355
    KJ_IF_MAYBE(firstResult, first(input)) {
      return rest.parseNext(input, kj::fwd<InitialParams>(initialParams)...,
                            kj::mv(*firstResult));
    } else {
356 357 358 359 360 361
      // TODO(msvc): MSVC depends on return type deduction to compile this function, so we need to
      //   help it deduce the right type on this code path.
      return Maybe<decltype(tuple(
          kj::fwd<InitialParams>(initialParams)...,
          instance<OutputType<FirstSubParser, Input>>(),
          instance<OutputType<SubParsers, Input>>()...))>{nullptr};
362 363 364 365 366
    }
  }

private:
  FirstSubParser first;
367
  Sequence_<SubParsers...> rest;
368 369
};

370 371
template <>
class Sequence_<> {
372
public:
373
  template <typename Input>
374
  Maybe<Tuple<>> operator()(Input& input) const {
375 376 377
    return parseNext(input);
  }

378
  template <typename Input, typename... Params>
379 380 381 382 383 384
  auto parseNext(Input& input, Params&&... params) const ->
      Maybe<decltype(tuple(kj::fwd<Params>(params)...))> {
    return tuple(kj::fwd<Params>(params)...);
  }
};

385
template <typename... SubParsers>
Kenton Varda's avatar
Kenton Varda committed
386
constexpr Sequence_<SubParsers...> sequence(SubParsers&&... subParsers) {
387 388
  // Constructs a parser that executes each of the parameter parsers in sequence and returns a
  // tuple of their results.
389

390 391
  return Sequence_<SubParsers...>(kj::fwd<SubParsers>(subParsers)...);
}
392 393

// -------------------------------------------------------------------
394
// many()
395
// Output = Array of output of sub-parser, or just a uint count if the sub-parser returns Tuple<>.
396 397

template <typename SubParser, bool atLeastOne>
398
class Many_ {
399 400
  template <typename Input, typename Output = OutputType<SubParser, Input>>
  struct Impl;
401
public:
Kenton Varda's avatar
Kenton Varda committed
402
  explicit constexpr Many_(SubParser&& subParser)
403
      : subParser(kj::fwd<SubParser>(subParser)) {}
404

405
  template <typename Input>
406 407 408 409 410 411 412 413 414 415 416
  auto operator()(Input& input) const
      -> decltype(Impl<Input>::apply(instance<const SubParser&>(), input));

private:
  SubParser subParser;
};

template <typename SubParser, bool atLeastOne>
template <typename Input, typename Output>
struct Many_<SubParser, atLeastOne>::Impl {
  static Maybe<Array<Output>> apply(const SubParser& subParser, Input& input) {
417
    typedef Vector<OutputType<SubParser, Input>> Results;
418 419 420
    Results results;

    while (!input.atEnd()) {
421
      Input subInput(input);
422 423 424 425 426 427 428 429 430 431 432 433 434

      KJ_IF_MAYBE(subResult, subParser(subInput)) {
        subInput.advanceParent();
        results.add(kj::mv(*subResult));
      } else {
        break;
      }
    }

    if (atLeastOne && results.empty()) {
      return nullptr;
    }

435
    return results.releaseAsArray();
436
  }
437
};
438

439 440 441
template <typename SubParser, bool atLeastOne>
template <typename Input>
struct Many_<SubParser, atLeastOne>::Impl<Input, Tuple<>> {
442 443
  // If the sub-parser output is Tuple<>, just return a count.

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  static Maybe<uint> apply(const SubParser& subParser, Input& input) {
    uint count = 0;

    while (!input.atEnd()) {
      Input subInput(input);

      KJ_IF_MAYBE(subResult, subParser(subInput)) {
        subInput.advanceParent();
        ++count;
      } else {
        break;
      }
    }

    if (atLeastOne && count == 0) {
      return nullptr;
    }

    return count;
  }
464 465
};

466 467 468 469 470 471 472
template <typename SubParser, bool atLeastOne>
template <typename Input>
auto Many_<SubParser, atLeastOne>::operator()(Input& input) const
    -> decltype(Impl<Input>::apply(instance<const SubParser&>(), input)) {
  return Impl<Input, OutputType<SubParser, Input>>::apply(subParser, input);
}

473
template <typename SubParser>
Kenton Varda's avatar
Kenton Varda committed
474
constexpr Many_<SubParser, false> many(SubParser&& subParser) {
475
  // Constructs a parser that repeatedly executes the given parser until it fails, returning an
476
  // Array of the results (or a uint count if `subParser` returns an empty tuple).
477
  return Many_<SubParser, false>(kj::fwd<SubParser>(subParser));
478 479 480
}

template <typename SubParser>
Kenton Varda's avatar
Kenton Varda committed
481
constexpr Many_<SubParser, true> oneOrMore(SubParser&& subParser) {
482 483
  // Like `many()` but the parser must parse at least one item to be successful.
  return Many_<SubParser, true>(kj::fwd<SubParser>(subParser));
484 485
}

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
// -------------------------------------------------------------------
// times()
// Output = Array of output of sub-parser, or Tuple<> if sub-parser returns Tuple<>.

template <typename SubParser>
class Times_ {
  template <typename Input, typename Output = OutputType<SubParser, Input>>
  struct Impl;
public:
  explicit constexpr Times_(SubParser&& subParser, uint count)
      : subParser(kj::fwd<SubParser>(subParser)), count(count) {}

  template <typename Input>
  auto operator()(Input& input) const
      -> decltype(Impl<Input>::apply(instance<const SubParser&>(), instance<uint>(), input));

private:
  SubParser subParser;
  uint count;
};

template <typename SubParser>
template <typename Input, typename Output>
struct Times_<SubParser>::Impl {
  static Maybe<Array<Output>> apply(const SubParser& subParser, uint count, Input& input) {
    auto results = heapArrayBuilder<OutputType<SubParser, Input>>(count);

    while (results.size() < count) {
      if (input.atEnd()) {
        return nullptr;
      } else KJ_IF_MAYBE(subResult, subParser(input)) {
        results.add(kj::mv(*subResult));
      } else {
        return nullptr;
      }
    }

    return results.finish();
  }
};

template <typename SubParser>
template <typename Input>
struct Times_<SubParser>::Impl<Input, Tuple<>> {
  // If the sub-parser output is Tuple<>, just return a count.

  static Maybe<Tuple<>> apply(const SubParser& subParser, uint count, Input& input) {
    uint actualCount = 0;

    while (actualCount < count) {
      if (input.atEnd()) {
        return nullptr;
      } else KJ_IF_MAYBE(subResult, subParser(input)) {
        ++actualCount;
      } else {
        return nullptr;
      }
    }

    return tuple();
  }
};

template <typename SubParser>
template <typename Input>
auto Times_<SubParser>::operator()(Input& input) const
    -> decltype(Impl<Input>::apply(instance<const SubParser&>(), instance<uint>(), input)) {
  return Impl<Input, OutputType<SubParser, Input>>::apply(subParser, count, input);
}

template <typename SubParser>
constexpr Times_<SubParser> times(SubParser&& subParser, uint count) {
  // Constructs a parser that repeats the subParser exactly `count` times.
  return Times_<SubParser>(kj::fwd<SubParser>(subParser), count);
}

562
// -------------------------------------------------------------------
563
// optional()
564 565 566
// Output = Maybe<output of sub-parser>

template <typename SubParser>
567
class Optional_ {
568
public:
Kenton Varda's avatar
Kenton Varda committed
569
  explicit constexpr Optional_(SubParser&& subParser)
570
      : subParser(kj::fwd<SubParser>(subParser)) {}
571

572 573 574
  template <typename Input>
  Maybe<Maybe<OutputType<SubParser, Input>>> operator()(Input& input) const {
    typedef Maybe<OutputType<SubParser, Input>> Result;
575

576 577
    Input subInput(input);
    KJ_IF_MAYBE(subResult, subParser(subInput)) {
578 579
      subInput.advanceParent();
      return Result(kj::mv(*subResult));
580 581
    } else {
      return Result(nullptr);
582 583 584 585 586 587 588 589
    }
  }

private:
  SubParser subParser;
};

template <typename SubParser>
Kenton Varda's avatar
Kenton Varda committed
590
constexpr Optional_<SubParser> optional(SubParser&& subParser) {
591 592 593
  // Constructs a parser that accepts zero or one of the given sub-parser, returning a Maybe
  // of the sub-parser's result.
  return Optional_<SubParser>(kj::fwd<SubParser>(subParser));
594 595 596
}

// -------------------------------------------------------------------
597
// oneOf()
598 599 600
// All SubParsers must have same output type, which becomes the output type of the
// OneOfParser.

601 602
template <typename... SubParsers>
class OneOf_;
603

604 605
template <typename FirstSubParser, typename... SubParsers>
class OneOf_<FirstSubParser, SubParsers...> {
606
public:
607 608
  explicit constexpr OneOf_(FirstSubParser&& firstSubParser, SubParsers&&... rest)
      : first(kj::fwd<FirstSubParser>(firstSubParser)), rest(kj::fwd<SubParsers>(rest)...) {}
609

610 611
  template <typename Input>
  Maybe<OutputType<FirstSubParser, Input>> operator()(Input& input) const {
612 613
    {
      Input subInput(input);
614
      Maybe<OutputType<FirstSubParser, Input>> firstResult = first(subInput);
615 616 617 618 619 620 621 622 623 624 625 626 627

      if (firstResult != nullptr) {
        subInput.advanceParent();
        return kj::mv(firstResult);
      }
    }

    // Hoping for some tail recursion here...
    return rest(input);
  }

private:
  FirstSubParser first;
628
  OneOf_<SubParsers...> rest;
629 630
};

631 632
template <>
class OneOf_<> {
633
public:
634 635
  template <typename Input>
  decltype(nullptr) operator()(Input& input) const {
636 637 638 639
    return nullptr;
  }
};

640
template <typename... SubParsers>
Kenton Varda's avatar
Kenton Varda committed
641
constexpr OneOf_<SubParsers...> oneOf(SubParsers&&... parsers) {
642 643 644 645
  // Constructs a parser that accepts one of a set of options.  The parser behaves as the first
  // sub-parser in the list which returns successfully.  All of the sub-parsers must return the
  // same type.
  return OneOf_<SubParsers...>(kj::fwd<SubParsers>(parsers)...);
646 647 648
}

// -------------------------------------------------------------------
649
// transform()
650 651 652 653 654 655
// Output = Result of applying transform functor to input value.  If input is a tuple, it is
// unpacked to form the transformation parameters.

template <typename Position>
struct Span {
public:
656 657
  inline const Position& begin() const { return begin_; }
  inline const Position& end() const { return end_; }
658 659

  Span() = default;
Kenton Varda's avatar
Kenton Varda committed
660
  inline constexpr Span(Position&& begin, Position&& end): begin_(mv(begin)), end_(mv(end)) {}
661 662 663 664 665 666

private:
  Position begin_;
  Position end_;
};

667
template <typename Position>
Kenton Varda's avatar
Kenton Varda committed
668
constexpr Span<Decay<Position>> span(Position&& start, Position&& end) {
669 670
  return Span<Decay<Position>>(kj::fwd<Position>(start), kj::fwd<Position>(end));
}
671

672 673 674
template <typename SubParser, typename TransformFunc>
class Transform_ {
public:
Kenton Varda's avatar
Kenton Varda committed
675
  explicit constexpr Transform_(SubParser&& subParser, TransformFunc&& transform)
676 677
      : subParser(kj::fwd<SubParser>(subParser)), transform(kj::fwd<TransformFunc>(transform)) {}

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
  template <typename Input>
  Maybe<decltype(kj::apply(instance<TransformFunc&>(),
                           instance<OutputType<SubParser, Input>&&>()))>
      operator()(Input& input) const {
    KJ_IF_MAYBE(subResult, subParser(input)) {
      return kj::apply(transform, kj::mv(*subResult));
    } else {
      return nullptr;
    }
  }

private:
  SubParser subParser;
  TransformFunc transform;
};

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
template <typename SubParser, typename TransformFunc>
class TransformOrReject_ {
public:
  explicit constexpr TransformOrReject_(SubParser&& subParser, TransformFunc&& transform)
      : subParser(kj::fwd<SubParser>(subParser)), transform(kj::fwd<TransformFunc>(transform)) {}

  template <typename Input>
  decltype(kj::apply(instance<TransformFunc&>(), instance<OutputType<SubParser, Input>&&>()))
      operator()(Input& input) const {
    KJ_IF_MAYBE(subResult, subParser(input)) {
      return kj::apply(transform, kj::mv(*subResult));
    } else {
      return nullptr;
    }
  }

private:
  SubParser subParser;
  TransformFunc transform;
};

715 716 717 718 719 720
template <typename SubParser, typename TransformFunc>
class TransformWithLocation_ {
public:
  explicit constexpr TransformWithLocation_(SubParser&& subParser, TransformFunc&& transform)
      : subParser(kj::fwd<SubParser>(subParser)), transform(kj::fwd<TransformFunc>(transform)) {}

721 722 723 724 725
  template <typename Input>
  Maybe<decltype(kj::apply(instance<TransformFunc&>(),
                           instance<Span<Decay<decltype(instance<Input&>().getPosition())>>>(),
                           instance<OutputType<SubParser, Input>&&>()))>
      operator()(Input& input) const {
726 727
    auto start = input.getPosition();
    KJ_IF_MAYBE(subResult, subParser(input)) {
728
      return kj::apply(transform, Span<decltype(start)>(kj::mv(start), input.getPosition()),
729
                       kj::mv(*subResult));
730 731 732 733 734 735 736
    } else {
      return nullptr;
    }
  }

private:
  SubParser subParser;
737
  TransformFunc transform;
738 739
};

740
template <typename SubParser, typename TransformFunc>
Kenton Varda's avatar
Kenton Varda committed
741 742
constexpr Transform_<SubParser, TransformFunc> transform(
    SubParser&& subParser, TransformFunc&& functor) {
743 744 745 746 747
  // Constructs a parser which executes some other parser and then transforms the result by invoking
  // `functor` on it.  Typically `functor` is a lambda.  It is invoked using `kj::apply`,
  // meaning tuples will be unpacked as arguments.
  return Transform_<SubParser, TransformFunc>(
      kj::fwd<SubParser>(subParser), kj::fwd<TransformFunc>(functor));
748 749
}

750 751 752 753 754 755 756 757 758
template <typename SubParser, typename TransformFunc>
constexpr TransformOrReject_<SubParser, TransformFunc> transformOrReject(
    SubParser&& subParser, TransformFunc&& functor) {
  // Like `transform()` except that `functor` returns a `Maybe`.  If it returns null, parsing fails,
  // otherwise the parser's result is the content of the `Maybe`.
  return TransformOrReject_<SubParser, TransformFunc>(
      kj::fwd<SubParser>(subParser), kj::fwd<TransformFunc>(functor));
}

759 760 761
template <typename SubParser, typename TransformFunc>
constexpr TransformWithLocation_<SubParser, TransformFunc> transformWithLocation(
    SubParser&& subParser, TransformFunc&& functor) {
762 763 764
  // Like `transform` except that `functor` also takes a `Span` as its first parameter specifying
  // the location of the parsed content.  The span's position type is whatever the parser input's
  // getPosition() returns.
765 766 767 768 769 770 771 772 773 774 775
  return TransformWithLocation_<SubParser, TransformFunc>(
      kj::fwd<SubParser>(subParser), kj::fwd<TransformFunc>(functor));
}

// -------------------------------------------------------------------
// notLookingAt()
// Fails if the given parser succeeds at the current location.

template <typename SubParser>
class NotLookingAt_ {
public:
776 777
  explicit constexpr NotLookingAt_(SubParser&& subParser)
      : subParser(kj::fwd<SubParser>(subParser)) {}
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

  template <typename Input>
  Maybe<Tuple<>> operator()(Input& input) const {
    Input subInput(input);
    subInput.forgetParent();
    if (subParser(subInput) == nullptr) {
      return Tuple<>();
    } else {
      return nullptr;
    }
  }

private:
  SubParser subParser;
};

template <typename SubParser>
constexpr NotLookingAt_<SubParser> notLookingAt(SubParser&& subParser) {
  // Constructs a parser which fails at any position where the given parser succeeds.  Otherwise,
  // it succeeds without consuming any input and returns an empty tuple.
  return NotLookingAt_<SubParser>(kj::fwd<SubParser>(subParser));
}

801
// -------------------------------------------------------------------
802
// endOfInput()
803
// Output = Tuple<>, only succeeds if at end-of-input
804

805
class EndOfInput_ {
806
public:
807
  template <typename Input>
808
  Maybe<Tuple<>> operator()(Input& input) const {
809
    if (input.atEnd()) {
810
      return Tuple<>();
811 812 813 814 815 816
    } else {
      return nullptr;
    }
  }
};

817 818
constexpr EndOfInput_ endOfInput = EndOfInput_();
// A parser that succeeds only if it is called with no input.
819 820 821

}  // namespace parse
}  // namespace kj