Skip to content

PHP 8.5: Recursive tokenization during token_get_all result on error #19507

Closed

Description

@gharlan

Description

The following code:

a.php:

<?php

set_error_handler(function (int $errno, string $msg) {
    require __DIR__.'/b.php';
    echo 'error handler called: ', $msg;
});

$code = '<?php (double) $x;';
$tokens = token_get_all($code, \TOKEN_PARSE);

echo "\n\n";
foreach ($tokens as $token) {
    if (is_string($token)) {
        echo $token, "\n";
    } else {
        echo token_name($token[0]) . ' "' . $token[1], "\"\n";
    }
}

b.php:

<?php 1;

Calling php a.php resulted in this output:

error handler called: Non-canonical cast (double) is deprecated, use the (float) cast instead

T_OPEN_TAG "<?php "
T_OPEN_TAG "<?php "
T_LNUMBER "1"
;
T_WHITESPACE "
"
T_DOUBLE_CAST "(double)"
T_WHITESPACE " "
T_VARIABLE "$x"
;

But I expected this output instead:

error handler called: Non-canonical cast (double) is deprecated, use the (float) cast instead

T_OPEN_TAG "<?php "
T_DOUBLE_CAST "(double)"
T_WHITESPACE " "
T_VARIABLE "$x"
;

Not sure about the error handler call. Is it intended that the error handler is called for deprecations inside the code given to token_get_all?
But at least I do not expect to get the tokens of b.php inside the tokens of the code given to token_get_all.

PHP Version

PHP 8.5.0-dev (cli) (built: Aug 16 2025 23:33:23) (NTS)
Copyright (c) The PHP Group
Built by Shivam Mathur
Zend Engine v4.5.0-dev, Copyright (c) Zend Technologies
    with Zend OPcache v8.5.0-dev, Copyright (c), by Zend Technologies

Operating System

macOS

Activity

  1. devnexen commented on Aug 17, 2025

    @devnexen
    Member

    verified on master, not happening on 8.4.x

  2. devnexen commented on Aug 17, 2025

    @devnexen
    Member

    @nielsdos do you think it is more a change in the engine ? Do not think it comes from the tokenizer extension.

  3. mvorisek commented on Aug 17, 2025

    @mvorisek
    Contributor
  4. DanielEScherzer commented on Aug 17, 2025

    @DanielEScherzer
    Member

    Probably caused by the deprecations coming from within zend_language_scanner.l rather than during compilation, e.g.

    <ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("integer"){TABS_AND_SPACES}")" {
    if (PARSER_MODE()) {
    zend_error(E_DEPRECATED, "Non-canonical cast (integer) is deprecated, use the (int) cast instead");
    }
    RETURN_TOKEN(T_INT_CAST);
    }

    CC @Girgias

  5. added this to the PHP 8.5 milestone on Aug 17, 2025
  6. hakre commented on Aug 18, 2025

    @hakre
    Contributor

    IIRC tokenization was error free for a long time. if it now emits, the diagnostic messages should probably be collected and optionally be available, e.g. an out parameter on token_get_all().

    That the previous(?) token is returned looks worry-some to me, too, collecting instead of immediate emission may solve that, too.

  7. keradus commented on Aug 18, 2025

    @keradus

    if it now emits, the diagnostic messages should probably be collected and optionally be available, e.g. an out parameter on token_get_all().

    I do not think this case should trigger any error in first place. if code is valid but deprecated, tokenizer should work as-is (same output as under 8.4)

  8. TimWolla commented on Aug 18, 2025

    @TimWolla
    Member

    The only other non-fatal in the scanner is a E_COMPILE_WARNING. See also: #18510.

  9. hakre commented on Aug 18, 2025

    @hakre
    Contributor

    if it now emits, the diagnostic messages should probably be collected and optionally be available, e.g. an out parameter on token_get_all().

    I do not think this case should trigger any error in first place. if code is valid but deprecated, tokenizer should work as-is (same output as under 8.4)

    Yes, triggering an error is a side-effect of emitting the diagnostic message, I'd like to keep it free from emitting those, that is what I meant by "error free" (not the type but the event itself), also as @TimWolla has pointed out we're not there yet:

    The only other non-fatal in the scanner is a E_COMPILE_WARNING. See also: #18510.

    So now I have to look how close we are... .

  10. arnaud-lb commented on Aug 18, 2025

    @arnaud-lb
    Member

    A possible fix would be to delay + record these errors, and emit them after tokenization, with zend_begin_record_errors() / zend_emit_recorded_errors(). Of course we need to handle cases where errors are already being recorded.

  11. ndossche commented on Aug 19, 2025

    @ndossche
    Member

    Yeah this happens because the "event" callback is a global for the scanner (LANG_SCNG(on_event)). So when a new file gets compiled during tokenization you also receive the events from that compilation pipeline.
    So we could also save+restore the old value of that global prior to invoking the compiler.
    I would prefer a solution that's solely changing ext-tokenizer though.

  12. hakre commented on Aug 20, 2025

    @hakre
    Contributor

    @nielsdos I have seen when zend_error_cb calls the user error handler callback, something is done there as well with some globals(?) and related to execution/compiling context. couldn't it be, that it falls short there as that mechanism is probably older than the tokenizer extension?

    /* User error handler may include() additional PHP files.
    * If an error was generated during compilation PHP will compile
    * such scripts recursively, but some CG() variables may be
    * inconsistent. */

  13. ndossche commented on Aug 20, 2025

    @ndossche
    Member

    Backing up and restoring the scanner event handler makes sense, I'll try it

  14. changed the title [-]PHP 8.5: Strange `token_get_all` result[/-] [+]PHP 8.5: Recursive `token_get_all` result on error[/+] on Aug 20, 2025
  15. ndossche commented on Aug 20, 2025

    @ndossche
    Member

    Oh it's even better in debug mode where it breaks an engine assumption:
    php: /run/media/niels/MoreData/php-src/Zend/zend_compile.c:2038: zendlex: Assertion `!(executor_globals.exception) || ret == T_ERROR' failed.

    Doesn't look fun, because that mean that an error handler that throws is also problematic for example.
    Simplest solution is to undeprecate these things ;)
    Anyway, I decided not to care about this issue.

  16. changed the title [-]PHP 8.5: Recursive `token_get_all` result on error[/-] [+]PHP 8.5: Recursive tokenization during `token_get_all` result on error[/+] on Aug 20, 2025
  17. arnaud-lb commented on Aug 21, 2025

    @arnaud-lb
    Member

    Turns out we do save/restore the lexer state (including on_event) everywhere we use lex_scan() / zendlex(), but on_event is not reset, so nested calls inherit the parent on_event.

    Resetting it fixes the issue:

    diff --git a/Zend/zend_language_scanner.l b/Zend/zend_language_scanner.l
    index d298ae8b9ea..5400df4a25f 100644
    --- a/Zend/zend_language_scanner.l
    +++ b/Zend/zend_language_scanner.l
    @@ -210,6 +210,7 @@ void shutdown_scanner(void)
     	zend_ptr_stack_destroy(&SCNG(heredoc_label_stack));
     	SCNG(heredoc_scan_ahead) = 0;
     	SCNG(on_event) = NULL;
    +	SCNG(on_event_context) = NULL;
     }
     
     ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state)
    @@ -581,6 +582,8 @@ ZEND_API zend_result open_file_for_scanning(zend_file_handle *file_handle)
     	zend_set_compiled_filename(compiled_filename);
     	zend_string_release_ex(compiled_filename, 0);
     
    +	SCNG(on_event) = NULL;
    +	SCNG(on_event_context) = NULL;
     	RESET_DOC_COMMENT();
     	CG(zend_lineno) = 1;
     	CG(increment_lineno) = 0;
    @@ -766,6 +769,8 @@ ZEND_API void zend_prepare_string_for_scanning(zval *str, zend_string *filename)
     	zend_set_compiled_filename(filename);
     	CG(zend_lineno) = 1;
     	CG(increment_lineno) = 0;
    +	SCNG(on_event) = NULL;
    +	SCNG(on_event_context) = NULL;
     	RESET_DOC_COMMENT();
     }
     

    Regarding exceptions: Returning T_ERROR if EG(exception) is set after calling zend_error() would safely allow exceptions to be thrown from error handlers:

    @@ -1636,6 +1646,9 @@ OPTIONAL_WHITESPACE_OR_COMMENTS ({WHITESPACE}|{MULTI_LINE_COMMENT}|{SINGLE_LINE_
     <ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("integer"){TABS_AND_SPACES}")" {
     	if (PARSER_MODE()) {
     		zend_error(E_DEPRECATED, "Non-canonical cast (integer) is deprecated, use the (int) cast instead");
    +		if (PARSER_MODE() && EG(exception)) {
    +			RETURN_TOKEN(T_ERROR);
    +		}
     	}
     	RETURN_TOKEN(T_INT_CAST);
     }
    @@ -1647,6 +1660,9 @@ OPTIONAL_WHITESPACE_OR_COMMENTS ({WHITESPACE}|{MULTI_LINE_COMMENT}|{SINGLE_LINE_
     <ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("double"){TABS_AND_SPACES}")" {
     	if (PARSER_MODE()) {
     		zend_error(E_DEPRECATED, "Non-canonical cast (double) is deprecated, use the (float) cast instead");
    +		if (PARSER_MODE() && EG(exception)) {
    +			RETURN_TOKEN(T_ERROR);
    +		}
     	}
     	RETURN_TOKEN(T_DOUBLE_CAST);
     }
    @@ -1666,6 +1682,9 @@ OPTIONAL_WHITESPACE_OR_COMMENTS ({WHITESPACE}|{MULTI_LINE_COMMENT}|{SINGLE_LINE_
     <ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("binary"){TABS_AND_SPACES}")" {
     	if (PARSER_MODE()) {
     		zend_error(E_DEPRECATED, "Non-canonical cast (binary) is deprecated, use the (string) cast instead");
    +		if (PARSER_MODE() && EG(exception)) {
    +			RETURN_TOKEN(T_ERROR);
    +		}
     	}
     	RETURN_TOKEN(T_STRING_CAST);
     }
    @@ -1685,6 +1704,9 @@ OPTIONAL_WHITESPACE_OR_COMMENTS ({WHITESPACE}|{MULTI_LINE_COMMENT}|{SINGLE_LINE_
     <ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("boolean"){TABS_AND_SPACES}")" {
     	if (PARSER_MODE()) {
     		zend_error(E_DEPRECATED, "Non-canonical cast (boolean) is deprecated, use the (bool) cast instead");
    +		if (PARSER_MODE() && EG(exception)) {
    +			RETURN_TOKEN(T_ERROR);
    +		}
     	}
     	RETURN_TOKEN(T_BOOL_CAST);
     }
  18. arnaud-lb commented on Aug 22, 2025

    @arnaud-lb
    Member

    Thank you @gharlan!

  19. added a commit that references this issue on Aug 22, 2025
    94d0b41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions