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