andrei-markeev / ts2c

Convert Javascript/TypeScript to C
ISC License
1.26k stars 95 forks source link

Feature: Classes (for TS at least) #68

Open pitust opened 4 years ago

pitust commented 4 years ago

Classes shouldn't be too difficult to get working, especially in typescript, and should be even easier than prototypes (i think).

ceremcem commented 4 years ago

FYI: LiveScript classes look like the following:

class A
  -> console.log \hello

  x: (y) -> 2 * y

  t: ~> 2 * t

...and compiles to the following Javascript:

var A;
A = (function(){
  A.displayName = 'A';
  var prototype = A.prototype, constructor = A;
  function A(){
    this.t = bind$(this, 't', prototype);
    console.log('hello');
  }
  A.prototype.x = function(y){
    return 2 * y;
  };
  A.prototype.t = function(){
    return 2 * t;
  };
  return A;
}());
function bind$(obj, key, target){
  return function(){ return (target || obj)[key].apply(obj, arguments) };
}
andrei-markeev commented 4 years ago

if we get prototype working, then we can use TS->ES3 transpilation to have classes as well. I don't want to make a separate implementation for classes for now. Let's cover ES3 first, this will open many doors :)

pitust commented 4 years ago

What if we made Functions be Objects?

pitust commented 4 years ago

(that would let us have the first thing @eclipticccc suggested)

pitust commented 4 years ago

Here is how i see it: make functions have an internal field, lets say __internal_fnptr_call, and when we call them, use that field instead.

andrei-markeev commented 4 years ago

@pitust it already kind of works like that

there are actually 3 things:

pitust commented 4 years ago

Maybe, but code like:

function f() {}
f.a = 3;

doesn't work. However, this does work:

function __real_f() {}
var f = {};
f.__internal_fnptr_call = __real_f;
f.a = 3;
andrei-markeev commented 4 years ago

ah I see. there's a difference between this (i.e. instance of a function) and statically adding fields to the function object. yes that is still not implemented.