asmblah / uniter

🎉 PHP in the browser and Node.js => Docs: https://phptojs.com/
https://asmblah.github.io/uniter/
Other
446 stars 42 forks source link

Unreachable Code after return statement #51

Closed phpengine closed 6 years ago

phpengine commented 6 years ago

Hi @asmblah ,

I see this a lot, probably hundreds of times a day actually :D . I've been ignoring it until I had the other bits reasonably stable, and I guess that's about now.

For instance, the console on the following page... http://www.devcloud.isophp.org.uk/

Has over 600 appearances of unreachable code after return statement

How do I get rid of these? Or do I need to?

Thanks, Dave

the-liquid-metal commented 6 years ago

hint: "unreachable code after return statement" means you have statement(s) after return statement.

for example:

function fn (a, b) {
    var c = a + b;
    return c;
    var d = a - b; // these statements cause "unreachable" warning
   console.log(d);
}
phpengine commented 6 years ago

Hi there @the-liquid-metal (terminator I hope) ,

Thanks for adding, though I knew the meaning of the warning. As this JS Code is generated by Uniter, it is not hand modified. So, in order for me to have the code generated without those statements, I was asking what I should change about my input code.

asmblah commented 6 years ago

Hi @phpengine,

Can I assume you're seeing those error messages in Firefox's console? Those will almost certainly be the end of any PHP function that returns a value, because the transpiler always appends some code to return a PHP null value at the end as that's the default. For example:

$ uniter -t -r 'print 21; return 101;'
require('phpruntime').compile(function(stdin, stdout, stderr, tools, namespace) {
  var namespaceScope = tools.topLevelNamespaceScope,
    namespaceResult, scope = tools.topLevelScope,
    currentClass = null;
  (stdout.write(tools.valueFactory.createInteger(21).coerceToString().getNative()), tools.valueFactory.createInteger(1));
  return tools.valueFactory.createInteger(101);
  return tools.valueFactory.createNull();
})

//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsInNvdXJjZXNDb250ZW50IjpbXX0=

At some point I'm planning for the transpiler to support optimisation passes for things like this, but for the time being I'd recommend just piping your bundle through UglifyJS as that should remove extra code like the return <null> above as part of its "dead code elimination" stage.

Cheers!

phpengine commented 6 years ago

Hi @asmblah , the fix you described works smoothly, and is the same as for the Production Settings task. I'm happy for you to close this one, Thanks Dude!

IngwiePhoenix commented 6 years ago

Ohh, I didn't actually know this would happen. Good to know! =)

asmblah commented 6 years ago

Hi @phpengine - perfect, glad to know it's sorted for you 👍