TypeScriptCompiler - TypeScript Compiler (by LLVM)

Overview

TypeScript Native Compiler

Powered by LLVM|MLIR

Donate

Build

Test Build (Windows) Test Build (Linux)

Demo

Demo

Chat Room

Want to chat with other members of the TypeScriptCompiler community?

Join the chat at https://gitter.im/ASDAlexander77/TypeScriptCompiler

Example

abstract class Department {
    constructor(public name: string) {}

    printName(): void {
        print("Department name: " + this.name);
    }

    abstract printMeeting(): void; // must be implemented in derived classes
}

class AccountingDepartment extends Department {
    constructor() {
        super("Accounting and Auditing"); // constructors in derived classes must call super()
    }

    printMeeting(): void {
        print("The Accounting Department meets each Monday at 10am.");
    }

    generateReports(): void {
        print("Generating accounting reports...");
    }
}

function main() {
    let department: Department; // ok to create a reference to an abstract type
    department = new AccountingDepartment(); // ok to create and assign a non-abstract subclass
    department.printName();
    department.printMeeting();
    //department.generateReports(); // error: department is not of type AccountingDepartment, cannot access generateReports
}

Run

tsc --emit=jit example.ts

Result

Department name: Accounting and Auditing
The Accounting Department meets each Monday at 10am.

Compile as JIT

tsc --emit=jit hello.ts

File hello.ts

function main() {
    print("Hello World!");
}

Result

Hello World!

Compile as Binary Executable

On Windows

File tsc-compile.bat

rem set %LLVM% and %TSCBIN%
set FILENAME=%1
set LLVMPATH=C:\TypeScriptCompiler\3rdParty\llvm\release\bin
set TSCPATH=C:\TypeScriptCompiler\__build\tsc\bin
set LIBPATH="C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\lib\x64"
set SDKPATH="C:\Program Files (x86)\Windows Kits\10\Lib\10.0.18362.0\um\x64"
set UCRTPATH="C:\Program Files (x86)\Windows Kits\10\Lib\10.0.18362.0\ucrt\x64"
%TSCPATH%\tsc.exe --emit=jit -nogc -dump-object-file -object-filename=%FILENAME%.o %FILENAME%.ts
%LLVMPATH%\lld.exe -flavor link %FILENAME%.o /libpath:%LIBPATH% /libpath:%SDKPATH% /libpath:%UCRTPATH% /defaultlib:libcmt.lib libvcruntime.lib

Compile

tsc-compile.bat hello

Run

hello.exe

Result

Hello World!

On Linux (Ubuntu 20.04)

File tsc-compile.sh

./tsc --emit=jit -nogc -dump-object-file -object-filename=$1.o $1.ts
gcc -o $1 $1.o

Compile

sh -f tsc-compile.sh hello

Run

./hello

Result

Hello World!

Compiling as WASM

On Windows

File tsc-compile-wasm.bat

rem set %LLVM% and %TSCBIN%
set LLVMPATH=%LLVM%\llvm\release\bin
set TSCPATH=%TSCBIN%\tsc\bin
%TSCPATH%\tsc.exe --emit=llvm -nogc %FILENAME%.ts 2>%FILENAME%.ll
%LLVMPATH%\llc.exe -mtriple=wasm32-unknown-unknown -O3 --filetype=obj -o=%FILENAME%.o %FILENAME%.ll
%LLVMPATH%\wasm-ld.exe %FILENAME%.o -o %FILENAME%.wasm --no-entry --export-all --allow-undefined

Compile

tsc-compile-wasm.bat hello

Run run.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script type="module">
let buffer;

const config = {
    env: {
        memory_base: 0,
        table_base: 0,
        memory : new WebAssembly.Memory({ initial: 256}),
        table: new WebAssembly.Table({
            initial: 0,
            element: 'anyfunc',
        })
    }
};

fetch("./hello.wasm")
    .then(response =>{
        return response.arrayBuffer();
    })
    .then(bytes => {
        return WebAssembly.instantiate(bytes, config); 
    })
    .then(results => { 
       let { main } =  results.instance.exports;
       buffer = new Uint8Array(results.instance.exports.memory.buffer);
       main();
    });
    </script>
  </body>
</html>

Build

On Windows

First, precompile dependencies

prepare_3rdParty.bat 

To build TSC binaries:

cd tsc
config_tsc_debug.bat
build_tsc_debug.bat

On Linux (Ubuntu 20.04)

First, precompile dependencies

sh -f prepare_3rdParty.sh

To build TSC binaries:

cd tsc
sh -f config_tsc_debug.sh
sh -f build_tsc_debug.sh
Comments
  • How to support gc compile ?

    How to support gc compile ?

    I noticed that the readme.md compile with nogc? ./tsc --emit=jit -nogc -dump-object-file -object-filename=$1.o $1.ts

    do this support gc ? how to enable gc compile ?

    opened by lixiangsheng2018 8
  • Compilation error

    Compilation error

    I'm trying out this project (along with Microsoft's pxt) and the following raises a compilation error not implemented (ElementAccessExpression):

    /** Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ */
    export type Maybe<T> = null | undefined | T;
    
    export interface Path {
      readonly prev: Path | undefined;
      readonly key: string | number;
      readonly typename: string | undefined;
    }
    
    /**
     * Given a Path and a key, return a new Path containing the new key.
     */
    export function addPath(
      prev: Readonly<Path> | undefined,
      key: string | number,
      typename: string | undefined,
    ): Path {
      return { prev, key, typename };
    }
    
    /**
     * Given a Path, return an Array of the path keys.
     */
    export function pathToArray(
      path: Maybe<Readonly<Path>>,
    ): Array<string | number> {
      const flattened = [];
      let curr = path;
      while (curr) {
        flattened.push(curr.key);
        curr = curr.prev;
      }
      flattened.reverse();
      return flattened;
    }
    
    function main() {
        let pathArray = pathToArray({
            key: "path",
            prev: undefined,
            typename: undefined,
        });
        for (let x of pathArray) {
            print(x);
        }
    }
    

    It would be great to know how far this project is compared to pxt when processing more complex TypeScript projects.

    Feel free to reach me at [email protected], we might be able to setup some sponsorship for this project!

    Thanks!

    opened by syrusakbary 6
  • generate unexpected llvm ir

    generate unexpected llvm ir

    version: Release v0.0-pre-alpha6 code:

    function func() {
        throw "123";
    }
    
    function main() {
        try {
            func();
        } catch {
            
        }
        return;
    }
    
    opened by ApsarasX 4
  • Integer types

    Integer types

    I started a project with this compiler in mind (although it won't be the only target) and I realized I will need integer types. I can't find any reference to integers in the repository. I will be using AssemblyScript's typedefs for now. If integer support is added I think it will be a good idea to use the same ones (i8, i16, i32, isize, u8, u16, u32, usize, f32, f64).

    opened by DiThi 3
  • `libTypeScriptRuntime.so.13git` not found in released tarball

    `libTypeScriptRuntime.so.13git` not found in released tarball

    I have downloaded the released tarball and decompressed it.

    It just like: image

    There is an invalid symbolic link for lack of libTypeScriptRuntime.so.13git

    opened by ApsarasX 2
  • More practical examples like connect to mysql/postgre database.

    More practical examples like connect to mysql/postgre database.

    Hello there.

    Your project is very nice. But i belive more practical and real world examples and tutorials like connect to database using libmysqlclient.so/libpg.so or libmysqlclient.a/libpg.a.

    opened by sirlordt 1
  • investigate: for/await  when having assert(v >= 1 && v <= 5); causes issue

    investigate: for/await when having assert(v >= 1 && v <= 5); causes issue

    function main() { let count = 0; for await (const v of [1, 2, 3, 4, 5]) { print(v); assert(v >= 1 && v <= 5); count++; }

    assert(count == 5);
    
    print("done.");
    

    }

    opened by ASDAlexander77 1
  • investigate: for/await sometimes not working due to GC enabled

    investigate: for/await sometimes not working due to GC enabled

    Exception thrown at 0x00007FFE5CBC1D01 (TypeScriptGCWrapper.dll) in tsc.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000008573443D10). The program '[52192] tsc.exe' has exited with code 0 (0x0).

    opened by ASDAlexander77 0
  • Support for Imports

    Support for Imports

    It would be great, if Typescript projects that are using the import syntax to import variables, functions, classes or types could be compiled with tsc.

    I tried the following:

    import x from "./x";
    

    And then tried to compile it, but it failed with "unknown statement type":

    ➜  tsc git:(main) ✗ ../__build/tsc-ninja/bin/tsc ../example.ts --emit=jit --nogc
    unknown statement type
    

    Thoughts?

    opened by syrusakbary 14
  • Investigate: loading second shared .so in Linux causes error

    Investigate: loading second shared .so in Linux causes error

    tsc --emit=jit --shared-libs=lib/libmlir_async_runti me.so,lib/libTypeScriptGCWrapper.so /tests/00print.ts

    Backtrace: __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50 50 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory. (gdb) bt #0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50 #1 0x00007ffff7a2d859 in __GI_abort () at abort.c:79 #2 0x00007ffff78f5d5a in llvm::report_fatal_error(llvm::Twine const&, bool) () from /mnt/c/dev/__unix/TypeScriptCompiler/__build/tsc-ninja-release/test/tester/../../../../3rdParty/llvm-ninja/release/lib/libmlir_async_runtime.so #3 0x00007ffff78f5f2e in llvm::report_fatal_error(char const*, bool) () from /mnt/c/dev/__unix/TypeScriptCompiler/__build/tsc-ninja-release/test/tester/../../../../3rdParty/llvm-ninja/release/lib/libmlir_async_runtime.so #4 0x00007ffff7954f51 in (anonymous namespace)::CommandLineParser::addOption(llvm::cl::Opti

    opened by ASDAlexander77 0
Releases(v0.0-pre-alpha22)
Owner
Alex D
Alex D
Writing a basic compiler frontend following LLVM's tutorial, with complete added supports Hindi and UTF-8 in general

सारस | SARAS Started with following LLVM's tutorial In development, a hobby project only JIT is broken right now, 'jit' branch par code hai uska Compi

Aditya Gupta 4 May 1, 2022
A demo app using: Svelte, Typescript, Vite, and Emscripten

Svelte + TS + Vite + Emscripten This template should help get you started developing with Svelte, TypeScript, and Emscripten in Vite. This template wa

Wolf McNally 3 Nov 15, 2021
Convert Javascript/TypeScript to C

Convert Javascript/TypeScript to C

Andrei Markeev 1.1k Jan 4, 2023
StarkScript - or the Stark programming language - is a compiled C-based programming language that aims to offer the same usability as that of JavaScript's and TypeScript's

StarkScript StarkScript - or the Stark programming language - is a compiled C-based programming language that aims to offer the same usability as that

EnderCommunity 5 May 10, 2022
Collection of C++ containers extracted from LLVM

lvc lvc is a set of C++ containers extracted form LLVM for an easier integration in external projects. To avoid any potential conflit, the llvm namesp

Benjamin Navarro 26 Apr 22, 2022
Toy LLVM obfuscator pass

ToyObfuscator Some simple obfuscator ;) (base on llvm-10) Compile Build out-tree pass git clone https://github.com/veritas501/ToyObfuscator.git cd Toy

veritas501 51 Nov 6, 2022
VM devirtualization PoC based on AsmJit and llvm

vm_jit PoC vm devirtualization based on AsmJit. The binary was taken from YauzaCTF 2021 competition. You are welcome to try to solve it yourself, the

Pavel 58 Aug 8, 2022
Convert LLVM coverage information into HTML reports

llvm-coverage-to-html converter The clang compiler supports source based coverage tracking, but the default reporting options are very basic. This too

Thomas Neumann 2 Oct 11, 2021
A simple Jasper interpreter made with Flex, Bison and the LLVM IR

JasperCompiler A simple Jasper interpreter (for now) made with Flex and Bison. Jasper? Jasper is "a scripting language inspired by Haskell, Javascript

Emmanuel 2 Jan 16, 2022
Tobsterlang is a simple imperative programming language, written in C++ with LLVM.

tobsterlang Tobsterlang is a simple imperative programming language, written in C++ with LLVM. One of its distinct features is the fact it uses XML in

TOBSTERA 8 Nov 11, 2021
repo to house various LLVM based SIHFT passes for RISCV 32/64 soft error resilience

compas-ft-riscv COMPAS: Compiler-assisted Software-implemented Hardware Fault Tolerance implemented in LLVM passes for the RISC-V backend Repo to hous

EDA@TUM 2 Jan 10, 2022
pluggable tool to convert an unrolled TritonAST to LLVM-IR, optimize it and get back to TritonAST

it is fork from https://github.com/fvrmatteo/TritonASTLLVMIRTranslator *WARNINGS: tested only linux(ubuntu 20.04) and only llvm and clang version 10*

pr4gasm 5 Jun 10, 2022
Per function, Lua JIT using LLVM C++ toolchain

Lua Low Level Brief This is an alternative Lua (5.3.2) implementation that aims to archive better performance by generating native code with the help

Gabriel de Quadros Ligneul 10 Sep 4, 2021
LLVM IR and optimizer for shaders, including front-end adapters for GLSL and SPIR-V and back-end adapter for GLSL

Licensing LunarGLASS is available via a three clause BSD-style open source license. Goals The primary goals of the LunarGLASS project are: Reduce the

LunarG, Inc. 153 Dec 8, 2022
Compiler Optimizations Playground

This is (hopefully) the simplest implementation of the classic register-machine intermediate representation (IR) to undertake data and control flow analysis in a compiler middle-end.

null 27 May 31, 2022
PL/0 Compiler Extension(including repeat, for, case, function, real, record and so on)

EX-PL0 PL/0 Compiler Extension(including repeat, for, case, function, real, record and so on) Structure src/PL source code of PL compiler; src/interpr

Chunshuo Qiu 16 Jul 21, 2022
A simple assembler, made primarily for assembling output from my compiler.

Assembler This assembler is not currently meant for general use. It supports only the instructions and features emitted (and used) in my C compiler. I

null 2 Nov 14, 2021
Pure Data patch export to lv2 plugin using heavy compiler + dpf example

Pure Data patch export to lv2 plugin using heavy compiler + dpf example Work in progress - Takes an audio input and writes to a 0.5 seconds buffers. 4

Qwrtst 3 Dec 27, 2022