compatibility_tokens.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. if (!\is_int($tokenId)) {
  27. throw new \Error(sprintf(
  28. 'Token %s has ID of type %s, should be int. ' .
  29. 'You may be using a library with broken token emulation',
  30. $token, \gettype($tokenId)
  31. ));
  32. }
  33. $clashingToken = $usedTokenIds[$tokenId] ?? null;
  34. if ($clashingToken !== null) {
  35. throw new \Error(sprintf(
  36. 'Token %s has same ID as token %s, ' .
  37. 'you may be using a library with broken token emulation',
  38. $token, $clashingToken
  39. ));
  40. }
  41. $usedTokenIds[$tokenId] = $token;
  42. }
  43. }
  44. // Now define any tokens that have not yet been emulated. Try to assign IDs from -1
  45. // downwards, but skip any IDs that may already be in use.
  46. $newTokenId = -1;
  47. foreach ($compatTokens as $token) {
  48. if (!\defined($token)) {
  49. while (isset($usedTokenIds[$newTokenId])) {
  50. $newTokenId--;
  51. }
  52. \define($token, $newTokenId);
  53. $newTokenId--;
  54. }
  55. }
  56. }
  57. defineCompatibilityTokens();
  58. }