Skip to content

Commit 8d02d37

Browse files
committed
More docs updates
1 parent e68b17c commit 8d02d37

9 files changed

+53
-47
lines changed

doc/component/AST_builders.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ abstract class SomeOtherClass extends SomeClass implements A\Few, \Interfaces
101101
*
102102
* @param SomeClass And takes a parameter
103103
*/
104-
public abstract function someMethod(SomeClass $someParam) : bool;
104+
public abstract function someMethod(SomeClass $someParam): bool;
105105
protected function anotherMethod($someParam = 'test')
106106
{
107107
print $someParam;

doc/component/Constant_expression_evaluation.markdown

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ PHP-Parser supports evaluation of such constant expressions through the `ConstEx
1919

2020
use PhpParser\{ConstExprEvaluator, ConstExprEvaluationException};
2121

22-
$evalutator = new ConstExprEvaluator();
22+
$evaluator = new ConstExprEvaluator();
2323
try {
24-
$value = $evalutator->evaluateSilently($someExpr);
24+
$value = $evaluator->evaluateSilently($someExpr);
2525
} catch (ConstExprEvaluationException $e) {
2626
// Either the expression contains unsupported expression types,
2727
// or an error occurred during evaluation
@@ -69,6 +69,7 @@ expressions, apart from the following:
6969
* `Scalar\MagicConst\*`
7070
* `Expr\ConstFetch` (only null/false/true are handled)
7171
* `Expr\ClassConstFetch`
72+
* `Expr\New_` (since PHP 8.1)
7273

7374
Handling these expression types requires non-local information, such as which global constants are
7475
defined. By default, the evaluator will throw a `ConstExprEvaluationException` when it encounters

doc/component/Error_handling.markdown

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ In order to receive information about not only the line, but also the column spa
1414
position attributes in the lexer need to be enabled:
1515

1616
```php
17-
$lexer = new PhpParser\Lexer(array(
17+
$lexerOptions = array(
1818
'usedAttributes' => array('comments', 'startLine', 'endLine', 'startFilePos', 'endFilePos'),
19-
));
20-
$parser = (new PhpParser\ParserFactory)->create(PhpParser\ParserFactory::PREFER_PHP7, $lexer);
19+
);
20+
$parser = (new PhpParser\ParserFactory())->createForHostVersion($lexerOptions);
2121

2222
try {
2323
$stmts = $parser->parse($code);
@@ -56,7 +56,7 @@ To instead collect all encountered errors into an array, while trying to continu
5656
an instance of `ErrorHandler\Collecting` can be passed to the `Parser::parse()` method. A usage example:
5757

5858
```php
59-
$parser = (new PhpParser\ParserFactory)->create(PhpParser\ParserFactory::ONLY_PHP7);
59+
$parser = (new PhpParser\ParserFactory())->createForHostVersion();
6060
$errorHandler = new PhpParser\ErrorHandler\Collecting;
6161

6262
$stmts = $parser->parse($code, $errorHandler);
@@ -72,4 +72,6 @@ if (null !== $stmts) {
7272
}
7373
```
7474

75+
The partial AST may contain `Expr\Error` nodes that indicate that an error occurred while parsing an expression.
76+
7577
The `NameResolver` visitor also accepts an `ErrorHandler` as a constructor argument.

doc/component/FAQ.markdown

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ $code = '...';
1919
$traverser = new NodeTraverser;
2020
$traverser->addVisitor(new ParentConnectingVisitor);
2121

22-
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
22+
$parser = (new ParserFactory())->createForHostVersion();
2323
$ast = $parser->parse($code);
2424
$ast = $traverser->traverse($ast);
2525
```
@@ -42,7 +42,7 @@ $code = '...';
4242
$traverser = new NodeTraverser;
4343
$traverser->addVisitor(new NodeConnectingVisitor);
4444

45-
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
45+
$parser = (new ParserFactory())->createForHostVersion();
4646
$ast = $parser->parse($code);
4747
$ast = $traverser->traverse($ast);
4848
```

doc/component/JSON_representation.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ function printLine($msg) {
1818
}
1919
CODE;
2020

21-
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
21+
$parser = (new ParserFactory())->createForHostVersion();
2222

2323
try {
2424
$stmts = $parser->parse($code);

doc/component/Lexer.markdown

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,17 @@ The attributes used in this example match the default behavior of the lexer. The
4242
> **Note:** The example in this section is outdated in that this information is directly available in the AST: While
4343
> `$property->isPublic()` does not distinguish between `public` and `var`, directly checking `$property->flags` for
4444
> the `$property->flags & Class_::VISIBILITY_MODIFIER_MASK) === 0` allows making this distinction without resorting to
45-
> tokens. However the general idea behind the example still applies in other cases.
45+
> tokens. However, the general idea behind the example still applies in other cases.
4646
4747
The token offset information is useful if you wish to examine the exact formatting used for a node. For example the AST
4848
does not distinguish whether a property was declared using `public` or using `var`, but you can retrieve this
4949
information based on the token position:
5050

5151
```php
52+
/** @param PhpParser\Token[] $tokens */
5253
function isDeclaredUsingVar(array $tokens, PhpParser\Node\Stmt\Property $prop) {
53-
$i = $prop->getAttribute('startTokenPos');
54-
return $tokens[$i][0] === T_VAR;
54+
$i = $prop->getStartTokenPos();
55+
return $tokens[$i]->id === T_VAR;
5556
}
5657
```
5758

@@ -72,12 +73,12 @@ class MyNodeVisitor extends PhpParser\NodeVisitorAbstract {
7273
}
7374
}
7475

75-
$lexer = new PhpParser\Lexer(array(
76+
$lexerOptions = array(
7677
'usedAttributes' => array(
7778
'comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos'
7879
)
79-
));
80-
$parser = (new PhpParser\ParserFactory)->create(PhpParser\ParserFactory::ONLY_PHP7, $lexer);
80+
);
81+
$parser = (new PhpParser\ParserFactory())->createForHostVersion($lexerOptions);
8182

8283
$visitor = new MyNodeVisitor();
8384
$traverser = new PhpParser\NodeTraverser();
@@ -111,14 +112,15 @@ The `startLexing()` method is invoked whenever the `parse()` method of the parse
111112
code that is to be lexed (including the opening tag). It can be used to reset state or preprocess the source code or tokens. The
112113
passed `ErrorHandler` should be used to report lexing errors.
113114

114-
The `getTokens()` method returns the current token array, in the usual `token_get_all()` format. This method is not
115-
used by the parser (which uses `getNextToken()`), but is useful in combination with the token position attributes.
115+
The `getTokens()` method returns the current array of `PhpParser\Token`s, which are compatible with the PHP 8 `PhpToken`
116+
class. This method is not used by the parser (which uses `getNextToken()`), but is useful in combination with the token
117+
position attributes.
116118

117119
The `handleHaltCompiler()` method is called whenever a `T_HALT_COMPILER` token is encountered. It has to return the
118120
remaining string after the construct (not including `();`).
119121

120-
The `getNextToken()` method returns the ID of the next token (as defined by the `Parser::T_*` constants). If no more
121-
tokens are available it must return `0`, which is the ID of the `EOF` token. Furthermore the string content of the
122+
The `getNextToken()` method returns the ID of the next token (in the sense of `Token::$id`). If no more
123+
tokens are available it must return `0`, which is the ID of the `EOF` token. Furthermore, the string content of the
122124
token should be written into the by-reference `$value` parameter (which will then be available as `$n` in the parser).
123125

124126
### Attribute handling
@@ -144,10 +146,10 @@ class KeepOriginalValueLexer extends Lexer // or Lexer\Emulative
144146
public function getNextToken(&$value = null, &$startAttributes = null, &$endAttributes = null) {
145147
$tokenId = parent::getNextToken($value, $startAttributes, $endAttributes);
146148

147-
if ($tokenId == Tokens::T_CONSTANT_ENCAPSED_STRING // non-interpolated string
148-
|| $tokenId == Tokens::T_ENCAPSED_AND_WHITESPACE // interpolated string
149-
|| $tokenId == Tokens::T_LNUMBER // integer
150-
|| $tokenId == Tokens::T_DNUMBER // floating point number
149+
if ($tokenId == \T_CONSTANT_ENCAPSED_STRING // non-interpolated string
150+
|| $tokenId == \T_ENCAPSED_AND_WHITESPACE // interpolated string
151+
|| $tokenId == \T_LNUMBER // integer
152+
|| $tokenId == \T_DNUMBER // floating point number
151153
) {
152154
// could also use $startAttributes, doesn't really matter here
153155
$endAttributes['originalValue'] = $value;

doc/component/Name_resolution.markdown

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ visitor (NameResolver) based on it.
1010
The NameResolver visitor
1111
------------------------
1212

13-
The `NameResolver` visitor can (and for nearly all uses of the AST, is) be applied to resolve names
13+
The `NameResolver` visitor can (and for nearly all uses of the AST, should) be applied to resolve names
1414
to their fully-qualified form, to the degree that this is possible.
1515

1616
```php
@@ -53,7 +53,7 @@ name. Once again, if an unqualified function or constant name cannot be resolved
5353
`resolvedName` attribute will not be present, and instead a `namespacedName` attribute is added.
5454

5555
The `replaceNodes` attribute is useful if you wish to perform modifications on the AST, as you
56-
probably do not wish the resoluting code to have fully resolved names as a side-effect.
56+
probably do not wish the resulting code to have fully resolved names as a side-effect.
5757

5858
The NameContext
5959
---------------
@@ -84,4 +84,4 @@ representation of a name given the current name resolution environment.
8484
The name context is intended to be used for name resolution operations outside the AST itself, such
8585
as class names inside doc comments. A visitor running in parallel with the name resolver can access
8686
the name context using `$nameResolver->getNameContext()`. Alternatively a visitor can use an
87-
independent context and explicitly feed `Namespace` and `Use` nodes to it.
87+
independent context and explicitly feed `Namespace` and `Use` nodes to it.

doc/component/Pretty_printing.markdown

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,16 @@ expression.
3131
Customizing the formatting
3232
--------------------------
3333

34-
Apart from an `shortArraySyntax` option, the default pretty printer does not provide any
35-
functionality to customize the formatting of the generated code. The pretty printer does respect a
36-
number of `kind` attributes used by some notes (e.g., whether an integer should be printed as
37-
decimal, hexadecimal, etc), but there are no options to control brace placement or similar.
34+
The pretty printer respects a number of `kind` attributes used by some notes (e.g., whether an
35+
integer should be printed as decimal, hexadecimal, etc). Additionally, it supports two options:
36+
37+
* `phpVersion` (defaults to 7.0) allows opting into formatting that is not supported by older PHP
38+
versions.
39+
* `shortArraySyntax` determines the used array syntax if the `kind` attribute is not set. This is
40+
a legacy option, and `phpVersion` should be used to control this behavior instead.
41+
42+
However, the default pretty printer does not provide any functionality for fine-grained
43+
customization of code formatting.
3844

3945
If you want to make minor changes to the formatting, the easiest way is to extend the pretty printer
4046
and override the methods responsible for the node types you are interested in.
@@ -46,29 +52,27 @@ default pretty printer with an existing library for code reformatting, such as
4652
Formatting-preserving pretty printing
4753
-------------------------------------
4854

49-
> **Note:** This functionality is **experimental** and not yet complete.
50-
5155
For automated code refactoring, migration and similar, you will usually only want to modify a small
5256
portion of the code and leave the remainder alone. The basic pretty printer is not suitable for
5357
this, because it will also reformat parts of the code which have not been modified.
5458

55-
Since PHP-Parser 4.0, an experimental formatting-preserving pretty-printing mode is available, which
59+
Since PHP-Parser 4.0, a formatting-preserving pretty-printing mode is available, which
5660
attempts to preserve the formatting of code (those AST nodes that have not changed) and only reformat
5761
code which has been modified or newly inserted.
5862

5963
Use of the formatting-preservation functionality requires some additional preparatory steps:
6064

6165
```php
62-
use PhpParser\{Lexer, NodeTraverser, NodeVisitor, Parser, PrettyPrinter};
66+
use PhpParser\{Lexer, NodeTraverser, NodeVisitor, ParserFactory, PrettyPrinter};
6367

64-
$lexer = new Lexer\Emulative([
68+
$lexerOptions = new [
6569
'usedAttributes' => [
6670
'comments',
6771
'startLine', 'endLine',
6872
'startTokenPos', 'endTokenPos',
6973
],
70-
]);
71-
$parser = new Parser\Php7($lexer);
74+
];
75+
$parser = (new ParserFactory())->createForHostVersion($lexerOptions);
7276

7377
$traverser = new NodeTraverser();
7478
$traverser->addVisitor(new NodeVisitor\CloningVisitor());
@@ -86,11 +90,9 @@ $newCode = $printer->printFormatPreserving($newStmts, $oldStmts, $oldTokens);
8690
```
8791

8892
If you make use of the name resolution functionality, you will likely want to disable the
89-
`replaceNodes` option. This will add resolved names as attributes, instead of directlying modifying
93+
`replaceNodes` option. This will add resolved names as attributes, instead of directly modifying
9094
the AST and causing spurious changes to the pretty printed code. For more information, see the
9195
[name resolution documentation](Name_resolution.markdown).
9296

93-
This functionality is experimental and not yet fully implemented. It should not provide incorrect
94-
code, but it may sometimes reformat more code than necessary. Open issues are tracked in
95-
[issue #344](https://github.com/nikic/PHP-Parser/issues/344). If you encounter problems while using
96-
this functionality, please open an issue, so we know what to prioritize.
97+
The formatting-preservation works on a best-effort basis and may sometimes reformat more code tha
98+
necessary. If you encounter problems while using this functionality, please open an issue.

doc/component/Walking_the_AST.markdown

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,8 +129,7 @@ Now `$a && $b` will be replaced by `!($a && $b)`. Then the traverser will go int
129129
only) child of `!($a && $b)`, which is `$a && $b`. The transformation applies again and we end up
130130
with `!!($a && $b)`. This will continue until PHP hits the memory limit.
131131

132-
Finally, two special replacement types are supported only by leaveNode. The first is removal of a
133-
node:
132+
Finally, there are two special replacement types. The first is removal of a node:
134133

135134
```php
136135
public function leaveNode(Node $node) {
@@ -165,8 +164,8 @@ This example will remove all calls to `var_dump()` which occur as expression sta
165164
that `var_dump($a);` will be removed, but `if (var_dump($a))` will not be removed (and there is no
166165
obvious way in which it can be removed).
167166

168-
Next to removing nodes, it is also possible to replace one node with multiple nodes. Again, this
169-
only works inside leaveNode and only if the parent structure is an array.
167+
Next to removing nodes, it is also possible to replace one node with multiple nodes. This
168+
only works if the parent structure is an array.
170169

171170
```php
172171
public function leaveNode(Node $node) {

0 commit comments

Comments
 (0)