1: <?php
2: // Parco
3: // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
4: // Licensed under the MIT license.
5: // See the LICENSE file or http://opensource.org/licenses/MIT for more information.
6: namespace Parco\Combinator;
7:
8: use Parco\Parser;
9:
10: /**
11: * An extension of {@see Parsers} for parsing arrays of
12: * {@see Parco\Positional}s, e.g. an array of tokens.
13: */
14: trait PositionalParsers
15: {
16: use Parsers;
17:
18: /**
19: * {@inheritdoc}
20: */
21: protected function atEnd($input)
22: {
23: return count($input) == 0;
24: }
25:
26: /**
27: * {@inheritdoc}
28: */
29: protected function head($input)
30: {
31: return $input[0];
32: }
33:
34: /**
35: * {@inheritdoc}
36: */
37: protected function tail($input, array $pos)
38: {
39: $head = $input[0];
40: $tail = array_slice($input, 1);
41: if (isset($tail[0])) {
42: $pos = $tail[0]->getPosition();
43: } else {
44: $pos = array(-1, -1);
45: }
46: return array($tail, $pos);
47: }
48:
49: /**
50: * {@inheritdoc}
51: */
52: protected function show($element)
53: {
54: if (method_exists($element, '__toString')) {
55: return $element->__toString();
56: }
57: return get_class($element);
58: }
59:
60: /**
61: * Use a parser to parse an input sequence.
62: *
63: * @param Parser $p
64: * A parser.
65: * @param Positional[] $input
66: * An input sequence.
67: * @return \Parco\Result Parse result.
68: */
69: public function parse(Parser $p, array $input)
70: {
71: if ($this->atEnd($input)) {
72: $pos = array(1, 1);
73: } else {
74: $pos = $this->head($input)->getPosition();
75: }
76: return $p->parse($input, $pos);
77: }
78:
79: /**
80: * Use a parser to parse an input sequence. The entire sequence must be
81: * consumed by the parser.
82: *
83: * `parseAll($p)` is the same as `parse(phrase($p))`.
84: *
85: * @param Parser $p
86: * A parser.
87: * @param Positional[] $input
88: * An input sequence.
89: * @return \Parco\Result Parse result.
90: */
91: public function parseAll(Parser $p, array $input)
92: {
93: return $this->parse($this->phrase($p), $input);
94: }
95: }
96: