rfc:token_as_object

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
rfc:token_as_object [2020/02/13 10:22] – Remove T_BAD_CHARACTER from ignorable tokens nikicrfc:token_as_object [2020/02/25 15:58] nikic
Line 1: Line 1:
-====== PHP RFC: token_get_all() TOKEN_AS_OBJECT mode ======+====== PHP RFC: Object-based token_get_all() alternative ======
   * Date: 2020-02-13   * Date: 2020-02-13
   * Author: Nikita Popov <nikic@php.net>   * Author: Nikita Popov <nikic@php.net>
Line 8: Line 8:
 ===== Introduction ===== ===== Introduction =====
  
-The ''token_get_all()'' function currently returns tokens either as a single-character string, or an array with a token ID, token text and line number. This RFC proposes to add a token_get_all() mode which returns an object instead. This reduces memory usage and makes code operating on tokens more readable.+The ''token_get_all()'' function currently returns tokens either as a single-character string, or an array with a token ID, token text and line number. This RFC proposes to add a token_get_all() alternative which returns an array of objects instead. This reduces memory usage and makes code operating on tokens more readable.
  
 ===== Proposal ===== ===== Proposal =====
  
-''token_get_all()'' accepts a new ''TOKEN_AS_OBJECT'' flag (which can be combined with the existing ''TOKEN_PARSE'' flag as well). If this flag is set, the return value is of type ''PhpToken[]'' declared as follows:+new ''PhpToken'' class is introduced with the following properties and methods:
  
 <PHP> <PHP>
Line 24: Line 24:
     /** The starting position (0-based) in the tokenized string. */     /** The starting position (0-based) in the tokenized string. */
     public int $pos;     public int $pos;
 +    
 +    /**
 +     * Same as token_get_all(), but returning array of PhpToken.
 +     * @return static[]
 +     */
 +    public static function getAll(string $code, int $flags = 0): array;
 +    
 +    final public function __construct(int $id, string $text, int $line = -1, int $pos = -1);
 } }
 </PHP> </PHP>
 +
 +The ''PhpToken::getAll()'' method is the replacement for ''token_get_all()'', which returns an array of ''PhpToken'' objects instead of a mix of strings and arrays.
  
 It should be emphasized that **all** tokens are returned as objects, including single-char tokens. While this uses more memory than returning them as strings, experience has shown that the current string/array mix is very inconvenient to work with. It should be emphasized that **all** tokens are returned as objects, including single-char tokens. While this uses more memory than returning them as strings, experience has shown that the current string/array mix is very inconvenient to work with.
Line 35: Line 45:
   * The token stores the position in the file, so that consumers don't have to compute and store it separately.   * The token stores the position in the file, so that consumers don't have to compute and store it separately.
  
-Finally (and this is the real motivation here), the tokens take up signficiantly less memory, and are faster to construct as well. On a large file:+Finally, the tokens take up significantly less memory, and are faster to construct as well. On a large file:
  
 <code> <code>
Line 46: Line 56:
 </code> </code>
  
-==== Additional methods ====+==== Extensibility ====
  
-There are a few useful helper methods that could be added to the ''PhpToken'' class. Whether these should be added as part of this proposal is an **open question**.+The ''PhpToken::getAll()'' method returns ''static[]'', as such it is possible to seamlessly extend the class: 
 + 
 +<PHP> 
 +class MyPhpToken extends PhpToken { 
 +    public function getLowerText() { 
 +        return strtolower($this->text); 
 +    } 
 +
 + 
 +$tokens = MyPhpToken::getAll($code); 
 +var_dump($tokens[0] instanceof MyPhpToken); // true 
 +$tokens[0]->getLowerText(); // works 
 +</PHP> 
 + 
 +To guarantee a well-defined construction behavior, the ''PhpToken'' constructor is final and cannot be overridden by child classes. This matches the extension approach of the ''SimpleXMLElement'' class. 
 + 
 +===== Open Questions ===== 
 + 
 +==== Additional methods ====
  
-Three suggestions are given as PHP code below. The ''is()'' method is a useful helper, variations of which will be found in many libraries processing token streams. ''isIgnorable()'' helps the particularly common case of skipping whitespace-like tokens. ''getTokenName()'' avoids going through ''token_name()'' for debug output.+There are a few useful helper methods that could be added to the ''PhpToken'' class. Three suggestions are given as PHP code below. The ''is()'' method is a useful helper, variations of which will be found in many libraries processing token streams. ''isIgnorable()'' helps the particularly common case of skipping whitespace-like tokens. ''getTokenName()'' avoids going through ''token_name()'' for debug output.
  
 <PHP> <PHP>
Line 92: Line 120:
  
     /** Get the name of the token. */     /** Get the name of the token. */
-    public function getTokenName(): string {+    public function getTokenName(): ?string {
         if ($this->id < 256) {         if ($this->id < 256) {
             return chr($this->id);             return chr($this->id);
 +        } elseif ('UNKNOWN' !== $name = token_name($this->id)) {
 +            return $name;
         } else {         } else {
-            return token_name($this->id);+            return null;
         }         }
     }     }
 } }
 </PHP> </PHP>
 +
 +===== Rejected Features =====
 +
 +==== Lazy token stream ====
 +
 +''PhpToken::getAll()'' returns an array of tokens. It has been suggested that it could return an iterator instead. This would reduce memory usage if it is sufficient to inspect tokens one-by-one for a given use-case.
 +
 +This is not supported by the current proposal, because the current PHP lexer doesn't support this in an efficient manner. A full lexer state backup and restore would have to be performed for each token. Even if support for an iterator is added in the future, the ability to directly create an array should still be retained, as this will always be more efficient than going through an iterator (for the use-cases that do need a full token array).
  
 ===== Backward Incompatible Changes ===== ===== Backward Incompatible Changes =====
  
-There are no backwards compatibility breaks, apart from the new constant name and the new class name.+There are no backwards compatibility breaks, apart from the new class name.
  
 ===== Vote ===== ===== Vote =====
rfc/token_as_object.txt · Last modified: 2020/11/12 13:33 by nikic