Perl-Critic / PPI

53 stars 44 forks source link

Misparse bareword as label #262

Closed carygravel closed 1 year ago

carygravel commented 2 years ago

It is common to have barewords defined by, e.g. Glib:

use Glib qw(TRUE FALSE);

When using a ternary operator, these can be misparsed. PPI 1.270 parses TRUE : as a label in the following:

$result = $result_of_expression ? TRUE : FALSE;

instead of identifying the : as an operator.

oalders commented 2 years ago
PPI::Document
  PPI::Statement::Include
    PPI::Token::Word    'use'
    PPI::Token::Whitespace      ' '
    PPI::Token::Word    'Glib'
    PPI::Token::Whitespace      ' '
    PPI::Token::QuoteLike::Words        'qw(TRUE FALSE)'
    PPI::Token::Structure       ';'
  PPI::Token::Whitespace        '\n'
  PPI::Token::Whitespace        '\n'
  PPI::Statement
    PPI::Token::Symbol          '$result'
    PPI::Token::Whitespace      ' '
    PPI::Token::Operator        '='
    PPI::Token::Whitespace      ' '
    PPI::Token::Symbol          '$result_of_expression'
    PPI::Token::Whitespace      ' '
    PPI::Token::Operator        '?'
    PPI::Token::Whitespace      ' '
    PPI::Token::Label   'TRUE :'
    PPI::Token::Whitespace      ' '
    PPI::Token::Word    'FALSE'
    PPI::Token::Structure       ';'
  PPI::Token::Whitespace        '\n'
h3xx commented 1 year ago

I've run across a similar bug where a terinary was parsed as a P:T:Label.

Adding a newline before the colon stopped it from parsing as a Label.

Expression Result
1 ? $var : 0
no Label ✅
1 ? $var->method : 0
Label ❌
1 ? $var::->method : 0
Label ❌
1 ? var->method : 0
Label ❌
1 ? ($var->method) : 0
no Label ✅
1 ? $var->method() : 0
no Label ✅
1 ? ($var)->method : 0
Label ❌
1 ? $var->method 
: 0
no Label ✅

Oddly:

Expression Result
$var ? TRUE : FALSE
Label ❌
$var ? 1 : 0
no Label ✅

PPI version 1.276.

oalders commented 1 year ago

If someone wanted to put together a patch to fix this, that would be great.

h3xx commented 1 year ago

I have fix submitted in #289. Can you let me know if this fixes your issue.

Also, could you especially let me know if this causes any other issues. 😄

wchristian commented 1 year ago

fwiw, i hope to be past the worst in my current $work project by wednesday and will do some review then :)

h3xx commented 1 year ago

@wchristian Any luck?

wchristian commented 1 year ago

sorry, work was not compatible, i have poked at the PR and left a comment