compatibility_tokens.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. if (!\function_exists('PhpParser\defineCompatibilityTokens')) {
  4. function defineCompatibilityTokens(): void {
  5. $compatTokens = [
  6. // PHP 8.0
  7. 'T_NAME_QUALIFIED',
  8. 'T_NAME_FULLY_QUALIFIED',
  9. 'T_NAME_RELATIVE',
  10. 'T_MATCH',
  11. 'T_NULLSAFE_OBJECT_OPERATOR',
  12. 'T_ATTRIBUTE',
  13. // PHP 8.1
  14. 'T_ENUM',
  15. 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG',
  16. 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG',
  17. 'T_READONLY',
  18. ];
  19. // PHP-Parser might be used together with another library that also emulates some or all
  20. // of these tokens. Perform a sanity-check that all already defined tokens have been
  21. // assigned a unique ID.
  22. $usedTokenIds = [];
  23. foreach ($compatTokens as $token) {
  24. if (\defined($token)) {
  25. $tokenId = \constant($token);
  26. $clashingToken = $usedTokenIds[$tokenId] ?? null;
  27. if ($clashingToken !== null) {
  28. throw new \Error(sprintf(
  29. 'Token %s has same ID as token %s, ' .
  30. 'you may be using a library with broken token emulation',
  31. $token, $clashingToken
  32. ));
  33. }
  34. $usedTokenIds[$tokenId] = $token;
  35. }
  36. }
  37. // Now define any tokens that have not yet been emulated. Try to assign IDs from -1
  38. // downwards, but skip any IDs that may already be in use.
  39. $newTokenId = -1;
  40. foreach ($compatTokens as $token) {
  41. if (!\defined($token)) {
  42. while (isset($usedTokenIds[$newTokenId])) {
  43. $newTokenId--;
  44. }
  45. \define($token, $newTokenId);
  46. $newTokenId--;
  47. }
  48. }
  49. }
  50. defineCompatibilityTokens();
  51. }