-
Notifications
You must be signed in to change notification settings - Fork 12
/
VariableAnalysisSniff.php
2111 lines (1929 loc) · 69.3 KB
/
VariableAnalysisSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace VariableAnalysis\Sniffs\CodeAnalysis;
use VariableAnalysis\Lib\ScopeInfo;
use VariableAnalysis\Lib\ScopeType;
use VariableAnalysis\Lib\VariableInfo;
use VariableAnalysis\Lib\Constants;
use VariableAnalysis\Lib\Helpers;
use VariableAnalysis\Lib\ScopeManager;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
class VariableAnalysisSniff implements Sniff
{
/**
* The current phpcsFile being checked.
*
* @var File|null
*/
protected $currentFile = null;
/**
* @var ScopeManager
*/
private $scopeManager;
/**
* A list of for loops, keyed by the index of their first token in this file.
*
* @var array<int, \VariableAnalysis\Lib\ForLoopInfo>
*/
private $forLoops = [];
/**
* A list of enum blocks, keyed by the index of their first token in this file.
*
* @var array<int, \VariableAnalysis\Lib\EnumInfo>
*/
private $enums = [];
/**
* A list of custom functions which pass in variables to be initialized by
* reference (eg `preg_match()`) and therefore should not require those
* variables to be defined ahead of time. The list is space separated and
* each entry is of the form `functionName:1,2`. The function name comes
* first followed by a colon and a comma-separated list of argument numbers
* (starting from 1) which should be considered variable definitions. The
* special value `...` in the arguments list will cause all arguments after
* the last number to be considered variable definitions.
*
* @var string|null
*/
public $sitePassByRefFunctions = null;
/**
* If set, allows common WordPress pass-by-reference functions in addition to
* the standard PHP ones.
*
* @var bool
*/
public $allowWordPressPassByRefFunctions = false;
/**
* Allow exceptions in a catch block to be unused without warning.
*
* @var bool
*/
public $allowUnusedCaughtExceptions = true;
/**
* Allow function parameters to be unused without provoking unused-var warning.
*
* @var bool
*/
public $allowUnusedFunctionParameters = false;
/**
* If set, ignores undefined variables in the file scope (the top-level
* scope of a file).
*
* @var bool
*/
public $allowUndefinedVariablesInFileScope = false;
/**
* If set, ignores unused variables in the file scope (the top-level
* scope of a file).
*
* @var bool
*/
public $allowUnusedVariablesInFileScope = false;
/**
* A space-separated list of names of placeholder variables that you want to
* ignore from unused variable warnings. For example, to ignore the variables
* `$junk` and `$unused`, this could be set to `'junk unused'`.
*
* @var string|null
*/
public $validUnusedVariableNames = null;
/**
* A PHP regexp string for variables that you want to ignore from unused
* variable warnings. For example, to ignore the variables `$_junk` and
* `$_unused`, this could be set to `'/^_/'`.
*
* @var string|null
*/
public $ignoreUnusedRegexp = null;
/**
* A space-separated list of names of placeholder variables that you want to
* ignore from undefined variable warnings. For example, to ignore the variables
* `$post` and `$undefined`, this could be set to `'post undefined'`.
*
* @var string|null
*/
public $validUndefinedVariableNames = null;
/**
* A PHP regexp string for variables that you want to ignore from undefined
* variable warnings. For example, to ignore the variables `$_junk` and
* `$_unused`, this could be set to `'/^_/'`.
*
* @var string|null
*/
public $validUndefinedVariableRegexp = null;
/**
* Allows unused arguments in a function definition if they are
* followed by an argument which is used.
*
* @var bool
*/
public $allowUnusedParametersBeforeUsed = true;
/**
* If set to true, unused values from the `key => value` syntax
* in a `foreach` loop will never be marked as unused.
*
* @var bool
*/
public $allowUnusedForeachVariables = true;
/**
* If set to true, unused variables in a function before a require or import
* statement will not be marked as unused because they may be used in the
* required file.
*
* @var bool
*/
public $allowUnusedVariablesBeforeRequire = false;
public function __construct()
{
$this->scopeManager = new ScopeManager();
}
/**
* Decide which tokens to scan.
*
* @return (int|string)[]
*/
public function register()
{
$types = [
T_VARIABLE,
T_DOUBLE_QUOTED_STRING,
T_HEREDOC,
T_CLOSE_CURLY_BRACKET,
T_FUNCTION,
T_CLOSURE,
T_STRING,
T_COMMA,
T_SEMICOLON,
T_CLOSE_PARENTHESIS,
T_FOR,
T_ENDFOR,
];
if (defined('T_FN')) {
$types[] = T_FN;
}
if (defined('T_ENUM')) {
$types[] = T_ENUM;
}
return $types;
}
/**
* @param string $functionName
*
* @return array<int|string>
*/
private function getPassByReferenceFunction($functionName)
{
$passByRefFunctions = Constants::getPassByReferenceFunctions();
if (!empty($this->sitePassByRefFunctions)) {
$lines = Helpers::splitStringToArray('/\s+/', trim($this->sitePassByRefFunctions));
foreach ($lines as $line) {
list ($function, $args) = explode(':', $line);
$passByRefFunctions[$function] = explode(',', $args);
}
}
if ($this->allowWordPressPassByRefFunctions) {
$passByRefFunctions = array_merge($passByRefFunctions, Constants::getWordPressPassByReferenceFunctions());
}
return isset($passByRefFunctions[$functionName]) ? $passByRefFunctions[$functionName] : [];
}
/**
* Scan and process a token.
*
* This is the main processing function of the sniff. Will run on every token
* for which `register()` returns true.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$scopeStartTokenTypes = [
T_FUNCTION,
T_CLOSURE,
];
$token = $tokens[$stackPtr];
// Cache the current PHPCS File in an instance variable so it can be more
// easily accessed in other places which aren't passed the object.
if ($this->currentFile !== $phpcsFile) {
$this->currentFile = $phpcsFile;
$this->forLoops = [];
$this->enums = [];
}
// Add the global scope for the current file to our scope indexes.
$scopesForFilename = $this->scopeManager->getScopesForFilename($phpcsFile->getFilename());
if (empty($scopesForFilename)) {
$this->scopeManager->recordScopeStartAndEnd($phpcsFile, 0);
}
// Report variables defined but not used in the current scope as unused
// variables if the current token closes scopes.
$this->searchForAndProcessClosingScopesAt($phpcsFile, $stackPtr);
// Scan variables that were postponed because they exist in the increment
// expression of a for loop if the current token closes a loop.
$this->processClosingForLoopsAt($phpcsFile, $stackPtr);
// Find and process variables to perform two jobs: to record variable
// definition or use, and to report variables as undefined if they are used
// without having been first defined.
if ($token['code'] === T_VARIABLE) {
$this->processVariable($phpcsFile, $stackPtr);
return;
}
if (($token['code'] === T_DOUBLE_QUOTED_STRING) || ($token['code'] === T_HEREDOC)) {
$this->processVariableInString($phpcsFile, $stackPtr);
return;
}
if (($token['code'] === T_STRING) && ($token['content'] === 'compact')) {
$this->processCompact($phpcsFile, $stackPtr);
return;
}
// Record for loop boundaries so we can delay scanning the third for loop
// expression until after the loop has been scanned.
if ($token['code'] === T_FOR) {
$this->recordForLoop($phpcsFile, $stackPtr);
return;
}
// Record enums so we can detect them even before phpcs was able to.
if ($token['content'] === 'enum') {
$enumInfo = Helpers::makeEnumInfo($phpcsFile, $stackPtr);
// The token might not actually be an enum so let's avoid returning if
// it's not.
if ($enumInfo) {
$this->enums[$stackPtr] = $enumInfo;
return;
}
}
// If the current token is a call to `get_defined_vars()`, consider that a
// usage of all variables in the current scope.
if ($this->isGetDefinedVars($phpcsFile, $stackPtr)) {
Helpers::debug('get_defined_vars is being called');
$this->markAllVariablesRead($phpcsFile, $stackPtr);
return;
}
// If the current token starts a scope, record that scope's start and end
// indexes so that we can determine if variables in that scope are defined
// and/or used.
if (
in_array($token['code'], $scopeStartTokenTypes, true) ||
Helpers::isArrowFunction($phpcsFile, $stackPtr)
) {
Helpers::debug('found scope condition', $token);
$this->scopeManager->recordScopeStartAndEnd($phpcsFile, $stackPtr);
return;
}
}
/**
* Record the boundaries of a for loop.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
private function recordForLoop($phpcsFile, $stackPtr)
{
$this->forLoops[$stackPtr] = Helpers::makeForLoopInfo($phpcsFile, $stackPtr);
}
/**
* Find scopes closed by a token and process their variables.
*
* Calls `processScopeClose()` for each closed scope.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
private function searchForAndProcessClosingScopesAt($phpcsFile, $stackPtr)
{
$scopeIndicesThisCloses = $this->scopeManager->getScopesForScopeEnd($phpcsFile->getFilename(), $stackPtr);
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
$line = $token['line'];
foreach ($scopeIndicesThisCloses as $scopeIndexThisCloses) {
Helpers::debug('found closing scope at index', $stackPtr, 'line', $line, 'for scopes starting at:', $scopeIndexThisCloses->scopeStartIndex);
$this->processScopeClose($phpcsFile, $scopeIndexThisCloses->scopeStartIndex);
}
}
/**
* Scan variables that were postponed because they exist in the increment expression of a for loop.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
private function processClosingForLoopsAt($phpcsFile, $stackPtr)
{
$forLoopsThisCloses = [];
foreach ($this->forLoops as $forLoop) {
if ($forLoop->blockEnd === $stackPtr) {
$forLoopsThisCloses[] = $forLoop;
}
}
foreach ($forLoopsThisCloses as $forLoop) {
foreach ($forLoop->incrementVariables as $varIndex => $varInfo) {
Helpers::debug('processing delayed for loop increment variable at', $varIndex, $varInfo);
$this->processVariable($phpcsFile, $varIndex, ['ignore-for-loops' => true]);
}
}
}
/**
* Return true if the token is a call to `get_defined_vars()`.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
protected function isGetDefinedVars(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
if (! $token || $token['content'] !== 'get_defined_vars') {
return false;
}
// Make sure this is a function call
$parenPointer = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
if (! $parenPointer || $tokens[$parenPointer]['code'] !== T_OPEN_PARENTHESIS) {
return false;
}
return true;
}
/**
* @return string
*/
protected function getFilename()
{
return $this->currentFile ? $this->currentFile->getFilename() : 'unknown file';
}
/**
* @param int $currScope
*
* @return ScopeInfo
*/
protected function getOrCreateScopeInfo($currScope)
{
$scope = $this->scopeManager->getScopeForScopeStart($this->getFilename(), $currScope);
if (! $scope) {
if (! $this->currentFile) {
throw new \Exception('Cannot create scope info; current file is not set.');
}
$scope = $this->scopeManager->recordScopeStartAndEnd($this->currentFile, $currScope);
}
return $scope;
}
/**
* @param string $varName
* @param int $currScope
*
* @return VariableInfo|null
*/
protected function getVariableInfo($varName, $currScope)
{
$scopeInfo = $this->scopeManager->getScopeForScopeStart($this->getFilename(), $currScope);
return ($scopeInfo && isset($scopeInfo->variables[$varName])) ? $scopeInfo->variables[$varName] : null;
}
/**
* Returns variable data for a variable at an index.
*
* The variable will also be added to the list of variables stored in its
* scope so that its use or non-use can be reported when those scopes end by
* `processScopeClose()`.
*
* @param string $varName
* @param int $currScope
*
* @return VariableInfo
*/
protected function getOrCreateVariableInfo($varName, $currScope)
{
Helpers::debug("getOrCreateVariableInfo: starting for '{$varName}'");
$scopeInfo = $this->getOrCreateScopeInfo($currScope);
if (isset($scopeInfo->variables[$varName])) {
Helpers::debug("getOrCreateVariableInfo: found variable for '{$varName}'", $scopeInfo->variables[$varName]);
return $scopeInfo->variables[$varName];
}
Helpers::debug("getOrCreateVariableInfo: creating a new variable for '{$varName}' in scope", $scopeInfo);
$scopeInfo->variables[$varName] = new VariableInfo($varName);
$validUnusedVariableNames = (empty($this->validUnusedVariableNames))
? []
: Helpers::splitStringToArray('/\s+/', trim($this->validUnusedVariableNames));
$validUndefinedVariableNames = (empty($this->validUndefinedVariableNames))
? []
: Helpers::splitStringToArray('/\s+/', trim($this->validUndefinedVariableNames));
if (in_array($varName, $validUnusedVariableNames)) {
$scopeInfo->variables[$varName]->ignoreUnused = true;
}
if (isset($this->ignoreUnusedRegexp) && preg_match($this->ignoreUnusedRegexp, $varName) === 1) {
$scopeInfo->variables[$varName]->ignoreUnused = true;
}
if ($scopeInfo->scopeStartIndex === 0 && $this->allowUndefinedVariablesInFileScope) {
$scopeInfo->variables[$varName]->ignoreUndefined = true;
}
if (in_array($varName, $validUndefinedVariableNames)) {
$scopeInfo->variables[$varName]->ignoreUndefined = true;
}
if (isset($this->validUndefinedVariableRegexp) && preg_match($this->validUndefinedVariableRegexp, $varName) === 1) {
$scopeInfo->variables[$varName]->ignoreUndefined = true;
}
Helpers::debug("getOrCreateVariableInfo: scope for '{$varName}' is now", $scopeInfo);
return $scopeInfo->variables[$varName];
}
/**
* Record that a variable has been defined and assigned a value.
*
* If a variable has been defined within a scope, it will not be marked as
* undefined when that variable is later used. If it is not used, it will be
* marked as unused when that scope ends.
*
* Sometimes it's possible to assign something to a variable without
* definining it (eg: assignment to a reference); in that case, use
* `markVariableAssignmentWithoutInitialization()`.
*
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return void
*/
protected function markVariableAssignment($varName, $stackPtr, $currScope)
{
Helpers::debug('markVariableAssignment: starting for', $varName);
$this->markVariableAssignmentWithoutInitialization($varName, $stackPtr, $currScope);
Helpers::debug('markVariableAssignment: marked as assigned without initialization', $varName);
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if (isset($varInfo->firstInitialized) && ($varInfo->firstInitialized <= $stackPtr)) {
Helpers::debug('markVariableAssignment: variable is already initialized', $varName);
return;
}
$varInfo->firstInitialized = $stackPtr;
Helpers::debug('markVariableAssignment: marked as initialized', $varName);
}
/**
* Record that a variable has been assigned a value.
*
* Does not record that a variable has been defined, which is the usual state
* of affairs. For that, use `markVariableAssignment()`.
*
* This is useful for assignments to references.
*
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return void
*/
protected function markVariableAssignmentWithoutInitialization($varName, $stackPtr, $currScope)
{
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
// Is the variable referencing another variable? If so, mark that variable used also.
if ($varInfo->referencedVariableScope !== null && $varInfo->referencedVariableScope !== $currScope) {
// Don't do this if the referenced variable does not exist; eg: if it's going to be bound at runtime like in array_walk
if ($this->getVariableInfo($varInfo->name, $varInfo->referencedVariableScope)) {
Helpers::debug('markVariableAssignmentWithoutInitialization: marking referenced variable as assigned also', $varName);
$this->markVariableAssignment($varInfo->name, $stackPtr, $varInfo->referencedVariableScope);
}
}
if (empty($varInfo->scopeType)) {
$varInfo->scopeType = ScopeType::LOCAL;
}
$varInfo->allAssignments[] = $stackPtr;
}
/**
* Record that a variable has been defined within a scope.
*
* @param string $varName
* @param ScopeType::PARAM|ScopeType::BOUND|ScopeType::LOCAL|ScopeType::GLOBALSCOPE|ScopeType::STATICSCOPE $scopeType
* @param ?string $typeHint
* @param int $stackPtr
* @param int $currScope
* @param ?bool $permitMatchingRedeclaration
*
* @return void
*/
protected function markVariableDeclaration(
$varName,
$scopeType,
$typeHint,
$stackPtr,
$currScope,
$permitMatchingRedeclaration = false
) {
Helpers::debug("marking variable '{$varName}' declared in scope starting at token", $currScope);
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if (! empty($varInfo->scopeType)) {
if (($permitMatchingRedeclaration === false) || ($varInfo->scopeType !== $scopeType)) {
// Issue redeclaration/reuse warning
// Note: we check off scopeType not firstDeclared, this is so that
// we catch declarations that come after implicit declarations like
// use of a variable as a local.
$this->addWarning(
'Redeclaration of %s %s as %s.',
$stackPtr,
'VariableRedeclaration',
[
VariableInfo::$scopeTypeDescriptions[$varInfo->scopeType],
"\${$varName}",
VariableInfo::$scopeTypeDescriptions[$scopeType],
]
);
}
}
$varInfo->scopeType = $scopeType;
if (isset($typeHint)) {
$varInfo->typeHint = $typeHint;
}
if (isset($varInfo->firstDeclared) && ($varInfo->firstDeclared <= $stackPtr)) {
Helpers::debug("variable '{$varName}' was already marked declared", $varInfo);
return;
}
$varInfo->firstDeclared = $stackPtr;
$varInfo->allAssignments[] = $stackPtr;
Helpers::debug("variable '{$varName}' marked declared", $varInfo);
}
/**
* @param string $message
* @param int $stackPtr
* @param string $code
* @param string[] $data
*
* @return void
*/
protected function addWarning($message, $stackPtr, $code, $data)
{
if (! $this->currentFile) {
throw new \Exception('Cannot add warning; current file is not set.');
}
$this->currentFile->addWarning(
$message,
$stackPtr,
$code,
$data
);
}
/**
* Record that a variable has been used within a scope.
*
* If the variable has not been defined first, this will still mark it used.
* To display a warning for undefined variables, use
* `markVariableReadAndWarnIfUndefined()`.
*
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return void
*/
protected function markVariableRead($varName, $stackPtr, $currScope)
{
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if (isset($varInfo->firstRead) && ($varInfo->firstRead <= $stackPtr)) {
return;
}
$varInfo->firstRead = $stackPtr;
}
/**
* Return true if a variable is defined within a scope.
*
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return bool
*/
protected function isVariableUndefined($varName, $stackPtr, $currScope)
{
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
Helpers::debug('isVariableUndefined', $varInfo, 'at', $stackPtr);
if ($varInfo->ignoreUndefined) {
return false;
}
if (isset($varInfo->firstDeclared) && $varInfo->firstDeclared <= $stackPtr) {
return false;
}
if (isset($varInfo->firstInitialized) && $varInfo->firstInitialized <= $stackPtr) {
return false;
}
// If we are inside a for loop increment expression, check to see if the
// variable was defined inside the for loop.
foreach ($this->forLoops as $forLoop) {
if ($stackPtr > $forLoop->incrementStart && $stackPtr < $forLoop->incrementEnd) {
Helpers::debug('isVariableUndefined looking at increment expression for loop', $forLoop);
if (
isset($varInfo->firstInitialized)
&& $varInfo->firstInitialized > $forLoop->blockStart
&& $varInfo->firstInitialized < $forLoop->blockEnd
) {
return false;
}
}
}
// If we are inside a for loop body, check to see if the variable was
// defined in that loop's third expression.
foreach ($this->forLoops as $forLoop) {
if ($stackPtr > $forLoop->blockStart && $stackPtr < $forLoop->blockEnd) {
foreach ($forLoop->incrementVariables as $forLoopVarInfo) {
if ($varInfo === $forLoopVarInfo) {
return false;
}
}
}
}
return true;
}
/**
* Record a variable use and report a warning if the variable is undefined.
*
* @param File $phpcsFile
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return void
*/
protected function markVariableReadAndWarnIfUndefined($phpcsFile, $varName, $stackPtr, $currScope)
{
$this->markVariableRead($varName, $stackPtr, $currScope);
if ($this->isVariableUndefined($varName, $stackPtr, $currScope) === true) {
Helpers::debug("variable $varName looks undefined");
if (Helpers::isVariableArrayPushShortcut($phpcsFile, $stackPtr)) {
$this->warnAboutUndefinedArrayPushShortcut($phpcsFile, $varName, $stackPtr);
// Mark the variable as defined if it's of the form `$x[] = 1;`
$this->markVariableAssignment($varName, $stackPtr, $currScope);
return;
}
if (Helpers::isVariableInsideUnset($phpcsFile, $stackPtr)) {
$this->warnAboutUndefinedUnset($phpcsFile, $varName, $stackPtr);
return;
}
$this->warnAboutUndefinedVariable($phpcsFile, $varName, $stackPtr);
}
}
/**
* Mark all variables within a scope as being used.
*
* This will prevent any of the variables in that scope from being reported
* as unused.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
protected function markAllVariablesRead(File $phpcsFile, $stackPtr)
{
$currScope = Helpers::findVariableScope($phpcsFile, $stackPtr);
if ($currScope === null) {
return;
}
$scopeInfo = $this->getOrCreateScopeInfo($currScope);
$count = count($scopeInfo->variables);
Helpers::debug("marking all $count variables in scope as read");
foreach ($scopeInfo->variables as $varInfo) {
$this->markVariableRead($varInfo->name, $stackPtr, $scopeInfo->scopeStartIndex);
}
}
/**
* Process a parameter definition if it is inside a function definition.
*
* This does not include variables imported by a "use" statement.
*
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $outerScope
*
* @return void
*/
protected function processVariableAsFunctionParameter(File $phpcsFile, $stackPtr, $varName, $outerScope)
{
Helpers::debug('processVariableAsFunctionParameter', $stackPtr, $varName);
$tokens = $phpcsFile->getTokens();
$functionPtr = Helpers::getFunctionIndexForFunctionParameter($phpcsFile, $stackPtr);
if (! is_int($functionPtr)) {
throw new \Exception("Function index not found for function argument index {$stackPtr}");
}
Helpers::debug('processVariableAsFunctionParameter found function definition', $tokens[$functionPtr]);
$this->markVariableDeclaration($varName, ScopeType::PARAM, null, $stackPtr, $functionPtr);
// Are we pass-by-reference?
$referencePtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, true, null, true);
if (($referencePtr !== false) && ($tokens[$referencePtr]['code'] === T_BITWISE_AND)) {
Helpers::debug('processVariableAsFunctionParameter found pass-by-reference to scope', $outerScope);
$varInfo = $this->getOrCreateVariableInfo($varName, $functionPtr);
$varInfo->referencedVariableScope = $outerScope;
}
// Are we optional with a default?
if (Helpers::getNextAssignPointer($phpcsFile, $stackPtr) !== null) {
Helpers::debug('processVariableAsFunctionParameter optional with default');
$this->markVariableAssignment($varName, $stackPtr, $functionPtr);
}
// Are we using constructor promotion? If so, that counts as both definition and use.
if (Helpers::isConstructorPromotion($phpcsFile, $stackPtr)) {
Helpers::debug('processVariableAsFunctionParameter constructor promotion');
$this->markVariableRead($varName, $stackPtr, $outerScope);
}
}
/**
* Process a variable definition if it is inside a function's "use" import.
*
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $outerScope The start of the scope outside the function definition
*
* @return void
*/
protected function processVariableAsUseImportDefinition(File $phpcsFile, $stackPtr, $varName, $outerScope)
{
$tokens = $phpcsFile->getTokens();
Helpers::debug('processVariableAsUseImportDefinition', $stackPtr, $varName, $outerScope);
$endOfArgsPtr = $phpcsFile->findPrevious([T_CLOSE_PARENTHESIS], $stackPtr - 1, null);
if (! is_int($endOfArgsPtr)) {
throw new \Exception("Arguments index not found for function use index {$stackPtr} when processing variable {$varName}");
}
$functionPtr = Helpers::getFunctionIndexForFunctionParameter($phpcsFile, $endOfArgsPtr);
if (! is_int($functionPtr)) {
throw new \Exception("Function index not found for function use index {$stackPtr} (using {$endOfArgsPtr}) when processing variable {$varName}");
}
// Use is both a read (in the enclosing scope) and a define (in the function scope)
$this->markVariableRead($varName, $stackPtr, $outerScope);
// If it's undefined in the enclosing scope, the use is wrong
if ($this->isVariableUndefined($varName, $stackPtr, $outerScope) === true) {
Helpers::debug("variable '{$varName}' in function definition looks undefined in scope", $outerScope);
$this->warnAboutUndefinedVariable($phpcsFile, $varName, $stackPtr);
return;
}
$this->markVariableDeclaration($varName, ScopeType::BOUND, null, $stackPtr, $functionPtr);
$this->markVariableAssignment($varName, $stackPtr, $functionPtr);
// Are we pass-by-reference? If so, then any assignment to the variable in
// the function scope also should count for the enclosing scope.
$referencePtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, true, null, true);
if (is_int($referencePtr) && $tokens[$referencePtr]['code'] === T_BITWISE_AND) {
Helpers::debug("variable '{$varName}' in function definition looks passed by reference");
$varInfo = $this->getOrCreateVariableInfo($varName, $functionPtr);
$varInfo->referencedVariableScope = $outerScope;
}
}
/**
* Process a class property that is being defined.
*
* Property definitions are ignored currently because all property access is
* legal, even to undefined properties.
*
* Can be called for any token and will return false if the variable is not
* of this type.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
protected function processVariableAsClassProperty(File $phpcsFile, $stackPtr)
{
$propertyDeclarationKeywords = [
T_PUBLIC,
T_PRIVATE,
T_PROTECTED,
T_VAR,
];
$stopAtPtr = $stackPtr - 2;
$visibilityPtr = $phpcsFile->findPrevious($propertyDeclarationKeywords, $stackPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if ($visibilityPtr) {
return true;
}
$staticPtr = $phpcsFile->findPrevious(T_STATIC, $stackPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if (! $staticPtr) {
return false;
}
$stopAtPtr = $staticPtr - 2;
$visibilityPtr = $phpcsFile->findPrevious($propertyDeclarationKeywords, $staticPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if ($visibilityPtr) {
return true;
}
// it's legal to use `static` to define properties as well as to
// define variables, so make sure we are not in a function before
// assuming it's a property.
$tokens = $phpcsFile->getTokens();
/** @var array{conditions?: (int|string)[], content?: string}|null */
$token = $tokens[$stackPtr];
if ($token && !empty($token['conditions']) && !empty($token['content']) && !Helpers::areConditionsWithinFunctionBeforeClass($token)) {
return Helpers::areAnyConditionsAClass($token);
}
return false;
}
/**
* Process a variable that is being accessed inside a catch block.
*
* Can be called for any token and will return false if the variable is not
* of this type.
*
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function processVariableAsCatchBlock(File $phpcsFile, $stackPtr, $varName, $currScope)
{
$tokens = $phpcsFile->getTokens();
// Are we a catch block parameter?
$openPtr = Helpers::findContainingOpeningBracket($phpcsFile, $stackPtr);
if ($openPtr === null) {
return false;
}
$catchPtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, $openPtr - 1, null, true, null, true);
if (($catchPtr !== false) && ($tokens[$catchPtr]['code'] === T_CATCH)) {
// Scope of the exception var is actually the function, not just the catch block.
$this->markVariableDeclaration($varName, ScopeType::LOCAL, null, $stackPtr, $currScope, true);
$this->markVariableAssignment($varName, $stackPtr, $currScope);
if ($this->allowUnusedCaughtExceptions) {
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
$varInfo->ignoreUnused = true;
}
return true;
}
return false;
}
/**
* Process a variable that is being accessed as a member of `$this`.
*
* Looks for variables of the form `$this->myVariable`.
*
* Can be called for any token and will return false if the variable is not
* of this type.
*
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
*
* @return bool
*/
protected function processVariableAsThisWithinClass(File $phpcsFile, $stackPtr, $varName)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Are we $this within a class?
if (($varName !== 'this') || empty($token['conditions'])) {
return false;
}
// Handle enums specially since their condition may not exist in old phpcs.
$inEnum = false;
foreach ($this->enums as $enum) {
if ($stackPtr > $enum->blockStart && $stackPtr < $enum->blockEnd) {
$inEnum = true;
}
}
$inFunction = false;
foreach (array_reverse($token['conditions'], true) as $scopeCode) {
// $this within a closure is valid
if ($scopeCode === T_CLOSURE && $inFunction === false) {
return true;
}
$classlikeCodes = [T_CLASS, T_ANON_CLASS, T_TRAIT];
if (defined('T_ENUM')) {
$classlikeCodes[] = T_ENUM;
}
if (in_array($scopeCode, $classlikeCodes, true)) {
return true;
}
if ($scopeCode === T_FUNCTION && $inEnum) {
return true;
}
// Handle nested function declarations.
if ($scopeCode === T_FUNCTION) {
if ($inFunction === true) {
break;
}
$inFunction = true;
}
}
return false;
}
/**
* Process a superglobal variable that is being accessed.
*
* Can be called for any token and will return false if the variable is not
* of this type.
*
* @param string $varName
*
* @return bool