nikic / PHP-Parser

A PHP parser written in PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

different parsing of "elseif" & "else if"

lc1337 opened this issue · comments

"elseif" and "else if" should have same meaning, but it's being treated differently

"else if" - incorrect

<?php

if(1){
}else if(2){
}else{
}

Screenshot_37

"elseif" - correct

<?php

if(1){
}elseif(2){
}else{
}

Screenshot_38

elseif is a special syntactical feature of if statements. else if is simply an else block that happens to contain an if. They are semantically the same, but syntactically quite different.

Now, the parser does sometimes gloss over syntactical differences, and for example will not distinguish between $$x and ${$x}. So I can in principle see an argument in favor of canonicalizing everything to the elseif representation.

Maybe @TomasVotruba or @ondrejmirtes have an opinion on that. Personally, I think it's preferable to stay closer to the actual syntactical structure of the program, especially wrt formatting preservation. (To give an example, the else if "syntax" allows you to mix normal and alternative form of if, while this is not possible with elseif. This sounds very painful to untangle.)

I agree with @nikic .
Having an array suggest there is 0+ items possible, but else is always exactly 0/1 item. I haven't had a need to use it differently.

OK, makes sense.

It's just a pity, because when reconstructing the PHP code back, instead of nice and flat structure of else if blocks, I would get a deep nested structure of else and if blocks.

I think we can accommodate this in the pretty printer. We should be able to print it as else if. I'll run some tests.

Done in aa72152.

Tested and works for me, thanks.

Hopefully it won't cause any troubles for others, since now, when the nested structure is coded explicitly:

if ( 1 ) {
} else {
	  if ( 2 ) {
	  } else {
	  }
}

by parsing + reprinting, it will change it to:

if ( 1 ) {
} else if ( 2 ) {
} else {
}