No Description

NameContext.php 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\Node\Name;
  4. use PhpParser\Node\Name\FullyQualified;
  5. use PhpParser\Node\Stmt;
  6. class NameContext
  7. {
  8. /** @var null|Name Current namespace */
  9. protected $namespace;
  10. /** @var Name[][] Map of format [aliasType => [aliasName => originalName]] */
  11. protected $aliases = [];
  12. /** @var Name[][] Same as $aliases but preserving original case */
  13. protected $origAliases = [];
  14. /** @var ErrorHandler Error handler */
  15. protected $errorHandler;
  16. /**
  17. * Create a name context.
  18. *
  19. * @param ErrorHandler $errorHandler Error handling used to report errors
  20. */
  21. public function __construct(ErrorHandler $errorHandler) {
  22. $this->errorHandler = $errorHandler;
  23. }
  24. /**
  25. * Start a new namespace.
  26. *
  27. * This also resets the alias table.
  28. *
  29. * @param Name|null $namespace Null is the global namespace
  30. */
  31. public function startNamespace(Name $namespace = null) {
  32. $this->namespace = $namespace;
  33. $this->origAliases = $this->aliases = [
  34. Stmt\Use_::TYPE_NORMAL => [],
  35. Stmt\Use_::TYPE_FUNCTION => [],
  36. Stmt\Use_::TYPE_CONSTANT => [],
  37. ];
  38. }
  39. /**
  40. * Add an alias / import.
  41. *
  42. * @param Name $name Original name
  43. * @param string $aliasName Aliased name
  44. * @param int $type One of Stmt\Use_::TYPE_*
  45. * @param array $errorAttrs Attributes to use to report an error
  46. */
  47. public function addAlias(Name $name, string $aliasName, int $type, array $errorAttrs = []) {
  48. // Constant names are case sensitive, everything else case insensitive
  49. if ($type === Stmt\Use_::TYPE_CONSTANT) {
  50. $aliasLookupName = $aliasName;
  51. } else {
  52. $aliasLookupName = strtolower($aliasName);
  53. }
  54. if (isset($this->aliases[$type][$aliasLookupName])) {
  55. $typeStringMap = [
  56. Stmt\Use_::TYPE_NORMAL => '',
  57. Stmt\Use_::TYPE_FUNCTION => 'function ',
  58. Stmt\Use_::TYPE_CONSTANT => 'const ',
  59. ];
  60. $this->errorHandler->handleError(new Error(
  61. sprintf(
  62. 'Cannot use %s%s as %s because the name is already in use',
  63. $typeStringMap[$type], $name, $aliasName
  64. ),
  65. $errorAttrs
  66. ));
  67. return;
  68. }
  69. $this->aliases[$type][$aliasLookupName] = $name;
  70. $this->origAliases[$type][$aliasName] = $name;
  71. }
  72. /**
  73. * Get current namespace.
  74. *
  75. * @return null|Name Namespace (or null if global namespace)
  76. */
  77. public function getNamespace() {
  78. return $this->namespace;
  79. }
  80. /**
  81. * Get resolved name.
  82. *
  83. * @param Name $name Name to resolve
  84. * @param int $type One of Stmt\Use_::TYPE_{FUNCTION|CONSTANT}
  85. *
  86. * @return null|Name Resolved name, or null if static resolution is not possible
  87. */
  88. public function getResolvedName(Name $name, int $type) {
  89. // don't resolve special class names
  90. if ($type === Stmt\Use_::TYPE_NORMAL && $name->isSpecialClassName()) {
  91. if (!$name->isUnqualified()) {
  92. $this->errorHandler->handleError(new Error(
  93. sprintf("'\\%s' is an invalid class name", $name->toString()),
  94. $name->getAttributes()
  95. ));
  96. }
  97. return $name;
  98. }
  99. // fully qualified names are already resolved
  100. if ($name->isFullyQualified()) {
  101. return $name;
  102. }
  103. // Try to resolve aliases
  104. if (null !== $resolvedName = $this->resolveAlias($name, $type)) {
  105. return $resolvedName;
  106. }
  107. if ($type !== Stmt\Use_::TYPE_NORMAL && $name->isUnqualified()) {
  108. if (null === $this->namespace) {
  109. // outside of a namespace unaliased unqualified is same as fully qualified
  110. return new FullyQualified($name, $name->getAttributes());
  111. }
  112. // Cannot resolve statically
  113. return null;
  114. }
  115. // if no alias exists prepend current namespace
  116. return FullyQualified::concat($this->namespace, $name, $name->getAttributes());
  117. }
  118. /**
  119. * Get resolved class name.
  120. *
  121. * @param Name $name Class ame to resolve
  122. *
  123. * @return Name Resolved name
  124. */
  125. public function getResolvedClassName(Name $name) : Name {
  126. return $this->getResolvedName($name, Stmt\Use_::TYPE_NORMAL);
  127. }
  128. /**
  129. * Get possible ways of writing a fully qualified name (e.g., by making use of aliases).
  130. *
  131. * @param string $name Fully-qualified name (without leading namespace separator)
  132. * @param int $type One of Stmt\Use_::TYPE_*
  133. *
  134. * @return Name[] Possible representations of the name
  135. */
  136. public function getPossibleNames(string $name, int $type) : array {
  137. $lcName = strtolower($name);
  138. if ($type === Stmt\Use_::TYPE_NORMAL) {
  139. // self, parent and static must always be unqualified
  140. if ($lcName === "self" || $lcName === "parent" || $lcName === "static") {
  141. return [new Name($name)];
  142. }
  143. }
  144. // Collect possible ways to write this name, starting with the fully-qualified name
  145. $possibleNames = [new FullyQualified($name)];
  146. if (null !== $nsRelativeName = $this->getNamespaceRelativeName($name, $lcName, $type)) {
  147. // Make sure there is no alias that makes the normally namespace-relative name
  148. // into something else
  149. if (null === $this->resolveAlias($nsRelativeName, $type)) {
  150. $possibleNames[] = $nsRelativeName;
  151. }
  152. }
  153. // Check for relevant namespace use statements
  154. foreach ($this->origAliases[Stmt\Use_::TYPE_NORMAL] as $alias => $orig) {
  155. $lcOrig = $orig->toLowerString();
  156. if (0 === strpos($lcName, $lcOrig . '\\')) {
  157. $possibleNames[] = new Name($alias . substr($name, strlen($lcOrig)));
  158. }
  159. }
  160. // Check for relevant type-specific use statements
  161. foreach ($this->origAliases[$type] as $alias => $orig) {
  162. if ($type === Stmt\Use_::TYPE_CONSTANT) {
  163. // Constants are are complicated-sensitive
  164. $normalizedOrig = $this->normalizeConstName($orig->toString());
  165. if ($normalizedOrig === $this->normalizeConstName($name)) {
  166. $possibleNames[] = new Name($alias);
  167. }
  168. } else {
  169. // Everything else is case-insensitive
  170. if ($orig->toLowerString() === $lcName) {
  171. $possibleNames[] = new Name($alias);
  172. }
  173. }
  174. }
  175. return $possibleNames;
  176. }
  177. /**
  178. * Get shortest representation of this fully-qualified name.
  179. *
  180. * @param string $name Fully-qualified name (without leading namespace separator)
  181. * @param int $type One of Stmt\Use_::TYPE_*
  182. *
  183. * @return Name Shortest representation
  184. */
  185. public function getShortName(string $name, int $type) : Name {
  186. $possibleNames = $this->getPossibleNames($name, $type);
  187. // Find shortest name
  188. $shortestName = null;
  189. $shortestLength = \INF;
  190. foreach ($possibleNames as $possibleName) {
  191. $length = strlen($possibleName->toCodeString());
  192. if ($length < $shortestLength) {
  193. $shortestName = $possibleName;
  194. $shortestLength = $length;
  195. }
  196. }
  197. return $shortestName;
  198. }
  199. private function resolveAlias(Name $name, $type) {
  200. $firstPart = $name->getFirst();
  201. if ($name->isQualified()) {
  202. // resolve aliases for qualified names, always against class alias table
  203. $checkName = strtolower($firstPart);
  204. if (isset($this->aliases[Stmt\Use_::TYPE_NORMAL][$checkName])) {
  205. $alias = $this->aliases[Stmt\Use_::TYPE_NORMAL][$checkName];
  206. return FullyQualified::concat($alias, $name->slice(1), $name->getAttributes());
  207. }
  208. } elseif ($name->isUnqualified()) {
  209. // constant aliases are case-sensitive, function aliases case-insensitive
  210. $checkName = $type === Stmt\Use_::TYPE_CONSTANT ? $firstPart : strtolower($firstPart);
  211. if (isset($this->aliases[$type][$checkName])) {
  212. // resolve unqualified aliases
  213. return new FullyQualified($this->aliases[$type][$checkName], $name->getAttributes());
  214. }
  215. }
  216. // No applicable aliases
  217. return null;
  218. }
  219. private function getNamespaceRelativeName(string $name, string $lcName, int $type) {
  220. if (null === $this->namespace) {
  221. return new Name($name);
  222. }
  223. if ($type === Stmt\Use_::TYPE_CONSTANT) {
  224. // The constants true/false/null always resolve to the global symbols, even inside a
  225. // namespace, so they may be used without qualification
  226. if ($lcName === "true" || $lcName === "false" || $lcName === "null") {
  227. return new Name($name);
  228. }
  229. }
  230. $namespacePrefix = strtolower($this->namespace . '\\');
  231. if (0 === strpos($lcName, $namespacePrefix)) {
  232. return new Name(substr($name, strlen($namespacePrefix)));
  233. }
  234. return null;
  235. }
  236. private function normalizeConstName(string $name) {
  237. $nsSep = strrpos($name, '\\');
  238. if (false === $nsSep) {
  239. return $name;
  240. }
  241. // Constants have case-insensitive namespace and case-sensitive short-name
  242. $ns = substr($name, 0, $nsSep);
  243. $shortName = substr($name, $nsSep + 1);
  244. return strtolower($ns) . '\\' . $shortName;
  245. }
  246. }