Hacker News new | past | comments | ask | show | jobs | submit login
PHP-Snow - A concise, dry and beautiful language that compiles to PHP (code.google.com)
90 points by dyscrete on March 25, 2012 | hide | past | favorite | 94 comments



I have seen many PHP improvement proposals over the years. I am really glad people are doing such things. But I would like to address something that seems a bit wrong-headed to me, that is common to many of these proposals.

PHP is a verbose language, it is known. It is not a bug, it is a feature. Yes, some languages like to make their source code look like it was gzip-compressed, and have one or two-character symbols for everything. PHP is not among those, and I don't see how writing "fn" instead of "function" really helps. Are you so lazy as to type "function"? Get a decent completing editor, it'll do it for you. But code saying "protected function sayHello()" is much better for everybody that one saying "pr fn sH()". Same goes for syntax like "!_->" - it looks like cartoon "expletive deleted" sequence, not like a readable code. PHP is not APL, it should be obvious to a reasonably knowledgeable person what goes on there.

The idea of space-as-syntax, the most known implementation of which is of course Python, has its advantages and disadvantages. I admire the cleanness of good python code, and and the same time I am greatly annoyed when I have my code break because there's some space instead of tab or tab instead of space or extra space somewhere where it is not obvious. But I'd be interested to see people try out "PHP with Python indentation syntax" and see how it works for them. I don't see it a big difference but would be an interesting idea to play with.


  and the same time I am greatly annoyed when I have my code break because there's some space instead of tab or tab instead of space or extra space somewhere where it is not obvious.
I have to say, I love this. I often do website work for clients and it's so incongruent, that switching over to Python where the indentation is perfect every time is like programming from a cloud. Or some better analogy that means "it's nice".


WOW, I'm on hackernews, wow! I completely agree on not shortening array, object, private, public, etc. I reached a similar decision a while ago, but didn't get around to fixing the docs.

I like shortening fn though, as it often makes the difference if an expression containing an anonymous function can fit on one 80 character line or not.

About the "!_->" syntax in the validation part of the function definition. Recently I've decided to remove the entire validation part, because the syntax is too specific and weird. I still like the defining of arguments on top of the function because it removes duplicate argument names between docblocks and code. The idea of validation together with the argument defintion is still sound i think though.


Perhaps function should be allowed in both long and short form. I might be willing to use fn for an anonymous function but much less likely in regular situations.


"I am greatly annoyed when I have my code break because there's some space instead of tab or tab instead of space or extra space somewhere where it is not obvious."

A good editor will show you that too.


I don't know if I'm the only one, but I hate with passion this trend to remove syntax from a language and call it an improvement. It may be easier to code, but the code you produce is often more cryptic and harder to maintain. The aspect of the maintainability of a language is often disregarded even tough it's a very important aspect. That project is a very good example of this. Sacrificing readability for a few keystroke is never a good trade-off.


Personally, I completely agree. Code is written once and read often, so when working with any codebase where contributors > 1, readability should win over writability every time.

This should not be an argument against language constructs which make languages more expressive, but there seems to be a trend where as languages move toward the functional end of the spectrum, they take on more and more terse and cryptic syntactical structures.

I've always felt that good code should read like a book. This can be reconciled with prefix notation, but not with overloading odd characters as operators.


Isn't the aim here to improve readability?


By which measure is

    <- 2
easier to read than

    return 2
There are many more examples in the code, but I generally found the PHP code MUCH easier to read, and I don't know PHP very well. It could be that I'm biased towards C-like languages, but I doubt it; words are a lot easier to read than arbitrary symbols.


I've never written a line of php code in my life but on my current project I was asked to port some code from my client's php server api to native Obj-C running in an app. I had no trouble reading the php code and had the port working in under a day.


The original reason for "<-" was to have it implement a "inner return", that should be "<--". Now I think there should only be one return type, but "<-" still looks ok to me as it points the value back as trying to "return" it :)


I wouldn't have blinked if it was:

  ^ 2
since that is what is used in Smalltalk, but the left arrow makes me think I am missing what it should point to.


In ruby you could just write

  2
assuming you're at the end of a function. Coffeescript is the same iirc.


If it is, it isn't working.


With a passion? Kind of over the top don't you think? Snow is just a tool like php is just a tool. We're all programmers just trying to make development easier for ourselves and hopefully others. I don't know how anyone can hate any aspect of programming with a passion. It's our modus to find things we dislike and we write tools to prevent us from ever having to do them again.


What I hate is the trend to overlook maintability of the code just to get something that will take less keystroke to write.

People are creating new language in good faith and they want their language to look nice. I don't think anyone can disagree on that. The problem is that the aspect of the maintability of the code is overlooked in the process of the creation. When you overlook this aspect it may not hurt you in the short term, but it hurts in the long term. It may be nice for you to code something in a way now, but everyone that will have to maintain your code may not find it nice to read.


I think the reason this is getting negative/poor feedback is because the SAT analogy does not hold - Snow:PHP::CoffeeScript:JavaScript

JavaScript is a great language with debatable syntax. CoffeeScript works because it clarifies the beauty in the language. Snow doesn't do this for PHP because there isn't much beauty underlying the syntax to begin with.


That could be true.

But the real reasons I use Coffee script are the features it adds to the language: list comprehensions, splats, existential operator, severely concise class syntax.

And I don't see this offering any features that are as useful as those. The Snow code looks uglier, I think, than the PHP code. But if it looked uglier and gave me extra features (like, for instance, splats, comprihensions, improved slicing and range syntax, etc), I'd still probably use it.


The whole journey of trying to "fix" PHP has indeed seemed difficult. Mostly because so much information is pushed to the syntax of the language. Where in python the "." operator is used both to designate namespace, calling methods and calling "static" methods, PHP has three different operators "\", "->" and "::". Has it been worth it? Personally: A big yes, thinking about languages is fun. Practically: When it's complete, I think I will like it better than PHP, but still prefer a lot of other scripting languages like Coffescript, Lua, Python, etc.


> PHP ... there isn't much beauty underlying the syntax

I disagree. To each his own, I suppose. PHP inherited it's syntax structure from C, the language it's written in. Would you say that C is ugly?


While I don't rail against this kind of thing instinctively, I really do have to ask, is:

  pri fn render_row(row)
really that much better than

  private function render_row($row) {

?


I get abbreviating function to fn since the import part is the name, it is very common, and a lot of languages do it. I think abbreviating private is a mistake. It is important in itself and should have attention called to it.


I completely agree, will change all the pri, pub, arr, etc. to private, public, array, etc.


Speaking of readability: Just `pri` as the constructor? When having just a quick glance at code I want to know which part does what. Function names help, even if it is __construct.

And the @str title=null line above the class seems very odd.


pri's not a constructor in this language's terms, it's just a visibility operator. The language wants you to be able to use code in your class member assignment statements; if that means it has to generate a constructor to make it happen, it will. Or maybe it just wants you to start coding without fussing with boilerplate.

And the @str title=null line above the class seems very odd.

This is great because you can indent code under it that's relevant to it, that would normally end up cluttering your function's narrative up with housekeeping for variables.

This is a much more pleasant way to deal with PHP. Check out the documentation, it is outstanding. http://code.google.com/p/php-snow/wiki/Class


I'm not sure I understand your comment - the function name in this case is "render_row()", and "pri" refers to the visibility of the function.

I don't feel that it's more readable, or even easier to write, as "pri", though.


pri is used first for the constructor (right after class SumTable) but not followed by any name. I find it quite hard to read this way.


Ah - I missed that entirely, thanks for pointing it out again. That line may just win the prize for least-clear line in the Snow example.


I thought it was a typeo


As something of a glorified preprocessor, there is a limit to how much it can "make the language better". However, they will probably be able to get a bit of hacker mileage out of code generation, and I can see how you could add features which would be handy (such as first-class anonymous functions; though good luck making that look like "idiomatic PHP code"). It is too bad, however, that they didn't decide to make HTML tags first-class entities in the language; although, of course, this is all vaporware at this point.

Anyone who is interested in new languages specifically designed for web programming should also check out: http://www.impredicative.com/ur/


>I can see how you could add features which would be handy (such as first-class anonymous functions; though good luck making that look like "idiomatic PHP code")

PHP added anonymous functions in 5.3.

http://php.net/manual/en/functions.anonymous.php


PHP has native first class anonymous functions now, so there is no reason snow can't do a good job converting them.


Thanks for the Ur link. But seriously, 2 clicks to get to a page (docs > tutorial intro) just to see a code sample?


Strip the comments from the PHP code and there isn't a drastic difference in size (as the snow example lacks comments), other than that, the PHP example is more readable. /shrugs


Snow: 33 Lines

PHP: 66 Lines

- w/o PHPDoc: 45 Lines

-- w/ Single-line foreaches, exceptions, and ternary operators: 34 Lines

So if we use the same formatting, the PHP is only one line longer, and 5 of the lines are just end-braces.

Now, taking my condensed PHP, and the Snow code, and converting 4 spaces to a tab, the filesizes are:

Snow: 746b

PHP: 847b

Using a lazy comparison: 12% less code, roughly the same number of lines.

I'm with you - I don't see how using a completely different syntax & complicating your toolchain is worth it to save a handful of characters when typing. Maybe more example code (2k-3k lines) would help.


Here's a side by side comparison without comments:

http://cl.ly/3Z3l1w0v2I2n2y231Y09/o

That's 10 lines more. 100 times more readable.


Well actually 15, as it seems fair to remove the comments in Snow too. About it being readable, I think that has a lot to do with experience. For me the Snow version is clear as day ;)


Well the comments in Snow are kinda necessary, since it's all abbreviated and hard to read. The PHP class in the other hand is a lot clearer, with informative class and function names.


@arr pri fn [!_->empty:

uhm, beautiful


Depends on the languages you're familiar with... fn is common in some areas, _ is a popular "default variable", -> I see as an interesting addition although it would be equivalent to empty(_).

What I'm not sure about is @arr (why not @array?) and [] instead of {} for a map...

I'm not sure if it's beautiful, but it's definitely an interesting shortcut for common operations and I could immediately see why it's useful and already remember the syntax for it. I like it and the author seems to like it too, not everyone has to agree of course ;)


  [] instead of {} for a map
PHP uses [] for both list and map types.

I don't think there's any difference between the two types in PHP. All lists are maps.


But we're talking syntax, not behavior. There's no reason they couldn't use {} to indicate maps and [] to indicate lists, even if they're the same data type. The point of this language is to be a cleaner syntax on top of PHP, so syntactical sugar like that is a Good Thing (TM).


Beauty is in the eye of the beholder. In mine it look a little bit odd as well, but I could imagine that it's better than PHP if you are used to it.


Can we start talking about this trend of people referring to their own work as beautiful? It seems kindof tasteless to me, am I alone here?


But if you don't call your work Beautiful how will people know you have Taste? When you're Intelligent and Creative you just have to show it.


I personally don't like the shortening of words. Having a long word doesn't really hurt readability.


I think Php is concise enough. Sory for being harsh but this looks like evil twin of Perl.


IMHO, you're trying too hard to fix the things which aren't broken in the first place. Covering the main flaws in PHP would be sufficient, e.g.

    str = 'foo'.replace('#', '').substr(1).as_array();
    int = 5.something();
would translate to

    $str = 'foo';
    $str = str_replace('#', '', $str);
    $str = substr($str, 1);
    $str = (array) $str;
    
    $int = 5;
    $int = something($int);
This would allow us to do things that aren't native to PHP but still have something much easier. Having strings, integers and other types used as objects (with a solid proxy syntax to the native functions) would be the first (and best) step forward.

Class definitions as well:

    Foo {
        // constants 
        BAR = 'fubar',
        BAR2 = 'foo';
        
        // properties
        protected _bar, _fubar;
    
        // public properties / methods
        public
        bar() {
            return ._bar;
        },
        fubar() {
            return ._bar + ._fubar;
        }
    }


I've said it once and I'll say it again: if you're going to compile down to a language, support macros. CoffeeScript tries to make Javascript better, but I personally prefer Javascript's syntax. That's not to say CS doesn't have its benefits for many people, but one of the only things missing from Javascript is macros, so CS is pretty much worthless to me.

After spending countless hours in lisp and javascript, php leaves a lot to be desired. One of the things I do not desire is a language of equal power with a completely different syntax. Syntax is meaningless if it doesn't allow greater power.

Honestly, it's bad enough that CoffeeScript is so prevalent. I understand why it's around and why people like it, but I don't prefer it to pure JS...and I'd rather the trend not spread to other languages.

One possible candidate would be Pharen, though: http://scriptor.github.com/pharen/.


How long before people start writing compilers that pre-compile the pre-compiliers?


That would be pointless in most cases, whereas the history of computing has pretty well established that preprocessors are useful.


So true...


What would be cooler is to use something like this as a basis to generate idiomatic php, python, perl or ruby. Let people sketch out their initial ideas in a common language, then compile in to a starter php project, or python project, etc.


Nice idea. Still a bit rough around the edges maybe? This certainly doesn't look as pure as snow:

    [!_->empty: "$row cannot be empty."]
Good luck anyway!


Nope that is way too magic. It will go away. :)


Honestly I fail to see a more readable thing, having experience with PHP it is really hard to me to read the snow code. A lot of the syntax just doesnt make sense to me.

There is also another thing that annoys me, the significant whitespaces, that is something I do not like in python (while I like the rest of it, the indentation instead of brackets is annoying), yes I agree that indented code is more readable, and I like to read indented but I like to write my code without caring for indentation and fix it after it is doing what I want (read: tell my IDE to indent it, brackets help on that). The replacement of .= for %= is just added confusion there is really no gain, and the return for <- seems just wrong looks like just a way to avoid using characters. Dropping the semicolons doesnt make much difference to me, but being used to them it could be a problem, when writing in languages that dont require them I write them on habit leading to a long list of syntax errors.

Warning personal rant: Why do people hate java like syntax and brackets WHYYYYYYYYYY? Whats wrong with brackets honestly???

Sorry just had to say that.


PHP as assembly language?

PHP does have a big advantage, it's unbiquity on low-cost web hosts that no other language can match. The downside is having to deal with PHP itself.

I'd like a platform of PHP-done-right but compiles to a set of .php files I can deploy to any webhost. I don't think this new language is it, but I'm happy to see developments.


This is outdated, I can find you a handful of hosts that offer Perl, Python and Ruby for under five bucks a month.


Sure, they exist, but these other languages have nowhere near the ubiquity of PHP in the economy webhosting world. PHP devs have plenty of choices.

Is your webhost's DNS/email/DB service just not quite what you need? PHP devs can take their pick of a very wide selection of competing services.


Please back up what you're saying with some proof. As I said, PHP is no longer the most ubiquitous economy hosting language.


This is syntactic sugar at best; other languages such as Python are cleaner and are more performant. Facebook's efforts to compile PHP to C++, HipHop, demonstrate this need, and in my opinion, this project is a step in the wrong direction.

PHP was great for its time, but sometimes you have to let grandpa go.


Sometimes you're stuck with large PHP codebases.


very true, though how would this project help? A major rewrite would have to be done with PHP-Snow just as much as another language.


If you were adding to the codebase, you could write the code using Snow. You could also rewrite select portions that you regularly need to work on, as opposed to having to port the entire codebase to another language.


Again, what is the advantage to be gained by simply reducing syntax? Programming efficiency? Saving a few key strokes?

Your suggested approach would certainly add more drag for little gain for programming teams.

Developers would be better served optimizing performance, not messing around with simplifying syntax. For that reason, HipHop a worthwhile addition to the PHP canon; this not at all.


Reducing syntax noise can theoretically make code easier to read and write. I personally don't go for that approach, but others swear by it and if it increases their productivity and makes them happier then that's a good thing.

Optimizing performance and making writing/managing code easier are two different problems and not mutually exclusive. Code written in Snow can then be optimized with HipHop.


I am genuinely perplexed by the fact that you don't seem to realize syntax is not just what you write, it's also what you read. Anything that makes code easier to read and understand is a win.

Python is just as "worthless" as Snow by the metric you're espousing here, because the benefits of Python over well-optimized C are in simplicity of reading and writing, not runtime performance.


Yay, another language!


indeed :) Competition breeds innovation, competition breeds excellence!


php as a target platform huhu, btw there was already php-reboot.

php reason to be is hosting + ecosystem, not linguistic qualities, too late for that.


I guess beauty lies in the eye of the beholder.


i value conciseness, but clarity matters more. i guess that's why the longer i code, the longer my variable names become.


Here's something constructive for all the haters. Snow is open source, seems with such a consensus it should be easy to get some people together and hack on a fork of snow that is more appealing to the masses. Or does the current PHP syntax leave nothing to be desired?


not as pretty as ruby or coffee-script :P


yay let's copy ruby and python!


How can anyone call this beautiful? o.O


why? do php to native c do very simple language to native c


As I said on twitter, someone finally managed to write a more pointless and retarded abstraction than HAML.

Bravo, for all the _wrong_ reasons.


This might be a nice replacement for PHP spaghetti code you might see everywhere - see the recent HN thread where PHP is voted the most-hated language - it's because even solid coders produce spaghetti code with it. You need to be really disciplined to create something that's easily maintainable.

I would not touch PHP codebase without a framework. Some nice PHP frameworks have emerged in past few years ranging from simplest CodeIgniter to pretty complete Yii I use for most projects now. I would never choose to use PHP for a project without Yii or a similar framework, so until we see a quality framework written in PHPSnow, I don't see any reason to use it.


> it's because even solid coders produce spaghetti code with it.

That's ridiculous -- PHP is pretty analogous to most languages in terms of both capability and syntax. The biggest warts in PHP revolve around the standard library and that wouldn't prevent anyone from producing solid code.


Why couldn't you use an existing PHP framework from PHPSnow?


Take Yii for example. Beside framework functionality, the power of rapid development comes from Gii code-generation tool and it generates PHP code (complete MVC for CRUD + admin. interface based on database tables or PHP class). You get skeleton structure that you need to fill in with your business logic (and put some design into views, but that's not really a problem here).

Everything that Gii does, you would have to write manually using PHPSnow. Doing that manually is slow and error prone.

Besides, using MVC framework makes the PHP code clean and maintainable, which are two real problems with PHP. Writing $this-> is a minor nuisance, but I hardly believe it warrants inventing a new language. If PHP is just ugly to you, why use it at all? There's Python, Ruby, whatever...


then again PHP is arguably a framework itself and when dealing with something either very simple or very complex Yii feels to verbose.


So much criticism... As usual the php community is resisting any change. I think what you are doing has a lot of merit. Your DSL just needs some polish.

What I like:

- The new return "<-"

What I think should change:

- The concatenating assignment operator "%=" shouldn't change. It should stay the same ".="

- Accessing instance variables/methods should be by using '@' rather than '.' as that is becoming an implied standard and php folk are already used to using '.' for string concatenation.

- The setting of parameter types and defaults on methods is too heavy and not what people expect. I would put them back into method declaration.

  eg. 
  @str title=null
  class

  # To become
  class
  fn constructor(str @title = null)

  As @ would be the way to access instance variables what this means is the instance variable of title would be assigned the value that gets passed through the constructor.

  # This is too much magic imo  
  @arr row
    # List of integers.
    [!_->empty: "$row cannot be empty."]
  fn add_row(row)

  # it should be something like this:
  fn add_row(arr row)
    !"$row cannot be empty." if row->empty

    
- This doesn't make a lot of sense:

  for row in .rows
    html %= "<table>" | .render_row(row) | "</table>"

  # I would prefer something like:
  html .= @render_row(row) for row in @rows
  html = "<table>{html}</table>"

Good work on what you have already achieved, with a bit of extra polish I think Snow can become very desirable.


> So much criticism... As usual the php community is resisting any change.

This grinds my gears on a few levels - I really don't feel as though the reaction here is a resistance to change, as much as it is a resistance to completely redefining pretty much all of the core language constructs.

The Snow code is, in my eyes, almost completely unreadable, due to a seemingly random collection of characters.

I'm a PHP developer, and while I appreciate that (at times) PHP can be quite verbose, introducing such sweeping changes really doesn't make any sense to me. The add_row() function in particular is mind-bending for me. Auto-declaration (and initialisation, within a loop, no less) can only hurt in larger systems - which is why developing with notices enabled is such a plus.


I didn't say Snow was perfect. Far from it. Didn't you see my long list of feedback?

I get annoyed with the php community because this thread embodies what a typical response from them is like. Criticize anyone trying to do something new by saying the old ways are best without giving any constructive feedback.

Also note. No one has to use Snow if they don't want to. These are not changes to the core of php, so it confuses me why people get so militant over the suggestion of a DSL for php.


I did indeed see your feedback, but it was the opening comment that framed the feedback, that bothered me most.

As for your feedback itself - your own suggestions don't appear to improve readability in any meaningful way, mainly because the underlying example is simply so unreadable already.

I'm perfectly happy to debate potential layers above PHP to help with speedy development, but I'm also perfectly happy to argue against those that I don't believe have any promise.


So any criticism of this is the "PHP community resisting change" -- that's rather convenient. I suspect many of the people criticizing both this language and the approach here aren't even PHP programmers.


Thank you so, so, so much for actual constructive criticism!!!

> The concatenating assignment operator "%=" shouldn't change. It should stay the same ".="

The reason for using "%" was that I wanted to use "." for objects:

  instance.my_method()
I don't think "%" will be used as much due in Snow, due to the new "smart strings":

  "{a_variable} and {a_method()}"
> Accessing instance variables/methods should be by using '@' rather than '.' as that is becoming an > implied standard and php folk are already used to using '.' for string concatenation.

This looks weird, no:

  @instance@var@subvar@sub_method()
and what about accessing static vars and methods?

> The setting of parameter types and defaults on methods is too heavy and not what people expect. I would put them back into method declaration.

Yes it's heavy, but as you always need to have a docblock to write "acceptable" PHP code, I chose not to duplicate the argument names.

> This doesn't make a lot of sense.

No this should go, I decided that a couple of weeks too. But the problem its trying to solve is a real one. Your proposal looks good, but how would it work on a new variable?


"As usual the php community is resisting any change." This is obviously false statement. There were a lot of changes in PHP lately. However, PHP community is a huge community, millions strong, and it is natural that some people evaluate new things not only on coolness, but on practical and other criteria, and not everybody likes the changes - it would be very hard to produce a big change that is universally liked by millions (unless it has letter "i" in front, of course - so if you called it iSnow you'd have much better chance ;).

You should expect criticism and taking is by falsely accusing the whole huge community of "resisting any change" is exactly the wrong way to do it.


The only constructive comment in the thread has been sunk by downvotes. I don't know why people hate these pre-processors so much. Coffeescript threads always have a fair amount of people complaining although Coffeescript has been pretty successful.

I think the best part of the pre-processors is that it does not force the entire community to adopt the syntax and allows some to play with new language features.


Pre-processors start at -100 points -- the complexity of adding to the tool chain, the leaky abstractions, the extra difficulty in debugging, the fact you have to know two languages well to be effective, and so on. A pre-processor has to be really good and really clever to be worth the overhead.


The point is: if you don't like it you don't have to use it. PHP still stands in its current form. Snow may become popular with a minority of more adventurous devs and develop into something that you may want to use.


The fact that you don't have to use it means that it's beyond criticism? What point are you trying to make? You don't have to use PHP either.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: