Git Product home page Git Product logo

guts's Introduction

Guts

Build Status

Guts is a language makes your life easier, it allows you to write less code to produce equivalent PHP code.

Guts compiler is written in Go, Go is faster than PHP, thus the compilation is fast, and of course you can compile sources concurrently.

For more details, please check the docs for the language synopsis.

Guts aims to be

  • simple to learn.
  • easy to use.
  • fast compilation.
  • shorter code.
  • phpdoc friendly.

Build

Simply run make to produce the parser:

git clone http://github.com/c9s/gutscript
cd gutscript
source goenv
make

Synopsis

For more language details, please check the docs for the language synopsis.

class Person
    # Print the name
    say :: (name) -> "Hello #{name}, Good morning"

    getPhone :: -> "12345678"

    setName :: (string name) -> @name = name

if str =~ /[a-z]/
    say "matched!"

The above code compiles to:

class Person {
    /**
     * Print the name
     * 
     * @param mixed $name
     */
    function say($name) {
        return "Hello " . $name . ', Good morning';
    }

    function getPhone() {
        return "12345678";
    }

    /**
     * @param string $name
     */
    function setName($name) {
        $this->name = $name;
    }
}
if ( preg_match('[a-z]',$str) ) {
    echo "matched!";
}

File Extension

The file extension is named with "*.gs", the compiler compiles your .gs files to .php files.

Guts Language

To make guts compiler compatible with PHP, there are some syntax are simplified but the derived syntax shouldn't break the compiler.

(Move to separated doc file later)

Constant

Defining const can be done by the same syntax of PHP.

const VAR = 10;

Variable Definition

$foo = 'string'; // explicitly defined without type
var $foo = 'string'; // explicitly defined and  implicitly typed
int $foo = 10; // explicitly defined and explicitly typed
string $foo = "foo bar"; // explicitly defined and explicitly typed

Array

string[] $list = []; // define an array of string.

Array operations - map, reduce, filter

...

Map

string[string] $contacts = []; // define a map for string -> string
$contacts["foo"] = "bar";
$contacts[0] = "bar"; // compilation error

Control Structure

If

Foreach

While

Function

The keyword function is optional, not required.

foo(Type $foo, Type $bar) : ReturnType {

}

Class

The code below works

<?php
class Foo extends Bar implements DoorLocker {
}

But you can also write:

<?php
class Foo is Bar does DoorLocker {

}

The inheritance syntax was derived from Perl6, see https://doc.perl6.org/language/objects#Inheritance for more details.

Class Property

Class Method

PHP method syntax still works in guts:

class Buffer {
    public function write($string) { ... }
}

However you can also do:

class Buffer {
    public write($string) : bool { ... }
}

The function keyword can be ignored.

To override a parent method, you can add a keyword "override" to explicitly define the override method.

class EncodedBuffer is Buffer {
    override public write($string) : bool { ... }
}

When -Wmethod-implicitly-override option is enabled, method overriding without override keyword will throw out the warning messages:

Traits

...

Namespace

Defining namespace is as the same as PHP:

namespace foo\bar;

Roadmap

  • Implement a parser that parses PHP5.3
  • Getter generator

Implementation

Guts uses Go yacc parser generator to generate a LALR(1) parser.

To add new syntax, please checkout the parser.y file, which is located in src/gutscript/parser.y

The lexer uses concurrent strategy to parse tokens, the state machine runs in another goroutine, so the parser receives the tokens from lexer through the channel concurrently.

Codegen is expected to be a separated tree structure traverser, and which is not implemented inside the ast node structure like the coffee-script codegen. So the code generator can be PHP code generator, LLVM bit-code generator or JavaScript generator.

Basic optimization is on the roadmap. Optimizer uses tree-pattern matching strategy to traverse the IR structure. 2 basic optimizations are in the plan -- constant folding and dead code elimination.

Current State

Not ready for production. this project is still in alpha stage. but I'd like to recevie comments, patches and feature requests.

Contribution

Feature requests, pull requests, comments are welcomed, but please discuss first on our GitHub issue. Just feel free to drop a line there.

Development

First, go get a workable go compiler at http://golang.org

Run the below command to setup GOPATH:

source goenv

Run make to build and test:

make

If you modified the grammar, remember to update the parser:

make parser

Run test cases:

make test

To dump lex tokens:

go run utils/lexdump/main.go src/gutscript/tests/09_class_properties.guts

Test the command tool with test case:

./bin/guts src/gutscript/tests/03_if_else_statement.guts

Grammar Rules

| Rule                

--- | ------------------- x | assignment statement x | if statement x | if else statement x | if elseif else statement x | function statement x | function param list x | empty class x | class with properties x | class with methods x | function call as expr o | string concatenation o | list structure o | hash structure o | for block o | dot range o | static method call o | method call as expr. o | assignment from method call o | namespace design o | map

Author

Yo-An Lin ([email protected])

IRC Channel

Join us on irc.freenode.net #gutscript

License

MIT License Copyright (c) 2012 Yo-An Lin

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

guts's People

Contributors

c9s avatar ciarand avatar harlantwood avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

guts's Issues

Syntax and CoffeeScript

Hey there,

instead of inventing yet another syntax, couldn't it be possible to re-use coffeescript's syntax ?

edit: just noticed last commit was 3 months ago, guess the project's dead anyway

php5 compliance

  • namespace
  • class
    • abstract
    • extends
    • implements
    • method
    • property
    • scope
    • type hinting
  • interface
  • function

Proposal: Syntax

Would it be possible to have a syntax like this on future versions?

namespace Universe\World\LivingThings
  class Specie
    protected $soul

  class Human extends Specie
    private $name
    private $age
    __construct: ($name, $age) ->
      @$name = $name
      @$age = $age
      @$soul = 'some soul'
      @breathe()
    private breathe: -> echo 'breathing'
    protected blink: -> echo 'blinking'
    protected @think: -> echo 'thinking'

  final class Person extends Human
    __construct: ($name, $age) ->
      parent::__construct $name, $age
      parent::blink()
      @blink()
      Human::think()
      self::hair()
      static::hair()
    protected blink: -> echo 'also blinking'
    protected @hair: -> echo 'long'
    public greet: -> 'hello world'
    public @something: -> new \Universe\World\Things\Something()

namespace Universe\World\Things
  use Universe\World\SomeOtherThings\Another as AnotherThing
  final class Something
    public anotherThing: -> new AnotherThing()

namespace Universe\World\SomeOtherThings
  final class Another

use Universe\World\LivingThings\Person
echo (new Person('joe', 21))->greet()
print_r Human::something()->anotherThing()

LIKE operator for preg_match

if str like /([a-z])/ into matches
   orig = matches[0]
   p     = matches[1]

And compiles to:

if ( preg_match("([a-z])", $str, $matches ) {
    $orig = $matches[0];
}

regex literal, ideas from Cindy

Cindy said:

有打算在字串或 regex 的 literal 裡面能塞複雜的 expression 嗎?
像是 perl 的 "... @{[ sin 5 ]}..." 或 ruby 的 "... #{ sine 5 } ... "

我記得在 C 裡面因為字串很單純, 頂多就 \ 能 escape 一個字, 所以 C 的 string literal 可以用 lexer 就認得出來
如果裡面還能塞 expression 的話, regex 就認不了了

(這邊的 regex 指的是 lexer ^^|)
就要寫入 context free grammar 裡面

javascript 的字串或 regex 都沒有變數 interpolation, 事情有簡化一點
perl 因為有 interpolation, 而且直接就塞簡單變數, 不需要 #{ }, 所以有 ambiguity 需要投票
/...$a[12].../ 可以解讀為 $a 的內容, 然後 [12] 或是 $a 陣列的 [12] 這個元素
嗯, 如果可以統一定成... 一定會 greedy
往後延伸, 或是一定要 #{$a[12]} 都可以避開 ambiguity
覺得 ruby (也是 coffeescript) 的 interpolation 比較好做. 雖然就總是要多寫 #{...}
用簡單變數的時候反而比原生 php 還長.. 不過 php 一整個是在亂做 orz

啊我看你的設計裡面變數什麼的好像都沒有 prefix, 那就不用煩惱這種事了, 反正一定不能用 php / perl 這種簡易 interpolate

那用 #{...} 好了, 這樣設計的語言還不少, 用起來比較熟悉...
ruby, coffeescript, sass 都是 #{...}
php 的 regex 是用函數做的, 而且主流有兩種.... (聽說全世界主流 regex 也就這兩種 XD) 如果不要做 =~ 而只有做 regex 的 literal 的話, 好處是比較靈活能套來路不明的 regex engine
如果做了 =~ 就相當於釘死要用哪一套了

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.