Passed
Push — master ( 52423a...23b91d )
by Koen
03:18
created

Parser::parseTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
ccs 9
cts 9
cp 1
rs 9.4285
nc 1
cc 1
eloc 7
nop 0
crap 1
1
<?php
2
3
namespace Vlaswinkel\Lua;
4
5
use Vlaswinkel\Lua\AST\ASTNode;
6
use Vlaswinkel\Lua\AST\NilASTNode;
7
use Vlaswinkel\Lua\AST\NumberASTNode;
8
use Vlaswinkel\Lua\AST\StringASTNode;
9
use Vlaswinkel\Lua\AST\TableASTNode;
10
use Vlaswinkel\Lua\AST\TableEntryASTNode;
11
12
/**
13
 * Class Parser
14
 *
15
 * @see     http://lisperator.net/pltut/parser/the-parser
16
 *
17
 * @author  Koen Vlaswinkel <[email protected]>
18
 * @package Vlaswinkel\Lua
19
 */
20
class Parser {
21
    /**
22
     * @var TokenStream
23
     */
24
    private $input;
25
26
    /**
27
     * Parser constructor.
28
     *
29
     * @param TokenStream $input
30
     */
31 23
    public function __construct(TokenStream $input) {
32 23
        $this->input = $input;
33 23
    }
34
35
    /**
36
     * @return ASTNode
37
     *
38
     * @throws ParseException
39
     */
40 23
    public function parse() {
41 23
        $result = $this->parseInternal();
42
43 21
        if (!$this->input->eof()) {
44 2
            if ($result instanceof StringASTNode && $this->isPunctuation('=')) {
45 2
                $this->skipPunctuation('=');
46 2
                $value = $this->parseInternal();
47
48 2
                return new TableASTNode([new TableEntryASTNode($value, $result)]);
0 ignored issues
show
Bug introduced by
It seems like $value defined by $this->parseInternal() on line 46 can be null; however, Vlaswinkel\Lua\AST\Table...yASTNode::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
49
            }
50
            
51
            $this->input->error('Parser has finished parsing, but end of file was not reached. Next character is ' . $this->input->peek()->getValue());
52
        }
53
54 19
        return $result;
55
    }
56
57
    /**
58
     * @return ASTNode
59
     *
60
     * @throws ParseException
61
     */
62 23
    protected function parseInternal() {
63 23
        if ($this->isPunctuation('{')) {
64 12
            return $this->parseTable();
65
        }
66 22
        if ($this->isPunctuation('[')) {
67 4
            return $this->parseTableKey();
68
        }
69 22
        $token = $this->input->next();
70 22
        if ($token->getType() == Token::TYPE_NUMBER) {
71 8
            return new NumberASTNode($token->getValue());
72
        }
73 20
        if ($token->getType() == Token::TYPE_STRING || $token->getType() == Token::TYPE_IDENTIFIER) {
74 17
            return new StringASTNode($token->getValue());
75
        }
76 5
        if ($token->getType() == Token::TYPE_KEYWORD) {
77 5
            if ($token->getValue() === 'nil') {
78 4
                return new NilASTNode();
79
            } else {
80 1
                $this->input->error('Unexpected keyword: ' . $token->getValue());
81
            }
82
        }
83
        $this->unexpected();
84
    }
85
86
    /**
87
     * @return TableASTNode
88
     */
89 12
    protected function parseTable() {
90 12
        return new TableASTNode(
91 12
            $this->delimited(
92 12
                '{',
93 12
                '}',
94 12
                ',',
95 12
                [$this, 'parseTableEntry']
96 12
            )
97 11
        );
98
    }
99
100
    /**
101
     * @return TableEntryASTNode
102
     */
103 11
    protected function parseTableEntry() {
104 11
        $token = $this->parseInternal();
105 11
        if ($this->isPunctuation('=')) {
106 10
            $this->skipPunctuation('=');
107 10
            $value = $this->parseInternal();
108 10
            return new TableEntryASTNode(
109 10
                $value,
0 ignored issues
show
Bug introduced by
It seems like $value defined by $this->parseInternal() on line 107 can be null; however, Vlaswinkel\Lua\AST\Table...yASTNode::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
110
                $token
111 10
            );
112
        }
113 5
        return new TableEntryASTNode($token);
0 ignored issues
show
Bug introduced by
It seems like $token defined by $this->parseInternal() on line 104 can be null; however, Vlaswinkel\Lua\AST\Table...yASTNode::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
114
    }
115
116
    /**
117
     * @return ASTNode
0 ignored issues
show
Documentation introduced by
Should the return type not be ASTNode|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
118
     */
119 4
    protected function parseTableKey() {
120 4
        $this->skipPunctuation('[');
121 4
        $token = $this->parseInternal();
122 4
        $this->skipPunctuation(']');
123 4
        return $token;
124
    }
125
126
    /**
127
     * @param string   $start
128
     * @param string   $stop
129
     * @param string   $separator
130
     * @param callable $parser
131
     *
132
     * @return array
133
     */
134 12
    protected function delimited($start, $stop, $separator, callable $parser) {
135 12
        $a     = [];
136 12
        $first = true;
137 12
        $this->skipPunctuation($start);
138 12
        while (!$this->input->eof()) {
139 12
            if ($this->isPunctuation($stop)) {
140 11
                break;
141
            }
142 11
            if ($first) {
143 11
                $first = false;
144 11
            } else {
145 4
                $this->skipPunctuation($separator);
146
            }
147 11
            if ($this->isPunctuation($stop)) {
148 2
                break;
149
            }
150 11
            $a[] = $parser();
151 11
        }
152 11
        $this->skipPunctuation($stop);
153 11
        return $a;
154
    }
155
156
    /**
157
     * @param string|null $char
158
     *
159
     * @return bool
160
     */
161 23
    protected function isPunctuation($char = null) {
162 23
        $token = $this->input->peek();
163 23
        return $token && $token->getType() == Token::TYPE_PUNCTUATION && ($char === null || $token->getValue(
164 23
            ) == $char);
165
    }
166
167
    /**
168
     * @param string|null $char
169
     *
170
     * @throws ParseException
171
     */
172 13
    protected function skipPunctuation($char = null) {
173 13
        if ($this->isPunctuation($char)) {
174 13
            $this->input->next();
175 13
        } else {
176 1
            $this->input->error('Expecting punctuation: "' . $char . '"');
177
        }
178 13
    }
179
180
    /**
181
     * @throws ParseException
182
     */
183
    protected function unexpected() {
184
        $this->input->error('Unexpected token: ' . json_encode($this->input->peek()));
185
    }
186
}