Home > Software engineering >  How do I change the perl regex for code formatting?
How do I change the perl regex for code formatting?

Time:02-11

I am trying to understand the below code. But I am not getting it. Basically, the below code currently checks for if condition in a c or cpp file.

if ($perl_version_ok &&
    $line =~ /^\ (.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
    # Throw error
}

where Constant is any macro or any constant value; LvalOrFunc is any variable or function call; Compare is the operations like !=, == ,&& , etc

The if checks for codes like this if(CONST_VALUE == x), where CONST_VALUE is some macros. In this case its true and goes inside if condition.

But I want to check for the opposite if(x == CONST_VALUE ), and then throw error.

Please help in understanding this piece of line and how to achieve the desired result.

Note: The code is from linux kernel dir, available here: https://github.com/torvalds/linux/blob/master/scripts/checkpatch.pl

Line number of the code: 5483

CodePudding user response:

The code doesn't check for if(CONST_VALUE == x). As shown in the comments above the line in the source code

# comparisons with a constant or upper case identifier on the left
#   avoid cases like "foo   BAR < baz"
#   only fix matches surrounded by parentheses to avoid incorrect
#   conversions like "FOO < baz()   5" being "misfixed" to "baz() > FOO   5"

it checks for a plus sign followed by a CONSTANT_VALUE == x. The \ in the regex matches a plus sign.

$line =~ /^\ (.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/
      ^   ^ ^  ^  ^
      |   | |  |  |
binding   | |  |  word
operator  | |  |  boundary
      start |  |
  of string |  |
         plus  | 
        anything

Reverting the compared values should be easy:

($LvalOrFunc)\s*($Compare)\s*($Constant|[A-Z_][A-Z0-9_]*)
  • Related