compatibility_tokens.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // PHP 8.4
  19. 'T_PROPERTY_C',
  20. 'T_PUBLIC_SET',
  21. 'T_PROTECTED_SET',
  22. 'T_PRIVATE_SET',
  23. ];
  24. // PHP-Parser might be used together with another library that also emulates some or all
  25. // of these tokens. Perform a sanity-check that all already defined tokens have been
  26. // assigned a unique ID.
  27. $usedTokenIds = [];
  28. foreach ($compatTokens as $token) {
  29. if (\defined($token)) {
  30. $tokenId = \constant($token);
  31. if (!\is_int($tokenId)) {
  32. throw new \Error(sprintf(
  33. 'Token %s has ID of type %s, should be int. ' .
  34. 'You may be using a library with broken token emulation',
  35. $token, \gettype($tokenId)
  36. ));
  37. }
  38. $clashingToken = $usedTokenIds[$tokenId] ?? null;
  39. if ($clashingToken !== null) {
  40. throw new \Error(sprintf(
  41. 'Token %s has same ID as token %s, ' .
  42. 'you may be using a library with broken token emulation',
  43. $token, $clashingToken
  44. ));
  45. }
  46. $usedTokenIds[$tokenId] = $token;
  47. }
  48. }
  49. // Now define any tokens that have not yet been emulated. Try to assign IDs from -1
  50. // downwards, but skip any IDs that may already be in use.
  51. $newTokenId = -1;
  52. foreach ($compatTokens as $token) {
  53. if (!\defined($token)) {
  54. while (isset($usedTokenIds[$newTokenId])) {
  55. $newTokenId--;
  56. }
  57. \define($token, $newTokenId);
  58. $newTokenId--;
  59. }
  60. }
  61. }
  62. defineCompatibilityTokens();
  63. }