1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vanderlee\Comprehend\Parser\Structure; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
use Vanderlee\Comprehend\Core\Context; |
7
|
|
|
use Vanderlee\Comprehend\Match\Success; |
8
|
|
|
use Vanderlee\Comprehend\Parser\Parser; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Description of SequenceParser. |
12
|
|
|
* |
13
|
|
|
* @author Martijn |
14
|
|
|
*/ |
15
|
|
|
class Sequence extends IterableParser |
16
|
|
|
{ |
17
|
|
|
use SpacingTrait; |
18
|
|
|
|
19
|
43 |
|
public function __construct(...$arguments) |
20
|
|
|
{ |
21
|
43 |
|
if (empty($arguments)) { |
22
|
1 |
|
throw new InvalidArgumentException('No arguments'); |
23
|
|
|
} |
24
|
|
|
|
25
|
42 |
|
$this->parsers = self::getArguments($arguments, false); |
26
|
42 |
|
} |
27
|
|
|
|
28
|
142 |
|
protected function parse(&$input, $offset, Context $context) |
29
|
|
|
{ |
30
|
142 |
|
$childMatches = []; |
31
|
|
|
|
32
|
142 |
|
$this->pushSpacer($context); |
33
|
|
|
|
34
|
142 |
|
$total = 0; |
35
|
|
|
/** @var Parser $parser */ |
36
|
142 |
|
foreach ($this->parsers as $parser) { |
37
|
142 |
|
if ($total > 0) { |
38
|
129 |
|
$skip = $context->skipSpacing($input, $offset + $total); |
39
|
129 |
|
if ($skip === false) { |
40
|
2 |
|
return $this->failure($input, $offset, $total); |
41
|
|
|
} |
42
|
128 |
|
$total += $skip; |
43
|
|
|
} |
44
|
142 |
|
$match = $parser->parse($input, $offset + $total, $context); |
45
|
142 |
|
$total += $match->length; |
46
|
|
|
|
47
|
142 |
|
if (!($match instanceof Success)) { // must match |
48
|
82 |
|
$this->popSpacer($context); |
49
|
|
|
|
50
|
82 |
|
return $this->failure($input, $offset, $total); |
51
|
|
|
} |
52
|
|
|
|
53
|
135 |
|
$childMatches[] = $match; |
54
|
|
|
} |
55
|
|
|
|
56
|
113 |
|
$this->popSpacer($context); |
57
|
|
|
|
58
|
113 |
|
return $this->success($input, $offset, $total, $childMatches); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Add one or more parsers to the end of this sequence. |
63
|
|
|
* |
64
|
|
|
* @param string[]|int[]|Parser[] $arguments |
65
|
|
|
* |
66
|
|
|
* @return $this |
67
|
|
|
*/ |
68
|
1 |
|
public function add(...$arguments) |
69
|
|
|
{ |
70
|
1 |
|
$this->parsers = array_merge($this->parsers, self::getArguments($arguments)); |
71
|
|
|
|
72
|
1 |
|
return $this; |
73
|
|
|
} |
74
|
|
|
|
75
|
94 |
|
public function __toString() |
76
|
|
|
{ |
77
|
94 |
|
return '( ' . implode(' ', $this->parsers) . ' )'; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|