Forbid invalid octals in PHP 7 mode

This commit is contained in:
Nikita Popov 2016-04-18 13:59:18 +02:00
parent 4c7ad7e194
commit e7869b9f14
5 changed files with 28 additions and 9 deletions

View File

@ -740,7 +740,7 @@ ctor_arguments:
;
common_scalar:
T_LNUMBER { $$ = Scalar\LNumber::fromString($1, attributes()); }
T_LNUMBER { $$ = Scalar\LNumber::fromString($1, attributes(), true); }
| T_DNUMBER { $$ = Scalar\DNumber[Scalar\DNumber::parse($1)]; }
| T_CONSTANT_ENCAPSED_STRING
{ $attrs = attributes(); $attrs['kind'] = strKind($1);

View File

@ -2,6 +2,7 @@
namespace PhpParser\Node\Scalar;
use PhpParser\Error;
use PhpParser\Node\Scalar;
class LNumber extends Scalar
@ -33,12 +34,13 @@ class LNumber extends Scalar
/**
* Constructs an LNumber node from a string number literal.
*
* @param string $str String number literal (decimal, octal, hex or binary)
* @param array $attributes Additional attributes
* @param string $str String number literal (decimal, octal, hex or binary)
* @param array $attributes Additional attributes
* @param bool $allowInvalidOctal Whether to allow invalid octal numbers (PHP 5)
*
* @return LNumber The constructed LNumber, including kind attribute
*/
public static function fromString($str, array $attributes = array()) {
public static function fromString($str, array $attributes = array(), $allowInvalidOctal = false) {
if ('0' !== $str[0] || '0' === $str) {
$attributes['kind'] = LNumber::KIND_DEC;
return new LNumber((int) $str, $attributes);
@ -54,6 +56,10 @@ class LNumber extends Scalar
return new LNumber(bindec($str), $attributes);
}
if (!$allowInvalidOctal && strpbrk($str, '89')) {
throw new Error('Invalid numeric literal', $attributes);
}
// use intval instead of octdec to get proper cutting behavior with malformed numbers
$attributes['kind'] = LNumber::KIND_OCT;
return new LNumber(intval($str, 8), $attributes);

View File

@ -2604,7 +2604,7 @@ class Php5 extends \PhpParser\ParserAbstract
}
protected function reduceRule419() {
$this->semValue = Scalar\LNumber::fromString($this->semStack[$this->stackPos-(1-1)], $this->startAttributeStack[$this->stackPos-(1-1)] + $this->endAttributes);
$this->semValue = Scalar\LNumber::fromString($this->semStack[$this->stackPos-(1-1)], $this->startAttributeStack[$this->stackPos-(1-1)] + $this->endAttributes, true);
}
protected function reduceRule420() {

View File

@ -10,7 +10,6 @@ Different integer syntaxes
0xfff;
0XfFf;
0777;
0787;
0b111000111000;
-----
array(
@ -39,9 +38,6 @@ array(
value: 511
)
8: Scalar_LNumber(
value: 7
)
9: Scalar_LNumber(
value: 3640
)
)

View File

@ -0,0 +1,17 @@
Invalid octal literals
-----
<?php
0787;
-----
!!php7
Invalid numeric literal from 2:1 to 2:4
-----
<?php
0787;
-----
!!php5
array(
0: Scalar_LNumber(
value: 7
)
)