Giter Club home page Giter Club logo

haxe's People

Contributors

aduros avatar andyli avatar atry avatar aurel300 avatar basro avatar bendmorris avatar cedx avatar deltaluca avatar fponticelli avatar frabbit avatar gama11 avatar haxiomic avatar herschel avatar hexonaut avatar hughsando avatar jdonaldson avatar kevinresol avatar klabz avatar mandel59 avatar markknol avatar mockey avatar nadako avatar ncannasse avatar peyty avatar pperidont avatar realyuniquename avatar simn avatar smerkyg avatar vonagam avatar waneck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

Forkers

hughsando

haxe's Issues

Pass by reference type

Implemented for function arguments only in 829e225

In some instances there's a need to pass a value by reference (it's needed to implement some array methods).
It might be interesting to allow something like this:

function test(v: Reference<String>): Reference<String> {
  return v;
}

To compile to:

function &test(&$v) {
  return $v;
}

Or alternatively use metadata to achieve the same.

@:reference function test(@:reference v: String): String {
  return v;
}

untyped magic

As I wrote before, I remember @Simn was not so happy with untyped __php__ and the like.
@Simn: Are there better ways to handle this, maybe already implemented in the newer generators (python, lua)?

cannot compile

File "src/generators/genphp7.ml", line 782, characters 50-57:
Error: Unbound value __POS__
make: *** [src/generators/genphp7.cmx] Error 2

NativeStructArray

Just wanted to write down my ideas on associative arrays. Not sure if it makes sense to implement this right away or if it makes sense at all.

From my POV associative arrays in PHP are often used in places where you would use an anonymous structure in Haxe, e.g. in option parameters for functions. There are many named fields (often optional) with a value of a certain type. So it makes sense to me to be able to define their type as a struct, e.g.:

typedef Options = {
  opt1:Int,
  ?opt2:String,
  opt3:Bool
}
var opts:NativeAssocArray<Options> = {opt1: 1, opt3: true};

IMO being able to define such structs and have the compiler check them is a huge benefit when interfacing with native PHP functions.
Checking the type would be basically be checking if the type param unifies with the assigned value, no? I wrote a macro once which does something like this.
Of course it would be good to generate a native array for literals like this:
['opt1' => 1, 'opt3' => true]
without going over objects. But I saw that you generate structs like this already (and just cast them to (object).

One open question is how to make a difference to map-like arrays with "dynamic" keys, like in Haxe this would be Map<String,Option>. Maybe one could misuse T:, like NativeAssocArray<T:Options> or maybe better define an additonal type like NativeStruct<T> for these struct-like arrays?

Implemented in HaxeFoundation@395b870

Calls to callback properties

Haxe

class Test {
  static var staticCallback : Void->Void;
  var callback : Void->Void;

  static function main() {
    var t = new Test();
    t.callback();
    Test.staticCallback();
  }

  function new () {}
}

PHP

($t->callback)();
(Test::$staticCallback)();

Call Boot initialization in each loaded class

Add a call to Boot initialization method to make explicit call to that method optional.
This will allow external code to use Haxe-generated one without the need to consider the specifics of Haxe-generated code.

Extracting tweets through Flume

i am tryiing to extract twitter data through flume and getting this error

2016-08-13 17:21:12,945 (conf-file-poller-0) [ERROR - org.apache.flume.node.Poll ingPropertiesFileConfigurationProvider$FileWatcherRunnable.run(PollingProperties FileConfigurationProvider.java:149)] Unhandled error
java.lang.AssertionError: java.lang.reflect.InvocationTargetException
at twitter4j.HttpClientFactory.getInstance(HttpClientFactory.java:81)
at twitter4j.TwitterStreamImpl.(TwitterStreamImpl.java:51)
at twitter4j.TwitterStreamFactory.(TwitterStreamFactory.java:40)
at org.apache.flume.source.twitter.TwitterSource.configure(TwitterSource .java:115)
at org.apache.flume.conf.Configurables.configure(Configurables.java:41)
at org.apache.flume.node.AbstractConfigurationProvider.loadSources(Abstr actConfigurationProvider.java:326)
at org.apache.flume.node.AbstractConfigurationProvider.getConfiguration( AbstractConfigurationProvider.java:97)
at org.apache.flume.node.PollingPropertiesFileConfigurationProvider$File WatcherRunnable.run(PollingPropertiesFileConfigurationProvider.java:140)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:51 1)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask. access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask. run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor. java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor .java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct orAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC onstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at twitter4j.HttpClientFactory.getInstance(HttpClientFactory.java:73)
... 14 more
Caused by: java.lang.NoSuchMethodError: twitter4j.conf.Configuration.getHttpClie ntConfiguration()Ltwitter4j/HttpClientConfiguration;
at twitter4j.StreamingReadTimeoutConfiguration.isGZIPEnabled(TwitterStre amImpl.java:804)
at twitter4j.HttpClientBase.(HttpClientBase.java:25)
at twitter4j.HttpClientImpl.(HttpClientImpl.java:55)
... 19 more

Global constants groupped in abstracts

Copied from #12 (comment)

@:phpGlobal
@:phpConstants("\\SOAP_SSL_METHOD_")
@:enum extern abstract SoapSslMethod(Int) {
  var TLS;
  var SSLv2;
  var SSLv3;
  var SSLv23;
}

Magic constants:

@:phpGlobal
@:phpConstants
extern class MagicConstant {
  @:native("__FUNCTION__")
  static var FUNCTION:String;
 ...
}

super => parent

Haxe Php
super() parent::__construct()
super.method() parent::method()

Rename things which has names conflicting with PHP

  • Generated class names not use PHP keywords;
  • Methods of classes in global namespace should not use the same name as class name unless those classes have real constructor defined.

Everything which starts with $ is allowed to use keywords

As of PHP 7.0.0 these keywords are allowed as as property, constant, and method names of classes, interfaces and traits, except that class may not be used as constant name.

So the task is:

  • Rename class names which are keywords;
  • Force constructor generation on each class;

Implemented in fab542b, 5e764ac, 6d19162, 5b8f2a3

FEnum field access

Example

enum ETest {
    A;
    B(i:Int);
}

ETest.A; //FEnum
ETest.B; //FEnum
B; //FEnum
B(1); //FEnum

optional function parameters

Do you handle optional function parameters in genphp7 or is this handles elsewhere?
There are these auto-generated nulls for missing parameters that are not so good for PHP.

Rename methods with the same name as their class, keywords.

Methods which have the same name as the class they're defined in should be renamed to prevent php from seeing them as the constructor.

I just compiled something like this:

class Main {
    public static function main()
        trace('hello world');
}

Which results in:

PHP Fatal error:  Constructor Main::main() cannot be static in .../Main.php on line 18

This is only relevant for non-namespaced classes in the top package:

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

UTF-8 aware String functions

Another thing that bothered me quite often is that the string functions in the old std lib are not utf8-aware (in contrary to other targets). From what I've read UTF-8 is more or less the default now in PHP (have to check this) Maybe it would be good to use mbstring and the like in std lib?

Global functions

As for global functions my thought is it's better to place them all in a single extern class like Global so that users with PHP background always know where to search for API of such function.

I'd prefer to have them separated, because they are just too numerous. I thought the way it is done in the reference could be adopted somehow:
http://php.net/manual/en/funcref.php
But I don't mind really. I can always add some aliases for me :-)
Do you want to keep the original PHP names then, like array_filter?

Enums

Haxe

enum Some {
    var One;
    var Two(arg:String);
}

PHP

final class Some extends Enum {
    //Need to somehow provide a list of enum constructors for further implementation of `haxe.EnumTools`
    static protected $constructors = ['One', 'Two'];

    //Enum constructors without arguments become singletones
    static private $_One;


    static public function One () {
        if (!self::$_One) {            
            self::$_One = new self(__FUNCTION__, []); //__construct is implemented in Enum class
        }
        return self::$_One
    }  


    static public function Two ($arguments) {
        return new self(__FUNCTION__, $arguments);
    }
}

Also

enum E {
    A;
}

class Test {
    static function main() {
        trace(Std.is(E, Enum)); //true
        trace(Std.is(A, E));    //true    
        trace(Std.is(A, Enum)); //false
    }
}

Implemented in 67ef0e8 and 4b3da3a as proposed above

FClosure field access

Example source

class Test {
    function new() {}
    function some() {}

    static function main() {
        var t = new Test();
        trace(t.some); //FClosure

        var o:{function some():Void;} = null;
        trace(o.some); //FClosure
    }
}

Closures

Haxe

var notUsedInClosure = 123;
var used = "world";

return function () {
    this.hello(used);
}

PHP

$notUsedInClosure = 123;
$used = "world";

return function () use (&$used) {
    $this->hello($used);
};

Anonymous functions
Support of this in closures requires at least PHP 5.4.

Implemented in adff433 and e9f152e

type hints

Did you consider adding type hints to php output?

Traits

Since PHP has traits we need an ability to specify that an extern class extends multiple classes so that compiller won't complain in such cases:

var q = new ExternClassUsingTrait1AndTrait2();

fn1 (q);  //q is of type Trait1
fn2 (q);  //but it is also Trait2

function fn1 (a:Trait1) {...}
function fn2 (a:Trait2) {...}

Perhaps in externs traits should be represented as interfaces.

Note: class can have two traits with the same method name, but different signature.

NativeArray

:@:coreType @:runtimeValue NativeArray {
@:arrayAccess function get (key:Dynamic);

Now, that's pretty close to my implementation, only @:coreType and @:arrayAccess don't seem to work ATM: HaxeFoundation#5525

For the time being I'd suggest:

abstract NatveArray(Dynamic) {
  @:arrayAccess inline function get<T>(key:EitherType<Int,String>):T
    return this[key];
  @:arrayAccess inline function set<T>(key:EitherType<Int,String>, val:T)
    this[key] = val;
}

Note that an array key can only be int or string, also I think T is always better than Dynamic.
And I'd like to add some array functions to the abstract, like public inline function count.

abstract NativeArrayNum(NativeArray)

I don't like Num here. How about NativeAssocArray and NativeIndexedArray as names?

Implemented in 09f84aa

PSR-4 / PSR-1 Compliance

Hello,

This is just a suggestion, I'm not a compiler expert - you be the judge of the pertinence of the issue!

Would it be a good idea to make sure that the generated PHP sources are PSR-4 compliant ( http://www.php-fig.org/psr/psr-4/ )? This could increase interoperability between Haxe-generated code and "native" PHP code. I looked at the sample generated file here ( https://gist.github.com/RealyUniqueName/2dc44c3d7a5e1f02df71c3a8186e5f43#file-test-php ) and the namespace use seems correct. It would just be a matter of validating that the output folders are compliant. Being able to use a Haxe library in a native PHP project (and vice-versa) using a standard class loader would be fun.

Once this is tackled, other PSRs could be added in order to ease debugging and increase familiarity with existing PHP developers. For example, PSR-1 covers basic code style ( http://www.php-fig.org/psr/psr-1/ ). Whether or not this is pertinent in a compiled environment, I'm not sure. The code itself can violate certain style rules. But the compiler could be implemented in a way that, by itself, it doesn't introduce more inconsistencies than the actual compiled code does.

What do you think?

Anonymous classes

Should Haxe->PHP generator "keep in mind" that variable can contain an anonymous class instance?
Can anonymous classes somehow impact externs signatures or runtime?

Pass static method as value

Haxe

class Test {
  static function some () return 'hello';

  static function main () {
    return Test::some;
  }
}

PHP

class Test {
  static function some () {
    return 'hello';
  }

  static function main () {
    return function() { return Test::some(); };
  }
}

Approach has been changed in 5776b8d:

class Test {
  static function some () {
    return 'hello';
  }

  static function main () {
    return new HxClass(Test::class, 'some');
  }
}

Class<T> implementation

Right now Class<T> is generated as instances of special HxClass class (in 48a9d20).

Perhaps it should be changed to plain string which is simple, easy to maintain and has almost zero runtime cost. However strings can lead to confusions like this one:

var str = "\\some\\pack\\MyClass";
var d : Dynamic = str;

d.someMehod();
//Should this fail with "cannot call `someMethod()` on non-object"?
//Or is it ok to invoke static `\some\pack\MyClass::someMethod()` in such cases?

Also keep in mind that native php class names can contain / and @ chars (see examples output and Note section)

Implemented as HxClass in 48a9d20

Handle --php-prefix compiler flag

--php-prefix should be used as additional top-level namespace for generated app.
When --php-prefix is used there should be no Haxe-generated php code in root namespace.

Example usage: --php-prefix some.pack will generate everything in \some\pack namespace.

Related commits: 463667a
Implemented in c584f61

Extern generator

This task is not a subject for this repo, but it will live here for a while to keep it in mind.

Since PHP has phpDocumentor which produces docs in convinient xml format, it is possible to create automatic extern generator.

External storage for class metadata and reflexion

Hello,

This is a suggestion. I'm no compiler expert, so fire at will if this is a bad one!

The current Haxe compiler stores class metadata in a static field called "meta". Metadata is then accessed using a function with the same name. While it does not cause any direct problem (the risk of colliding with this very specific name is low, I guess), I wonder if this would not be better stored elsewhere in order to reduce clutter in the generated class file.

Maybe something along the lines of the Java world (hides from people throwing rocks) like having an explicit class definition somewhere in which to store any metadata or compiler-related information could be a nice thing? It would reduce the risks of name collision and any information unobtainable by using the standard PHP reflection API could be stored there.

For example: given a class "org.acme.Test", there could be a generated class "haxe.rtti.generated.org.acme.Test" containing all the information. The developer itself would not see this generated class - only the compiler and internal Haxe's RTTI API would have access to it.

Someone would have to double check here, but I do not think that PHP has standardized annotations yet. There was an RFC for annotations here ( https://wiki.php.net/rfc/annotations ). And some frameworks already provide a solution by using comments ( http://symfony.com/doc/current/validation.html / https://wiki.typo3.org/Dependency_Injection ).

I am very far from being a fan of the comment approach since comments are, by definition, not supposed to alter the execution of the program. Is there anything being pushed forward by PHP regarding metadata?

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.