Skip to content
HawkyntPublic

About

Polypiler — verified cross-language optimizing compiler and transpiler. Translates algorithms between C#, JavaScript, Rust, C/C++, Kotlin, Python, Perl and PowerBASIC, and lifts LLVM IR, MSIL, JVM, WebAssembly, x86, ARM and 6502 machine code back to readable, tested source.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

87 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Polypiler

License Language

CI Last Commit Activity

Stars Forks Issues Code Size Repo Size

Release Nightly Downloads

Write or recover an algorithm in one language. Compile it into another. Preserve its semantics. Optimize for the target. Polypiler is a cross-language optimizing compiler and transpiler that lifts algorithms from source code, bytecode or machine code into one verified intermediate representation and emits readable, tested, target-native implementations — from C#, JavaScript and Rust to PowerBASIC, LLVM IR and MOS 6502.

🧭 Vision

Polypiler is a planned, cross-language optimizing compiler and algorithm ecosystem. Its goal is to accept algorithm implementations written in supported source languages—or recovered from supported intermediate and machine-code formats—and generate readable, executable, verified implementations for other languages, runtimes, processors and operating environments.

It is designed to do more than translate syntax. Polypiler recognizes the computation represented by source code, type patterns, library operations, pointer arithmetic, inline assembly and machine instructions. It can reverse source-specific optimizations, reconstruct higher-level operations, then choose a different implementation suited to the destination.

Project status: specification and initial implementation planning. This README describes the intended product, not a finished transpiler. The commands and language combinations below are planned interfaces and acceptance scenarios, not claims that they already work. The one exception is a first prototype that translates a small subset of C# and of JavaScript, with or without type annotations, to JavaScript or C#; Quick start shows it and says where it ends. The detailed agent implementation contract is in PRD.md.

A correct algorithm should not need to be manually rewritten for every programming language and processor. Polypiler aims to make algorithm implementations portable through a common, semantically precise intermediate representation (IR) and a verifier-driven compiler pipeline.

The same engine should eventually support:

  • Source → source: JavaScript Cipher implementation → C#, PowerBASIC → Rust, Kotlin deinterlacer → Perl.
  • Source → executable: C# numeric algorithm → DOS x86-16 executable, Rust bit manipulation → MOS 6502 machine code.
  • Binary/bytecode → source: MSIL → PHP, JVM bytecode → Delphi, x86 → C++, ARM → PowerBASIC, MOS 6502 → C#.
  • IR interchange: LLVM .ll / .bc → Polypiler → other languages, and Polypiler → LLVM IR for compatible toolchains.
  • Algorithm distribution: Import a tested algorithm from the catalogue and generate only its relevant implementation, runtime helpers, tests and dependencies.

Every pair is useful only when the supported language subset, source semantics, target runtime, external dependencies and ABI have been independently verified. Polypiler will report unsupported features instead of fabricating superficially plausible code.

✨ Features

All of the following is planned — nothing is advertised as working before its verification gate passes.

  • Source → source translation between C#, JavaScript, Rust, C, C++, Kotlin, Perl, Python, PowerBASIC and more — every language planned as both input and output.
  • Binary and bytecode recovery — MSIL, JVM, WebAssembly, LLVM IR, tokenized BASIC, x86/x64, ARM and 6502 lifted back to readable source.
  • Native executables for constrained targets such as 8086 DOS and MOS 6502.
  • Semantic recovery and de-optimization — popcount, min/max, rotations, bit permutations, unrolled and interleaved loops recognized regardless of how they were written.
  • Proof-driven optimization — every rewrite backed by range/alias facts, exhaustive small-width tests or SMT bitvector proofs.
  • De-dynamicization — JavaScript, Python and Perl specialized into typed code with guarded fallbacks.
  • Foreign libraries and ABIs preserved — native bindings, binary-compatible UDTs and marshalling plans.
  • Rich language features lowered — generics, classes, closures, exceptions, coroutines and async turned into dispatch tables, state machines and cleanup code for targets that lack them.
  • Verification built in — generated code is compiled, executed and compared against independent oracles before a pair is called supported.

🧩 Support matrix

What works today, per direction. A frontend reads the language, a backend writes it; the two advance separately, and supporting one is no evidence for the other. Every cell is backed by tests that run the generated code — a row changes only in the pull request that makes it true.

✅ full for the declared subset · ⚠️ partial, explained in the row · — not yet (planned).

The state of every source-profile and target-profile pair, as far as gate records prove it, is the generated capability report (JSON); a pair without evidence reads planned there. Live cross-backend translations of high-level C# constructs — including structs, records, classes, statics, inheritance, generics, closures, callbacks, recursion, overloading, collections, iterators, LINQ, exceptions, async tasks, stdio, spans/pointers and native interop across all supported text and disassembled binary backends — are generated in the translation showcase.

Languages

Language Dialect / version Frontend Backend Notes
C# Frontend: C# 14, .NET 10. Backend, by --profile: net2.0 (C# 2), net3.5 (C# 3), net4.6 (C# 6), net4.8 and netstandard2.0 (C# 7.3), netstandard2.1 and netcoreapp3.1 (C# 8), net8.0 (C# 12), net10.0 (C# 14, the default) ⚠️ ⚠️ Prototype subset. The frontend imports one static class of static methods over every integer type from sbyte to ulong, char, float, double, bool, one-dimensional arrays of the numeric types and value records - struct, readonly struct, record struct and readonly record struct beside or inside the class, with fields, constructors that assign them, new T(), default, object initializers, field access through variables, array elements and nested fields, arrays of structs and the ==/!=/Equals(T) of a record struct - with the promotions and conversions of C# and checked/unchecked; if, while, do, for, foreach over an array, switch with constant labels, break, continue, ++/-- as values; const and static readonly fields as constants and read-only tables; private/internal static fields, and static readonly ones whose value is computed or whose array elements are written, as module state that every method shares from call to call, initialised once in source order (an initializer reads only constants and earlier fields and calls only methods that touch no static field); Array.Copy/Fill/Clear; the exact operations of Math, MathF, BitOperations and BitConverter, and the integer members of BitOperations, Math, BinaryPrimitives, BitConverter and the integer types — rotates, counts, IsPow2, RoundUpToPowerOf2, ReverseEndianness, BigMul, DivRem with its out argument or deconstructed, Clamp, Min/Max/Abs/Sign, CreateSaturating/Truncating/Checked, endian Read…/Write… on an array or any span of bytes and BitConverter.To… on an array or its AsSpan, of the integers and of float and double as their IEEE 754 encoding (BitConverter.ToSingle/ToDouble on an array and an index), and Bmi2.ParallelBitExtract/ParallelBitDeposit computed on every processor. Every floating-point member of Math, MathF, double and float that the table CSharpFloatApi lists (floating-point operations) - the trigonometric, hyperbolic, exponential and logarithmic functions and their inverses, Pow, Cbrt, Hypot, RootN, FusedMultiplyAdd, IEEERemainder, Round with every MidpointRounding given as a constant and to digits, CopySign, the magnitude and number forms of Min and Max, Clamp, ScaleB, ILogB, BitIncrement/BitDecrement, the classification, the angle conversion, Lerp and the two parts of SinCos - is the operation it means or the sequence .NET 10 computes it by (double.Exp2 is Math.Pow(2, x)). Views: Span<T> and ReadOnlySpan<T> of the number types as locals, parameters and results - AsSpan, new Span<T>(…), the conversion of an array, Slice, ranges and indices from the end, Length, IsEmpty, the indexer, foreach, stackalloc, CopyTo, TryCopyTo, Fill, Clear, SequenceEqual, ToArray, MemoryMarshal.Cast/AsBytes into a read-only span and MemoryMarshal.Read/Write; Memory<T> and ReadOnlyMemory<T> as locals, parameters, results and fields of a class that is no record - AsMemory, new Memory<T>(…), the conversion of an array, Slice, Span, Length, IsEmpty, ToArray (not GetReference, CreateSpan and ref locals). Pointers: unsafe code as bounded pointers - unsafe classes, methods and blocks, pointers to the number types and void*, fixed over an array, an element or a span, & of a local, *p, p[i], p + n, p - q, ++, --, +=, -=, the comparisons, casts between pointer types, sizeof and stackalloc into a pointer; the backend keeps them unsafe code in every profile, whose file asks for AllowUnsafeBlocks (not a cast between a pointer and an integer, delegate*, char*, pointers to structs and a pointer kept after its fixed). Strings of UTF-16 code units: string locals, parameters, results, constants and arrays, literals, + and interpolation of strings and chars, ==, switch on a string, foreach over one and the ordinal members CSharpStringApi lists (Substring, IndexOf(char), Contains, Replace, Split(char), Join, Trim, PadLeft, CompareOrdinal against 0 …); a member that compares by culture is refused with the advice to pass StringComparison.Ordinal, and so is case mapping. Numbers to text and back by .NET's rules with the invariant culture: ToString, + and interpolation of numbers and bool, F<n>, D<n>, x<n>, `Convert.ToString(v, 2
JavaScript Frontend: ES2022 scripts and modules. Backend: ES5, ES2015, ES2017, ES2020, ES2022 as ES module, CommonJS module or script; Node ⚠️ ⚠️ Prototype subset. The frontend imports plain JavaScript without annotations: every number is a double computed as ECMA-262 computes it, and a variable, a parameter of a function nothing outside calls or a result is an int32 or uint32 where the program proves it — where every value that reaches it comes from a bitwise operator, >>> 0, Math.imul, Math.clz32, a typed array, a length, an integer literal or +/- directly under a coercion (a product is never narrowed). JSDoc (int8 to uint64, number, float32, boolean, every typed array, and the spellings of Cipher's framework: byte, int, bool, string, a class of the file, `T
PowerBASIC DOS 3.5 (pb35), pb36 — —
C C11 / C17 / C23 — —
C++ C++17 / C++20 / C++23 (--profile cpp/cpp17|cpp/cpp20|cpp/cpp23, --namespace) ⚠️ ⚠️ Verified std-only ISO C++ subset (#401). The frontend parses and lowers C++17/20/23 directly (no external Clang process required): fixed-width integer and floating-point types, bool, std::string, std::vector<T>, std::array<T, N>, std::span<T>, std::optional<T>, structs, classes with constructors/methods/inheritance, enum class, namespaces, if/else, while, do/while, for, range-for, switch, try/catch/throw, static_cast/std::bit_cast, and <cmath>/<bit>/<algorithm> intrinsics (PLY1400–PLY1404). The backend emits clean, warning-free (-Wall -Wextra -Werror) header/source pairs (.hpp + .cpp) using only the C++ standard library, preserving exact wrap-around/checked integer semantics, IEEE-754 floating-point operations, <bit>/std::bit_cast/std::byteswap per profile with C++17 fallbacks, arrays/spans/structs/classes/enums/optionals/exceptions, and refusing unsupported constructs with PLY1450–PLY1452.
Rust Frontend: 2024 edition; the overflow mode of --overflow-checks panic (debug) or wrap (release), else the overflow-checks of the Cargo profile (--cargo-profile, default dev) in the Cargo.toml above the source, else panic. Backend, by --profile: rust2018 (Rust 1.31), rust2021 (Rust 1.56), rust2024 (Rust 1.85, the default); --rust-version raises the MSRV; --trap-policy panic (default) or result; --allow-unsafe admits the one unsafe lowering ⚠️ ⚠️ Frontend: free functions over i8…i64, u8…u64, isize/usize (64-bit), f32, f64, bool, with literals of every base and suffix, the operators, as casts (float to integer saturating), MIN/MAX/BITS, the wrapping_*, checked_* (consumed by unwrap, expect, unwrap_or, is_some, is_none), overflowing_* (.0, .1, tuple let) and saturating_* methods, abs, signum, pow, abs_diff, min, max, clamp, div_euclid, rem_euclid, rotations, byte and bit reversal, bit counts, float abs, sqrt, to_bits, from_bits, is_nan; let, shadowing, const, blocks, if, match (literal, range, or, tuple, binding and guard patterns, exhaustiveness checked), while, loop with break value, for over integer ranges with rev()/step_by() in either order, labelled break/continue and blocks, calls and recursion, pub as the exported surface; fixed arrays, &[T]/&mut [T] slices and Vec<T> of numbers, bool, tuples and structs (indexing, ranges, len, iter, iter_mut, chunks_exact, split_at, copy_from_slice, fill, swap, push, pop, vec!), shared and &mut references (aliased places, &mut parameters copied in and out), tuples, structs and tuple structs with inherent methods and associated constants, field-less enums with discriminants, Option and Result with ?, if let, while let and destructuring patterns, match on constants as a switch; closures (inlined, move included) and iterator chains (map, filter, enumerate, zip, rev, step_by, copied into sum, product, count, fold, any, all, for_each, collect into Vec, maps and sets), function pointers; modules inline and in files, use trees, re-exports, #[test] functions and #[cfg(test)] modules. String, &str and char with Rust's UTF-8 byte lengths, offsets and slicing panics computed over the IR's UTF-16 strings, chars, bytes, split, trim, find, parse of integers, to_string and format! of integers, bool, char and text; traits of the crate's types with provided methods, supertraits and static dispatch, trait objects (&dyn T, Box<dyn T>, Rc<dyn T>) dispatched through the IR's interfaces, generic functions, structs, impls, methods and traits monomorphised per type arguments with standard and crate bounds and T::Output results (a public generic function exported as the instances the crate makes), the operator traits and PartialEq on the crate's types; HashMap, BTreeMap, HashSet, BTreeSet with insert, get, remove, contains, indexing and entry().or_insert(), never iterated. Parsed and typed by the frontend itself, use after move (E0382) and a second live &mut of a place (E0499) checked; refusals PLY1500–PLY1546 name the construct (&mut dyn T, generic enums, enums with data, smart pointers, iterating a map). See the Rust frontend. Backend: a Cargo package - Cargo.toml without dependencies, src/lib.rs with #![forbid(unsafe_code)] (#![deny(unsafe_code)] where --allow-unsafe let in the one unsafe spelling function) and the lints the code needs allowed, src/<module>.rs - every integer type, src/lib.rs with #![forbid(unsafe_code)] and the lints the code needs allowed, src/<module>.rs, a file per module of a Rust source crate (src/util/bits.rs, use crate::…, its tests as #[test]) - every integer type, f32, f64 and bool; the arbitrary-precision integer (a Python int no fixed width holds) as PlyBigInt, a struct of the crate converted from num-bigint, with every operation and conversion of the IR; the arithmetic with its contract in every build mode (wrapping_add, checked_add(…).expect("IntegerOverflow"), saturating_add, masked wrapping_shl), the division and its traps, every conversion, the intrinsics Rust has a method for (the IR helper library and the portable floating-point implementations for the others, chosen by the MSRV); functions, calls, recursion; arrays by ownership - &[T]/&mut [T] parameters, Vec<T> for arrays the code makes, static tables, borrowed results with their lifetime, element loops for &x in data, parallel loops for (&s, d) in src.iter().zip(dst.iter_mut()), a vector moved where the source never names it again, copies (copy_from_slice, copy_within inside one array), split_at_mut, fills and endian access checked before they touch a byte, pointers as positions in a region known statically (a pinned array or view, a stackalloc, the address of a local, a pointer parameter with its slice) with no raw pointer, overlay views read as safe copies through from_le_bytes/to_le_bytes, a written one only under --allow-unsafe as one audited unsafe block that passes Miri, one array passed twice to a writing callee through a copy of the callee with the parameters merged; structs of numbers with their derives and the IR's equality, #[repr(C)] for a sequential [StructLayout] (explicit offsets, a packing or a size refused with PLY1584), structs holding arrays with Vec fields, moved at their last read; a second variable of an array or a list borrowing it (let r = &mut v;) where the source is read again only after; strings as UTF-16 code units (Vec<u16>/&[u16]) with their searches, splits, trims and joins; enums as newtypes with their text and parse, an enum the module only ever gives a member's value as #[repr(u8)] pub enum with impl TryFrom<u8> and match over its variants; numbers as text both ways; single-owner classes as plain structs with &self/&mut self methods, borrowed where passed and moved where returned, other classes as Rc of a struct with a Cell/RefCell per field (array fields included), Option<Rc<T>> where a nullness analysis finds null possible; interfaces and class hierarchies as traits with Rc<dyn Trait> values, virtual calls, is/as/casts; generic methods as Rust generics with the bounds their bodies need (fn max<T: Ord + Copy>, where clauses), an instantiation a bound would give another meaning - a float under Ord/Eq - kept per instantiation; generic classes of single-owner objects as generic structs (pub struct Ring<T>, impl<T: Default + Copy> Ring<T>, Ring::<i64>::new(3)), other generic classes per instantiation; static fields as atomics; spans as slices; if/else if, while, loop with break value, for i in a..b and a..=b (to the type's maximum, 0..=255u8), reductions as iterator folds (`.fold(0u32,
Kotlin JVM — —
Perl Perl 5.6, 5.8 and modern Perl 5 (64-bit integers; --profile perl/5.6|perl/5.8|perl/5, --byte-storage array|string, --object-model blessed|moose|inside-out) ⚠️ ⚠️ Verified Perl 5 subset (#429). The frontend compiles Perl 5.6, 5.8 and modern Perl 5 through the core B module (B::PolypilerDump) with explicit contracts (--perl-contract): numeric scalars, use integer lexical regions, 64-bit shift and overflow rules, if/elsif/else/unless, statement modifiers, while/until, counted and reverse range foreach, last/next with lexical labels, arrays, lists, negative indices, byte strings, portable endian-explicit pack/unpack, subs with @_/shift/$_[N]/signatures, closures with shared lexical capture, packages, Exporter lists (use Exporter 'import' and our @ISA = qw(Exporter)), use constant (5.6 single-constant and 5.8+ hashref forms), List::Util/POSIX/Carp/Scalar::Util/Hash::Util::FieldHash, Test::More files, constant-key and computed-key hashes, undef/defined///, die/eval/try/catch/finally, plus plain blessed-hash classes (bless { … }, $class, @ISA/use base/use parent, SUPER::, isa), inside-out classes (bless \(my $o), $class with private lexical field hashes via refaddr, "$self" or fieldhash, and DESTROY), and Moose classes and Moose::Role interfaces (has, extends, with, requires, does, make_immutable); unsupported features (goto, redo, dynamic loop control, regexes, host-endian pack, escaping closures, unknown external @ISA/Moo/overload, unsorted keys, string eval, tie/magic) are refused with PLY1700–PLY1743. The backend emits standalone Perl 5 modules in CPAN layout (lib/…/*.pm, t/….t with Test::More) for --profile perl/5.6 (use 5.006;, @ISA = qw(Exporter), single use constant, pure-Perl float and endian helpers without // or </>), --profile perl/5.8 (use 5.008;, utf8::downgrade, Scalar::Util::refaddr inside-out, Moose), and --profile perl/5 (5.10+: //, </> pack modifiers, use Exporter 'import', Hash::Util::FieldHash inside-out, Moose), using use strict; use warnings;, 64-bit integer BEGIN guard, fixed-width masks with range-analysis elision, use integer regions, array and string byte storage, string-or-array byte API on exports, structured loops, if/elsif switches with range compression, hash-reference structs, enums, optionals, lists/maps/sets, closures, bound methods, using cleanup scopes, die/eval exception handling with when filters and safe completion recording across finally, and full classes, single inheritance, interfaces, virtual/override/base dispatch, is/as/casts and record equality under --object-model blessed (blessed hashes), --object-model moose (use Moose; / use Moose::Role;, Perl 5.8+), or --object-model inside-out (blessed opaque scalar references with lexically encapsulated private field hashes that external code cannot access); unsupported constructs are refused with PLY1750–PLY1783.
Windows Batch cmd, native Windows command extensions ⚠️ ⚠️ Lifts closed Int32 scripts using the explicit SETLOCAL prologue, decimal SET /A arithmetic (including >> and &), single-line literal FOR /L numeric loops, static CALL :label with decimal arguments, nested SETLOCAL/ENDLOCAL and &/&& scoped return transfers, IF/GOTO, GOTO :EOF, and EXIT /B. SET /A decimal literals must fit before unary negation; rejects ambient reads, zero-step or overflowing FOR /L ranges, recursion, unmatched scopes, and lines that can exceed cmd's 8,191-character limit. Emits standalone ASCII CRLF batch files for closed Int32 kernels with arithmetic, bitwise operations and masked shifts, IrSwitch, branches, loops, 1D Int32 arrays with aliasing and bounds traps (PLY_BATCH_TRAP=IndexOutOfRange, status 97), and printable-ASCII Console.WriteLine(string) with decimal Int32 interpolation. Round-trips closed integer kernels between C# and cmd.exe.
MS-DOS Batch dos622, COMMAND.COM 6.22 ⚠️ ⚠️ --batch-dialect dos622 lifts closed ASCII CRLF scripts with literal and template SET, case-sensitive IF string and ERRORLEVEL comparisons, eight-character label lookup, CALL and direct batch transfers over declared companion files, %0–%9 and unqualified SHIFT, and ECHO output. --profile dos622 emits parameterless Int32 kernels with unchecked addition, equality, and static control flow. Both use eight-digit hexadecimal PLYRESULT records. Run generated code in a fresh COMMAND.COM /E:32768 /C KERNEL.BAT child with at most 1,024 bytes of inherited environment entries.
Python Frontend: Python 3, parsed by the ast module of the installed CPython (pinned 3.14). Backend, by --profile: py3.8 to py3.14 (the default) ⚠️ ⚠️ Prototype subset. The frontend imports a module and the modules of the import it imports (import m, from m import f, relative imports, packages): functions with positional, keyword, positional-only and keyword-only parameters and defaults evaluated once, recursion, nested functions and closures with nonlocal, lambdas as key= and of map/filter, generators with yield and yield from, :=; module constants, tables and global variables, run once in source order; int, float and bool with + - * / // % ** << >> & | ^ ~, comparisons (chained, an int with a float exactly), and/or giving an operand; list, tuple, str (code points), bytes and bytearray with indexing from the end, slices, +, *, in, ==, len, append, pop(), extend, copy, comprehensions and generator expressions (as sequence operations), for over sequences with enumerate, zip and reversed, sorted, sum, min, max, any, all; dict as an insertion-ordered map and set (keys of int, bool, str and plain objects) with displays, comprehensions, d[k] (KeyError), del, in, len, ==, get, pop, add, remove, discard, clear, copy, iteration of a dict and its keys/values/items (RuntimeError when its size changes), and a set only where its order cannot count (sorted, sum, min, max, any, all); int.from_bytes, int.to_bytes, str.encode, struct with explicit byte order; classes without bases, @dataclass, NamedTuple, Enum and IntEnum, @staticmethod, @property, __eq__, __len__, __getitem__, __setitem__; None and Optional; raise, try/except/else/finally and exception classes derived from the built-in ones; math.sqrt, isqrt, floor, ceil, trunc, fabs, copysign, gcd, isnan, isinf, isfinite and its constants; if, while, match on literals and enum members, assert, with definite assignment required. A parameter has the type of its hint, its default or the import's calls, a local and a result the type of their values; hints are recorded as contracts. An int is the IR's arbitrary-precision integer, exact at every magnitude (literals of any size, floor // and %, / correctly rounded, int/float conversions with CPython's OverflowError), and O0062 narrows it to i32, u32, i64 or u64 where masks and ranges prove that exact: masked hashes such as FNV-1a, SplitMix64 and xorshift compute natively. An int kept in an attribute, a tuple, an optional, a module table, a dict key or a set element is 64 bits wide there and raises OverflowError beyond (py-int-held-64). Refused with a code per family (PLY1820–PLY1823, PLY1830–PLY1834, PLY1840–PLY1844): other list and string methods, f-strings, iterating a set, float and tuple keys, set algebra and the other dict and set methods, slice assignment, native struct formats, inheritance between classes, with, *args. See the Python frontend. The backend writes one typed module per IR module (PEP 484 hints, __all__ of the public functions in snake_case, everything else private behind an underscore), standard library only. The arbitrary-precision integer as int, with helpers for its truncating division and remainder, shifts by a count of any sign and the conversion to float that gives an infinity. Integers of every width with masks and sign-wraps, truncating division, checked arithmetic and the conversions that saturate or trap through small helpers; f64 IEEE 754 (division and remainder by zero included), f32 rounded to binary32 after every operation; bit casts through struct; the integer operations of the library as its helpers, int.bit_count from 3.10; the floating-point functions as their portable implementations. Branches, while and post-test loops, counted loops as for … in range(…) where the counter cannot wrap past the bound (otherwise a while), switches as match from 3.10 and as an if/elif chain before; arrays as lists, module constants and globals; strings as str of UTF-16 code units; classes with inheritance, virtual and interface dispatch, properties and statics as Python classes, structs as dataclasses (frozen where nothing writes a field, copied where the IR copies), records with the IR's equality, enums as enum.IntEnum, optional values as T | None tested with is None; lists, maps and sets as list and dict (.NET's slot order and checked enumeration where the module needs them); closures as lambdas and nested functions, a variable of every pass as a cell; iterators as generators, restartable where the IR's are, LINQ as the fused loops; spans and memory as _PlyView, pointers as a region and an offset, endian accesses as int.from_bytes/int.to_bytes/struct; the number-text conversions of .NET and ECMA-262; traps as built-in exceptions (or classes derived from them) with try/except/finally and using as try/finally; async functions as async def with await and asyncio.gather. Refused with PLY1850/PLY1851/PLY1858/PLY1874 naming the construct: a native call, an exception filter that must run before the finally blocks inside its try, two constructors of one arity, two exports of one Python name. See the Python backend.
TypeScript current — —
Java JDK 17 / 21 — —
Go current — —
Delphi / Object Pascal Free Pascal in Delphi mode — —
FreeBASIC -lang fb, -lang qb — —
PHP 8.x — —
Ruby 3.x — —
Visual Basic .NET VB 16 on .NET — —
Visual Basic 6 classic VB6 (source, forms excluded) — — No freely available compiler: needs an oracle decision first
VBA Office VBA 7 — — Shares the classic VB core; host object models are external
VBScript VBScript 5.8 (Windows Script Host; --profile vbscript/5.8, --vbscript-contract) ⚠️ ⚠️ Verified VBScript 5.8 subset (#1133). The pure-C# frontend lexes, parses and type-infers Option Explicit VBScript 5.8 with doc-comment ('' @param/'' @return) and CLI (--vbscript-contract) contracts: numeric, boolean and string scalars, If/ElseIf/Else, Select Case, For/Next, Do/While/Until, Exit For/Exit Do/Exit Function/Exit Sub, Dim/ReDim/Array/UBound, Function/Sub (ByVal/ByRef), Class with Public/Private fields, Property Get/Let/Set, Class_Initialize and New, built-in math/string/conversion functions (Abs, Sqr, Int, Fix, Len, Mid, Left, Right, InStr, InStrRev, Replace, Trim, UCase, LCase, Asc, Chr, CLng, CDbl, CStr, CBool), and refuses unsupported COM/dynamic features (CreateObject, Eval, Execute, With, On Error, For Each, GoTo) with PLY2600–PLY2604. The backend emits standalone Option Explicit .vbs scripts runnable under Windows Script Host (cscript //Nologo): exact 8/16/32/64-bit integer wraparound and bitwise helpers, IEEE-754 floats, checked overflow and division-by-zero traps, arrays, strings, structs (ply_clone/ply_equals), classes, inheritance and virtual/interface dispatch, enums, optionals, try/catch/finally via On Error Resume Next, and refuses unsupported constructs with PLY2650–PLY2652.
Commodore BASIC V2 (C64); VIC-20 and C128 as profiles — —

Bytecode, intermediate and machine-code formats

For these, the frontend lifts (decodes and recovers semantics) and the backend emits (encodes).

Format / instruction set Dialect / variant Lift Emit Notes
.NET MSIL ECMA-335 assemblies (--profile msil/net10|msil/net8, --output-type library|exe) ⚠️ ⚠️ Verified MSIL subset (#833). The frontend reads PE32 and PE32+ IL-only assemblies directly through PEReader/MetadataReader, decodes CIL method bodies, builds a typed control-flow graph and lifts numeric scalars (i8–u64, f32, f64, bool), checked/unchecked arithmetic, conversions, branches, switches, loops, one-dimensional arrays, static fields, intra-assembly static calls and recognized Math/MathF/BitOperations/BitConverter intrinsics with optional --export filtering (PLY3000–PLY3008). The backend emits verifiable PE/CLI .dll class libraries and runnable console executables (.dll + .runtimeconfig.json via --output-type exe) directly with System.Reflection.Metadata.Ecma335 for msil/net10 and msil/net8, lowering unsupported intrinsics through the IR helper library and refusing unsupported constructs with PLY3050–PLY3052.
JVM bytecode JVMS class files (major 50+) and JAR archives (--profile jvm/21|jvm/17|jvm/8, --package-format jar|class) ⚠️ ⚠️ Verified JVM bytecode subset (#831). The frontend parses JVMS Chapter 4 .class files and .jar archives without external dependencies, decodes opcodes, validates constant pools and stack maps, and lifts static methods over byte/short/char/int/long/float/double/boolean, arrays, static fields, structured control flow (if, loops, tableswitch/lookupswitch), try/catch/finally handlers and Math/Integer/Long/Float/Double intrinsics with optional --export filtering (PLY3100–PLY3108). The backend emits verifier-clean (java -Xverify:all) .class files and deterministic .jar archives (META-INF/MANIFEST.MF, optional Main-Class) targeting jvm/21 (65.0), jvm/17 (61.0) or jvm/8 (52.0), computing StackMapTable frames directly and refusing unsupported constructs with PLY3150–PLY3152.
WebAssembly core specification, binary modules — —
LLVM IR .ll text, .bc bitcode — —
GCC GIMPLE / GENERIC GCC's own intermediate language, per GCC version — — Feasibility study first: reached through a GCC plugin or dump, never through LLVM
MOS 6502 NMOS; 65C02 and 65C816 as variants — —
Zilog Z80 / Intel 8080 — —
8086 / x86-16 real mode, DOS MZ and COM — —
x86 (32-bit) / x64 integer core; extensions in the table below — —
ARM32 / Thumb, AArch64 AAPCS, AAPCS64 — —
Commodore BASIC tokenized C64 PRG; VIC-20, C128 — —
GW-BASIC tokenized — —
Microsoft BASIC p-code per dialect, after an inventory — —

No instruction set is lifted or emitted yet. The machine level they build on exists: MachineIR with machine profiles (test-m32, test-m64, mos6502), sub-registers, flags, traps and memory regions, its verifier and interpreter, observable-state traces with machine vector files, and the binary image model with its manifest.

Instruction-set extensions

A CPU family is not one instruction set. Each extension is lifted and emitted separately, and a target profile names exactly the ones it may use; an instruction of an extension that is not lifted yet is preserved as an opaque operation, never dropped.

Family Extension Lift Emit Notes
x86 / x64 x87 FPU — — 80-bit extended precision, stack registers
x86 / x64 MMX — — 64-bit integer vectors
x86 / x64 SSE, SSE2 — — 128-bit float and integer vectors; scalar float arithmetic on x64
x86 / x64 SSE3, SSSE3, SSE4.1, SSE4.2 — — horizontal operations, byte shuffle, blends, string compares, CRC32
x86 / x64 AES-NI, PCLMULQDQ, SHA — — cipher rounds, carry-less multiply, hash rounds
x86 / x64 AVX, AVX2, FMA3, F16C — — 256-bit vectors, fused multiply-add, half-float conversion
x86 / x64 AVX-512 (F, BW, DQ, VL, VBMI, VNNI) — — 512-bit vectors, mask registers
x86 / x64 BMI1, BMI2, POPCNT, LZCNT, ADX — — bit manipulation, PEXT/PDEP, multi-precision carry chains
ARM32 / AArch64 NEON (Advanced SIMD), VFP — — 128-bit vectors, floating point
AArch64 Cryptography extensions (AES, SHA, PMULL), CRC32 — —
AArch64 SVE, SVE2 — — scalable vectors

Every language and format above is planned in both directions. LLVM integration broadens access to LLVM-based source frontends such as Clang; it does not automatically expose every GCC language frontend. GCC GENERIC/GIMPLE requires a separate verified adapter.

📦 Installation

Nothing has been released yet. Once the first alpha lands, self-contained polypiler binaries for Windows and Linux are published on the releases page — dated releases and automatic nightlies. Until then, build from source (see 🛠️ Building); the only requirement is the .NET 10 SDK.

🚀 Quick start

One public command name is planned: polypiler. Today it has two working commands: the translate prototype below and verify. Every other example in this section establishes the product interface and will not run until the corresponding features have been implemented and verified.

Run the prototype: a small C# algorithm to a JavaScript module

# Works today, from a checkout with the .NET 10 SDK
dotnet run --project Polypiler.Cli -c Release -- translate tests/fixtures/prototype/Adler32.cs \
  --from csharp --to javascript --output ./generated

# The generated module runs as it is; this prints 300286872, the published Adler-32 of "Wikipedia"
node --input-type=module -e "import { Compute } from './generated/Adler32.mjs'; console.log(Compute(new TextEncoder().encode('Wikipedia')))"

# The same algorithm for an old engine: ./generated/Adler32.js, an ES5 script that declares the global Checksums
dotnet run --project Polypiler.Cli -c Release -- translate tests/fixtures/prototype/Adler32.cs \
  --from csharp --to javascript --profile es5 --module iife --global Checksums --output ./generated

# The same subset written back out as C# (prototype subset): ./generated/Adler32.cs, here in a namespace
dotnet run --project Polypiler.Cli -c Release -- translate tests/fixtures/prototype/Adler32.cs \
  --from csharp --to csharp --namespace Demo.Checksums --output ./generated

# The same again for an old framework: C# 7.3 that compiles for .NET Framework 4.8
dotnet run --project Polypiler.Cli -c Release -- translate tests/fixtures/prototype/wide/Library.cs \
  --from csharp --to csharp --profile net4.8 --output ./generated

This is a walking skeleton, not the product: one thin path from source to generated code, with the first recognition rules as its only optimization and without --verify. The fact facade with its constant, range and pointer-provenance analyses and the per-target cost model exist as libraries that no pass consults yet.

  • Input: one C# file holding one static class of static methods and constants, and the structs and record structs it uses (value records).
    • Types: sbyte, byte, short, ushort, char, int, uint, long, ulong, float, double, bool, and one-dimensional arrays of the numeric ones.
    • Expressions: arithmetic, bitwise, shift, comparison and logical operators with the promotions of C# (uint with int is computed as long), ?:, every cast between numeric types, checked and unchecked, ++/-- as statements and as values, compound assignment to variables and array elements, calls within the class.
    • Statements: if/else, while, do … while, for, foreach over an array, switch on an integer or char with constant labels, break, continue, return, local const.
    • Constants and tables: const fields, and static readonly fields whose initializer is a constant or — for an array — a list of constants (new uint[] { … }, { … }, [ … ]). A table is read-only: it can be indexed, measured, iterated and copied from.
    • Arrays: new T[n], new T[] { … }, Length, Array.Copy(source, sourceIndex, target, targetIndex, length), Array.Fill(array, value), Array.Clear(array).
    • Base library, where the result is exact: Math/MathF Abs, Min, Max, Sign, Sqrt, Floor, Ceiling, Truncate, Round (to even, or MidpointRounding.AwayFromZero); BitConverter DoubleToInt64Bits, Int64BitsToDouble, SingleToInt32Bits, Int32BitsToSingle; the constants of the numeric types such as uint.MaxValue.
    • Integer and bit operations: the members of CSharpIntegerApi — every member of BitOperations the IR has an operation for (not Crc32C); RotateLeft, RotateRight, PopCount, LeadingZeroCount, TrailingZeroCount, Log2, IsPow2, Clamp, Min, Max, Abs, Sign, DivRem, CreateSaturating, CreateTruncating, CreateChecked of the integer types; Math.BigMul, Math.Clamp and Math.DivRem (the out argument of a 64-bit BigMul and of DivRem a local, in a statement); BinaryPrimitives.ReverseEndianness and Read…/Write…LittleEndian/BigEndian on a byte[], its AsSpan(index) or its AsSpan(index, size); BitConverter.ToInt16 to ToUInt64 (little-endian, as on every supported host). Log2 of a negative signed value and crossed Clamp bounds trap with another kind than the exception .NET throws.
  • Output: <class>.mjs, an ES module that exports every public method and states above each function what crosses its boundary.
    • Integers of up to 32 bits and floating-point numbers are JavaScript numbers; long and ulong are BigInts. Arrays are the typed array of their element type, from Int8Array to BigUint64Array and Float64Array.
    • Integers wrap around at their width as in C#, shift counts are masked, and float arithmetic is rounded to binary32 after every operation. Conversions from floating point to an integer saturate as .NET 10 does them.
    • What throws in C# throws a RangeError: a division by zero, an index outside its array, MinValue / -1, and every overflow in a checked context.
  • Output for another JavaScript: --profile <es5|es2015|es2017|es2020|es2022> names the language level and --module <esm|cjs|iife> the packaging; the file is <class>.mjs, <class>.cjs or <class>.js and states its profile in its second line.
    • Module formats: esm exports every public method, cjs assigns them to exports, iife is a script that declares one global object holding them, named by --global <name>. Without --module the level decides: esm from ES2015 on, cjs at ES5, which has no modules — --profile es5 --module esm is a usage error.
    • Below ES2020 there is no BigInt: a long or ulong is an object { hi, lo } of its upper and lower 32 bits, each an unsigned number, also as a parameter and as a result — the comment above the function says so — and arrays of them are plain arrays. Addition, subtraction, multiplication, division, remainder, shifts, comparisons and conversions are computed on the halves by helpers that never leave the integers a number holds exactly.
    • At ES5 there is no let, Math.imul, Math.clz32, Math.fround, Math.trunc or Math.sign: variables are vars, renamed where two of one name would otherwise become one variable, and the functions are helpers; float arithmetic is rounded to binary32 by arithmetic. Arrays are plain arrays whose stores wrap around as a typed array would; --typed-arrays says the engine has typed arrays and DataView, and they are used.
    • One known difference: without a DataView a NaN has no bits a program can read, so BitConverter.SingleToInt32Bits and DoubleToInt64Bits give every NaN the bits of the quiet NaN 0x7FC00000 and 0x7FF8000000000000, whatever payload it had.
    • Native calls (foreign calls, ADR 0007): a [DllImport] or [LibraryImport] function of the source calls the function of its symbol in the binding that --bind <library>=<module or global> names - imported by esm, required by cjs, read from a global by iife - with the value contract of the reference page; the manifest records each as an unverified external. Without a binding the translation is refused with PLY1152.
  • Output with --to csharp: <class>.cs, one public static class with a method per function — public where the source was — in the namespace --namespace names, or in none. It holds everything the input list names.
    • --profile names what the file is written for; the header of the file repeats it. A profile is a target framework and the C# version of that framework's time: net2.0 (C# 2), net3.5 (C# 3), net4.6 (C# 6), net4.8 and netstandard2.0 (C# 7.3), netstandard2.1 and netcoreapp3.1 (C# 8), net8.0 (C# 12) and net10.0 (C# 14), which is the default. --langversion raises the language version (--profile net4.8 --langversion 10); it cannot lower it.
    • The file uses what its profile has and nothing else. An API the framework lacks is replaced — MathF.Sqrt(x) by (float)Math.Sqrt(x), which has the same bits, a rotate or a population count by a private helper that the class gets only when it calls it — and the language is written in the forms of its version: a file-scoped namespace from C# 10 on and a block before, => bodies from C# 6, var from C# 3, >>> from C# 11, the discard from C# 7. The generated code depends on no package in any profile, and a public method has the same name in every profile.
    • Variables keep their names. A local named like a parameter or like a local of an enclosing or enclosed block, which JavaScript and the IR allow and C# does not (CS0136), becomes <name>_<k> with the smallest free k; of two such locals the later one is renamed.
    • Every call returns the same in every profile. That includes what an older framework's own library would do differently: Math.Min and Math.Max did not order -0.0 and +0.0 before .NET Core 3.0, and a cast from floating point to an integer saturates only from .NET 9 on, so a file for an older profile calls a helper for both.
    • Arithmetic that wraps around stands in an unchecked block and what was checked in a checked(…) expression, so the file computes the same with and without CheckForOverflowUnderflow. Every float result is cast to float, so that it is binary32 wherever the file is compiled.
    • A division by zero, an overflow in a checked context, the one quotient that does not fit and an index outside its array throw DivideByZeroException, OverflowException and IndexOutOfRangeException; Array.Copy reports a range outside an array as an ArgumentException.
    • Constants come back as private const fields, tables as private static readonly arrays that no method writes to, a char as ushort, and the library operations as the calls of System.Math, MathF, BitOperations, BitConverter and Array they were, named in full.
    • A for with a continue comes back as a for when its step is one statement and otherwise as a while that runs the step before each continue; any other for and every foreach come back as a while, and x += y as x = x + y.
  • Everything else is refused, not approximated: decimal, Half, Int128, nint, multi-dimensional and jagged arrays, bool[], generic math and typeof(T), events, goto, pattern matching beyond type tests and is null, and ref/out are reported as PLY1002 with their position, and nothing is written. So is every library member outside the mapping tables, by its name, and every write to a static readonly array. LINQ is not referenced at all, so its use is a compiler error.
  • Optimization: between the frontend and the backend the pass pipeline runs 17 recognition rules over the IR until nothing changes: rotates (O0100), population counts from loops and from the SWAR sequence (O0101, O0102), zero counts from bit-scanning loops (O0103), bit reversal (O0105), byte swaps (O0106), single-bit test, set, clear and toggle (O0108), sign extension (O0109), parity (O0110), minimum and maximum (O0120), the absolute value that wraps (O0121), sign (O0122), clamp (O0123), multiplication by a constant (O0125), the remainder from the quotient (O0127, where the target's table prefers it) and endian loads and stores (O0140, O0141). A spelled-out rotate becomes BitOperations.RotateLeft, four byte loads BinaryPrimitives.ReadUInt32LittleEndian. A rule applies only where its result is exact, traps included; each page says what it matches and what it leaves alone. --opt none|default (default default) switches the pipeline off or on, --disable-opt O####[,O####…] (repeatable) switches single rules off, and --explain-opt lists every rule application with its number, function and statement on standard error. An unknown or malformed number is PLY0003.
  • --float strict|accurate (default accurate, ADR 0005): strict writes the portable, correctly rounded implementation of every floating-point function with a tolerance, so every target and profile returns the same bits; accurate calls the target's own function where its measured error is admitted and names each one with its comparison bound in the header of the file.
  • Manifest (PRD §10.2): beside the files, translate writes polypiler.manifest.json, which spec/schemas/manifest.schema.json describes: the compiler and IR version, the command line with its paths relative to the output directory, the SHA-256 of the input and of every file written, the source language, the target profile and runtime, the exported functions with their IR signatures, the intrinsics, the floating-point mode with every native function and bound the header of the file names, every helper the backend emitted with its origin, licence, call sites, size and dependencies, the licence of the output — the input's SPDX-License-Identifier header together with the helpers' MIT (LICENSE-OUTPUT.md), NOASSERTION without a header — the optimizations applied, the caveats of a JavaScript import and the warnings. Its state is generated: a manifest reaches built, executed or verified only with the build, run and oracle results recorded in it, and ManifestValidator refuses one that claims more (PLY0054) or breaks the schema (PLY0053). The text is canonical — the same output gives the same bytes, with no timestamp, host name or absolute path.
  • Gate states (PRD §23.6): the acceptance tests that run the generated code record how far each fixture got in artifacts/gates/<from>--<to>--<source-profile>--<target-profile>.json (spec/schemas/gate-record.schema.json), with the files that show it: C# to JavaScript per JavaScript profile (node-es2022-esm …), JavaScript to C# per C# profile. parsed needs a translation without an error, lifted and legalized the frontend's IR as the verifier and the target's check accept it, emitted the manifest of the translation, compiled, executed and verified a manifest that records the build, the run and the comparison with the compiled original or node on the original; recognition and proof are not recorded, since the rewrites are reported unproven. A pair is the lowest state of its fixtures. GateStore re-hashes every file and rejects a record that claims more than its evidence (PLY0058); a C# profile whose code an earlier profile runs reaches compiled only.
  • Equivalence proofs (docs/quality/VERIFICATION.md): a rewrite is handed over as a ProofObligation - before and after IR in the notation of ADR 0002, inputs, preconditions. ExhaustiveProver evaluates every input of up to 24 bits with the IR interpreter (proof class exhaustive-8bit for a width-generic obligation); SmtBitvectorProver asks Z3 (NuGet Microsoft.Z3 4.11.2) at 16, 32 and 64 bits and re-evaluates every model with the interpreter (smt-bitvector). A counterexample is PLY0056, a too large domain PLY0057, a timeout or vacuous preconditions PLY0055 (the rewrite stays off), floating point, memory and calls PLY0062. No rule engine asks them yet.
  • Command line (ADR 0004): polypiler [--diagnostics text|json] [--quiet] <command> [arguments] [options]; polypiler help <command> and <command> --help print a command's operands and options. Diagnostics go to standard error, as text or, with --diagnostics json, one JSON object per line; --quiet leaves infos and warnings off. A command line the grammar refuses is one diagnostic and nothing else: PLY0002 for an unknown command, PLY0003 for an unknown option, a missing value or operand, a repeated option or an empty list item, PLY0011 for two options that exclude each other.
  • Exit codes: 0 success, 1 a file that cannot be read or written (PLY0004 for the source, PLY0005 for the output directory), 2 usage error (PLY0002, PLY0003, PLY0011), 3 unsupported construct (PLY1002 in the source, PLY1052 for IR the C# backend cannot write, PLY1053 for IR that has no form in the chosen C# profile, PLY1152 for IR that has no form in the chosen JavaScript profile — nothing today), 4 invalid C# (PLY1000, or PLY1003 for a constant expression that overflows, each with the compiler's own message), 70 internal error (PLY0101 when the float implementations the executable carries precomputed are missing or damaged, PLY0001 for any exception nothing anticipated, which a stack trace follows on standard error only with POLYPILER_DEBUG=1), 130 a run cancelled by the user. The exit code is the one of the first error reported, 70 once PLY0001 was; in text format a command that ran and reported something ends standard error with polypiler: <e> error(s), <w> warning(s). polypiler help exit-codes prints the whole table of PRD §10.1, with the codes no command raises yet.

The pair C# → JavaScript is executed on the fixtures in tests/fixtures/prototype, tests/fixtures/prototype/wide, tests/fixtures/prototype/bits and tests/fixtures/prototype/records: every call of every fixture has the same outcome in node, in the IR interpreter and in the fixture as the C# compiler built it — in every profile and module format, where each generated file is also parsed at the language level it claims. The pair C# → C# is executed on the same fixtures, in each of the nine profiles: the generated file compiles in the profile's language version against the reference assemblies of the profile's framework with warnings as errors, and every call has the same outcome in the generated C#, compiled for the running runtime with and without overflow checking, in the interpreter and in the fixture itself. The files are run on .NET 10 only — what the runtime of an older framework does with them is not measured. Neither pair is verified.

Run the prototype: JavaScript to C# or JavaScript

# Works today: two functions of Cipher's OpCodes.js, pinned in this repository, become ./generated/OpCodes.cs
dotnet run --project Polypiler.Cli -c Release -- translate tests/fixtures/prototype/js/OpCodes.js \
  --from javascript --to csharp --export RotL32,RotR32 --namespace Cipher --output ./generated

# JavaScript without a single annotation goes through the same IR and comes out as a module again; this prints 300286872
dotnet run --project Polypiler.Cli -c Release -- translate tests/fixtures/prototype/js/untyped/adler32.mjs \
  --from javascript --to javascript --output ./generated --explain-types
node --input-type=module -e "import { compute } from './generated/adler32.mjs'; console.log(compute(new TextEncoder().encode('Wikipedia')))"

--explain-types prints why every parameter, local and result has its type — the first expression that decided it, with line and column. For compute:

tests/fixtures/prototype/js/untyped/adler32.mjs: type compute: parameter data: u8[] from 'new Uint8Array([87, 105, 107, 105, 112, 101, 100, 105, 97])' at (17,18)
tests/fixtures/prototype/js/untyped/adler32.mjs: type compute: local a: u32 from '((a + data[i]) % 65521) >>> 0' at (9,9)
tests/fixtures/prototype/js/untyped/adler32.mjs: type compute: local b: u32 from '((b + a) % 65521) >>> 0' at (10,9)
tests/fixtures/prototype/js/untyped/adler32.mjs: type compute: local i: f64 from 'i++' at (8,36)
tests/fixtures/prototype/js/untyped/adler32.mjs: type compute: result: u32 from '((b << 16) | a) >>> 0' at (12,10)

JavaScript has no static types. This importer models what JavaScript itself does — a number is a double — and makes an integer of a value only where the program proves it is one. It never guesses from a name, from a literal alone or from typical usage.

  • Which functions: function declarations, export function, the declarations directly inside the one immediately invoked function that wraps the file (helpers nothing outside can call), and the function-valued properties of an object literal that stands in either place, also of a literal inside it (O.Bits.low(x)). --export <name>[,<name>...] imports the named functions and what they call; without it every function of the file must import. Only the functions are read — what a file does while it loads is not — and the constants around them: a const of a number, or of a list of numbers or a typed array of listed numbers that the file only ever reads an element or the length of.
  • A number is a double: + - * / % are double arithmetic with NaN, both zeros and the infinities; | & ^ ~ << >> work on ToInt32 of their operands and >>> on ToUint32, exact also beyond 2^53; a number as a condition is false for a zero and a NaN; Math.imul, clz32, fround, trunc, floor, ceil, round (half up), abs, sign, min, max and sqrt mean what they mean in JavaScript. == and != are accepted between two values of one kind, where they are === and !==.
  • Integers where the program proves them: a local, a parameter of a function nothing outside can call, or a result is an int32 or uint32 when every value that reaches it comes from a bitwise operator, >>> 0, Math.imul, Math.clz32, an element of a typed array, a length, an integer literal in range, a variable already so typed, or +/- of such values directly under a coercion — (a + b) | 0 is the wrapping addition, because the exact sum of 32-bit integers is a double. (a * b) | 0 stays a double multiplication followed by the conversion: its exact value can exceed 2^53. A mask (& 0xFF, & 0xFFFF) or a small typed array proves an 8- or 16-bit integer. A place that integers and other numbers reach is a double; i++ is i + 1 in doubles, so a loop counter is one.
  • Parameters: JSDoc states a contract — @param {type} name with int8, uint8, int16, uint16, int32, uint32, int64, uint64, number/float64, float32, boolean, type[] or the name of a typed array — and a call inside the file that passes something else is refused. Without JSDoc a parameter of an exported function is a double, unless the function reads it under ToInt32/ToUint32 only or re-assigns it coerced before anything else (x = x | 0): then it is that integer. A parameter used as an array needs JSDoc, or a call in the same file that shows which array it is. @returns is taken where it holds every value the function returns.
  • 64-bit integers: a BigInt is accepted where the program bounds it — a literal, BigInt.asUintN(64, …) and BigInt.asIntN(64, …) with + - * & | ^ ~, <<, >>, / and % directly inside, BigInt(x) of a proven integer, BigUint64Array/BigInt64Array, JSDoc uint64/int64.
  • Statements and arrays: if, while, do … while, for, switch on an integer whose sections end in break, return or continue, break, continue, compound assignment and ++/-- on variables and array elements, let x; when an assignment precedes every read. Every typed array, array literals of numbers and new Array(n) of a proven integer n filled by indexed stores, typed by what is stored in them.
  • Everything else is refused, not approximated, each with its position, one diagnostic per refused function, and nothing is written: strings, objects, classes, this, closures, generators, exceptions, growable arrays (push, pop), a switch section that falls through, a var used outside its block and a JSDoc contract a call does not keep are PLY1102; a JSDoc type the importer does not know and an array parameter nothing gives a type are PLY1101; a BigInt that nothing bounds is PLY1103; a variable that holds values of two kinds (a number and an array, say) is PLY1105; a variable that may be read before it is assigned is PLY1106.
  • Known differences are announced: where the imported code cannot behave like the original, the command says so in a note. js-oob-read: at an index that is not the integer of an element JavaScript reads undefined and lets an Array grow; where that value is returned or computed with before a coercion the imported code traps, and takes an index that is a double without its fraction. A read directly under ToInt32, ToUint32 or ToNumber is 0 or a NaN outside the array and a store into a typed array is made only inside it, as in JavaScript, and an index the program proves inside needs no note. js-div-zero: a remainder of non-negative integers that is no operand of a coercion, a BigInt division and a quotient whose dividend has an effect trap on a zero divisor; (a / b) | 0 and (a % b) >>> 0 of two integers are 0 there, as in JavaScript (import differences). js-param-integer-inferred and js-param-array-inferred name the parameters that got an integer or an array type without JSDoc: JavaScript coerces or takes whatever is passed, the imported function takes that type.
  • Exit codes: as above, with 3 for PLY1101 to PLY1106 (PLY1104: --export names a function the file does not have) and 4 for a syntax error (PLY1100, with the parser's own message).

Of the 155 functions that stand directly in the OpCodes object, 103 import today — all 37 that imported while every type had to be stated in JSDoc among them; tests/fixtures/prototype/js/OpCodes.import.txt lists every one with the reason it is refused. The pairs JavaScript → JavaScript and JavaScript → C# are executed on the fixtures in tests/fixtures/prototype/js — node running the original is the oracle, a double compared by its bits — not verified.

Verify a generated directory

# Works today: checks the JavaScript of a generated directory with node, calls its adler32 on every vector and
# compares; prints "tests/fixtures/cli/verify/adler32-js: verified (4 of 4 vectors)" and exits with 0
dotnet run --project Polypiler.Cli -c Release -- verify tests/fixtures/cli/verify/adler32-js \
  --against tests/fixtures/cli/verify/adler32.vectors.json --no-update --evidence ./artifacts/evidence

verify re-establishes from a directory and its polypiler.manifest.json alone whether the output still builds, runs and matches independent vectors (docs/cli/verify.md): it recomputes the hash of every listed output (an edited file is PLY0054 and nothing runs), reads a vector file of the oracle framework (--against, or the one the manifest recorded), checks every JavaScript source with node --check, calls the function the vector file exports once per vector in the sandbox and compares the outputs under the file's exactness policy. Each vector is a pass or FAIL expected <e> actual <a> line. The manifest's build, execution and verification are then rewritten to what this run found — a verified manifest that now fails goes back to executed — unless --no-update is given; --evidence <directory> writes an evidence bundle. PLY0016 for a directory without a manifest, PLY0017 for a vector file that is not one, PLY0063 when no independent oracle is left. Only JavaScript output is run so far.

Translate an existing algorithm

# A JavaScript checksum from Cipher to a compiled C# library
polypiler translate path/to/Cipher/algorithms/checksum/example.js \
  --from javascript --to csharp --runtime net9.0 \
  --verify --output ./generated/checksum-csharp

# A PowerBASIC numeric kernel to Rust
polypiler translate path/to/example.bas \
  --from powerbasic --dialect pb35 --to rust \
  --verify --output ./generated/example-rust

# A Kotlin CPU deinterlacer to Perl
polypiler translate path/to/Deinterlacer.kt \
  --from kotlin --to perl --profile perl5 \
  --verify --output ./generated/deinterlace-perl

Translate a lower-level representation

# LLVM bitcode, preserving supported ABI/effect contracts
polypiler translate kernel.bc --from llvm --to csharp \
  --verify --output ./generated/kernel-csharp

# A supported C# algorithm as an 8086 DOS executable
polypiler translate Checksum.cs --from csharp --to x86-16 \
  --os dos --cpu 8086 --verify --output ./generated/checksum-dos

# A 6502 binary routine to C# (machine profile/entry point required)
polypiler recover checksum.bin --from mos6502 --to csharp \
  --cpu mos6502 --entry 0x8000 --verify --output ./generated/checksum-csharp

Inspect and verify optimizations

polypiler inspect path/to/algorithm.cs --from csharp \
  --show types,ranges,effects,patterns,ir,proofs

polypiler capabilities --from kotlin --to perl --profile perl5

polypiler verify ./generated/checksum-csharp \
  --against ./tests/fixtures/checksum-vectors.json

Generate an existing catalogue algorithm

polypiler search "Floyd-Steinberg"
polypiler generate color.dithering.floyd-steinberg \
  --to rust --verify --output ./generated/floyd-steinberg

The catalogue and publishing workflows are later deliverables. A generated package is not automatically published to NuGet, crates.io, npm, CPAN, PyPI or any other registry.

📚 Documentation

Before starting work, follow the issue-writing standard and its Ready and Blocked examples.

Start with the documentation index, then follow the end-to-end compilation flow, IR and analysis contracts, semantic recovery, foreign interoperability, and verification gates. The full PRD remains the normative implementation plan; these pages describe the proposed design, not shipped features.

Every diagnostic code Polypiler reports, from PLY0001 on, has a page in the error catalogue: its severity, its exit code and what to do about it. The catalogue is generated from spec/diagnostics.yaml by polypiler-tooling report errors, and CI refuses a copy that is out of date.

🔬 What makes it different

Recover semantics before optimizing

An algorithm may already contain hand-written bit tricks, custom unrolling, interleaved computations, compiler-generated state machines, or inline assembly. Polypiler aims to recognize operations such as PopCount, Min, Max, multiplication, bit permutation, memory copy, matrix multiplication, loop maps/reductions and deterministic disposal regardless of the particular implementation pattern.

Recognition and instruction selection are separate. For example, the same recovered bit permutation might become PEXT/PDEP on a compatible CPU, masks and shifts on another, or an 8-bit assembly routine on a 6502. A recognized sequence is rewritten only when its equivalence preconditions and effects are proven.

One optimization middle-end, many frontends and backends

The intended architecture is:

flowchart TB
  Inputs["Source, bytecode or machine code"] --> IR["Frontend and semantic lifting<br/>Typed IR with explicit effects"]
  IR --> Transform["Analyze and recover operations<br/>Prove legal rewrites"]
  Transform --> Target["Legalize target and ABI<br/>Emit source, IR or binary"]
  Target --> Verify["Compile, execute and compare"]
  Oracle["Independent source oracle"] --> Verify
  Verify --> Evidence["Manifest and support evidence"]
Loading

The IR must preserve source-language arithmetic, conversions, ownership, error handling, runtime identity and observable effects. Native operations and external code are neither discarded nor treated as permanently opaque if their semantics can be recovered.

Specialize dynamic code into typed code

When an algorithm's actual values and call contracts permit it, Polypiler should recover concrete types from JavaScript, Python and Perl and replace dynamic objects, conversions and boxed collections with typed values, arrays, records, spans or buffers. Speculative fast paths require guards and valid fallbacks; only proven cases can be lowered without runtime checks.

Support old and new machines

The target profile may describe .NET 9, .NET Framework 2.0-compatible helper code, modern x86/x64, ARM, GPU/NPU runtimes or 8086/6502-class systems. Bounds checks, integer widths, pointers, banked memory, CPU flags, stack behavior and memory-mapped I/O are part of the compilation problem—not implementation details the translator can ignore.

Preserve foreign libraries and ABIs

Polypiler should generate native target-language bindings for recognized external calls: for example, C declarations using a DLL can become PowerBASIC DECLARE ... LIB ... ALIAS declarations for the same compatible Windows DLL.

It must also synthesize binary-compatible target UDTs, byte-backed records, pack/unpack marshaling, unaligned accessors and ABI bridge code when native target representations have different padding, alignment or calling conventions. A byte-compatible structure is not necessarily callable by value under another ABI. Unknown external calls or memory effects are preserved or explicitly diagnosed, never erased.

Lower rich language features to constrained targets

Generics, classes, abstract classes, interfaces, multiple/diamond inheritance, anonymous types, structural records, enums, closures, overloads, operator overloads, variadic functions, type-switch and pattern-matching expressions, exceptions, On Error Resume Next, using, RAII, generators, coroutines, async/await and iterators should be represented semantically.

When the target lacks a feature, Polypiler can specialize it away or generate explicit UDTs, dispatch tables, state machines, cleanup control flow and minimal runtime helpers. Observable behavior must be preserved. A real-time DOS or 6502 target may reject capabilities its environment cannot implement within its resource constraints.

💡 Prior art and reference corpora

Polypiler is designed to build on, and later gradually replace duplicated compiler functionality in, existing projects. Those projects remain independently usable until verified migration gates pass.

Project Candidate contribution
PB-Compiler Typed SSA, range/known-bits passes, PowerBASIC semantics, LLVM emission, x86-16 backend and emulation oracles
Cipher JavaScript type-aware frontend, AST/IL pipeline, language emitters, cryptographic algorithms and test vectors
BitPerm Bit-routing model, heuristic/Dijkstra synthesis, CPU cost profiles and building-block tests
BitBench Bit-width, encoding, numeric and format catalogue
C--FrameworkExtensions Legacy and unusual numeric types, fixed point, Float80/MBF, BCD, Posit, image/color algorithms
Randomizer Deterministic RNG algorithms and independent test vectors
CompressionWorkbench Bitstream algorithms, compression codecs, tests and corpora
PNGCrushCS Image format implementations and binary processing tests
MediaDroyd Kotlin CPU deinterlacing/motion algorithms, shaders and optional native NN integration

The first Kotlin→Perl showcase targets the actual MediaDroyd Deinterlacer.kt, not a synthetic substitute. Derivative implementations must respect the file's documented FFmpeg/GStreamer licensing and attribution. NCNN-backed interpolation is initially a provider-backed Rust adapter; a pure Rust neural implementation additionally requires model/operator/weight conversion and appropriate licenses.

🗺️ Roadmap

The complete product contract, implementation phases, architecture and acceptance tests are in PRD.md. That document is authoritative for agent work; this README is an overview and planned user experience.

The initial milestone is deliberately narrow: set up a reproducible repository and build an actual CLI that translates a pinned Cipher JavaScript algorithm → C# and a PowerBASIC algorithm → C#, compiling and executing generated code against independent known-answer vectors. Only expand the advertised language matrix when those gates pass.

At project bootstrap, the agent should:

  1. Read docs/PRD.md and upstream AGENTS.md files, pin sources/toolchains, and inventory licenses and existing tests.
  2. Create Polypiler.slnx, .editorconfig, AGENTS.md, versioned specifications, NUnit tests and CI on a feature branch.
  3. Implement typed/effect-aware IR, verification, real JavaScript and PowerBASIC imports and C# emission; add runnable acceptance tests and negative diagnostics.
  4. Merge only via reviewed, green PRs with linear history. Never push directly to main, master or trunk.

For regular compiler projects, target .NET 10 and current stable C# features; keep framework compatibility backports separate, with .NET Framework 2.0 as their compatibility baseline where applicable. The repository's C# style and testing conventions are specified in the PRD and AGENTS.md.

📈 Optimizations

Recognizing what code computes and choosing a better form for the target is the middle of the product. Every optimization, recognition rule and lowering rewrite has an identifier (O####), a page with an example before and after, the conditions under which it applies, the cases in which it must not fire, and a switch to turn it off.

The optimization checklist lists all of them with their state: 33 of 294 are implemented today in the pipeline of translate; reciprocal division (O0126) is accepted on an exact certificate; SWAR population count (O0102), zero-count loops (O0103), de Bruijn bit scans (O0104), bit reversal (O0105), byte swap (O0106), single-bit operations (O0108), parity (O0110), minimum and maximum (O0120), wrapping magnitude (O0121), signum (O0122) and shift-add multiplication (O0125) require SMT equivalence proofs before rewriting. The families from "Loop transformations" on are borrowed from PB-Compiler; the catalog maps each of its 424 optimization documents to the page here that covers it.

Family Planned
General passes — folding, propagation, dead code, loops, vectors 30
De-dynamicization — typing JavaScript, Python and Perl 7
Legalization — expressing what a target lacks 10
Recognition and recovery — rotates, popcounts, CRCs, de-unrolling 57
Bit permutations 10
Language-construct lowering and recovery — generics, classes, exceptions, coroutines 30
Interop and layouts 2
Loop transformations — induction variables, fusion, interchange, versioning 29
Memory and data layout — store and load motion, structure layout, lookup tables 23
Redundancy — reassociation, reciprocal reuse 5
Value propagation and arithmetic rewrites — path facts, speculation with side exits 17
Interprocedural — constants across calls, cloning, lambda specialisation, call merging, dead functions and globals 19
Vectorization refinements — alignment, tails, alias versioning 11
Control-flow shaping and block layout — dispatch tables, jump threading, block placement 20
Profile-guided 9
Strings 13
Target emission — passes over the backends' syntax trees: helper inlining, unused declarations 2

🏗️ Architecture

The planned monorepo contains these internal components, all under the Polypiler product name:

Component Responsibility
Polypiler.Core IR, frontends/backends, type/range analysis, semantic recovery, optimization, legalization
Polypiler.Base Portable semantic types, numbers, vectors, buffers, ownership, sequences and tensor operations
Polypiler.Permutation BitPerm-derived bit mapping recovery, composition, synthesis and cost selection
Polypiler.Interop Native bindings, foreign ABIs, layouts, UDT synthesis and marshalling plans
Polypiler.Catalog Algorithm identities, reference vectors, verified target packages, provenance
Polypiler.Adapters Optional NCNN and other native compute/runtime integrations
Polypiler.Cli Translation, inspection, verification, capability reporting and catalogue commands

The implementation is initially C# on .NET 10, with NUnit-based testing and a language-neutral, versioned IR specification. Older .NET and non-.NET output targets receive generated compatible code rather than depending on the compiler's own runtime.

Semantic correctness is a release gate

Support states are reported at the granularity of source language/version, source construct, target language/version, target ABI/architecture/runtime and optimization configuration:

State Meaning
planned Specified, not implemented
experimental Prototype exists; full execution/equivalence gate not met
compiled Destination compiler accepts the generated output; behavior not yet verified
executed Output runs with test inputs; complete conformance not yet established
verified Independent source/target oracles and required semantic/effect tests pass
unsupported / blocked Not implemented or cannot be verified in the configured environment

For optimizations, a successful pattern match is not a correctness proof. Polypiler will use proof preconditions, range and alias analysis, exhaustive small-width tests, differential testing and SMT bitvector reasoning where applicable. An unknown or timed-out proof must not silently authorize a rewrite.

⚠️ Limitations

  • Translating an algorithm is not equivalent to translating an entire language runtime, OS, object model or native library.
  • Foreign calls, inline assembly, volatile/memory-mapped I/O, arbitrary memory writes, exception semantics, reflection and runtime effects must be preserved or explicitly rejected.
  • An ABI-compatible layout needs more than matching field names; padding, alignment, byte order, by-value classification, calling convention and lifetime are part of the contract.
  • Some sources, especially neural implementations and model weights, have additional license restrictions. Their presence in an upstream repository does not authorize copying or redistributing them.
  • Legacy hardware has concrete resource limits and potentially timing-sensitive behavior. Performance improvements are measured, never assumed.
  • Untrusted source code and generated native artifacts must be tested in isolated environments with pinned toolchains and resource limits.
  • Imported code, generated derivative works, model weights and native dependencies keep their own licences and require per-source provenance checks; the licences of PB-Compiler, Cipher, BitPerm, MediaDroyd and third-party libraries are not assumed to be interchangeable.
  • The helper and runtime code Polypiler emits into generated outputs is MIT (LICENSE-OUTPUT.md), while the compiler stays LGPL-3.0-or-later: a translated program keeps the licence of its source. Helpers converted from third-party code keep their own permissive licence; the header of a generated file names the licence of its helpers, and the manifest lists each one with its origin.

🛠️ Building

dotnet build Polypiler.slnx -c Release
dotnet test Polypiler.slnx -c Release   # everything
dotnet test Polypiler.slnx -c Release --filter "TestCategory!=Slow&TestCategory!=EndToEnd&TestCategory!=OsIntegration&TestCategory!=ExternalInterop&TestCategory!=PolyglotInterop&TestCategory!=Performance"   # the fast tier

Requires the .NET 10 SDK. CONTRIBUTING.md covers the test tiers, CI and releases.

🤝 Contributing

Contributions should start with an IR/semantic contract and a positive and negative test case, not just an emitter that produces plausible source. A supported translation requires a real target compiler/runtime, a separately executed reference oracle and documented limitations. The agent-specific workflow, branch rules, coverage targets and PR checklist are in PRD.md.

❤️ Support

If this project saves you time or money, consider supporting its development:

GitHub Sponsors PayPal

📜 License

Licensed under LGPL-3.0-or-later — see LICENSE.

About

Polypiler — verified cross-language optimizing compiler and transpiler. Translates algorithms between C#, JavaScript, Rust, C/C++, Kotlin, Python, Perl and PowerBASIC, and lifts LLVM IR, MSIL, JVM, WebAssembly, x86, ARM and 6502 machine code back to readable, tested source.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages