• This repository has been archived on 03/Jun/2018
  • Stars
    star
    573
  • Rank 77,865 (Top 2 %)
  • Language
    C++
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python to C++ 14 transpiler

Python to C++ 14 transpiler

Wercker Status Coverage Status Scrutinizer Code Quality Code Health

⚠️ This repository is no longer actively maintained by Lukas Martinelli.

This is a little experiment that shows how far you can go with the C++ 14 auto return type and templates. C++14 has such powerful type deduction that it is possible to transpile Python into C++ without worrying about the missing type annotations in python. Only a small subset of Python is working and you will encounter many bugs. The goal is to showcase the power of C++14 templates and not to create a fully functional transpiler.

Example

Original Python version.

def factorial(num):
	if num <= 1:
		return num
	return factorial(num-1) * num

Transpiled C++ template.

template <typename T1> auto factorial(T1 num) {
	if (num <= 1) {
		return num;
	}
	return factorial(num - 1) * num;
}

How it works

Consider a map implementation.

def map(values, fun):
	results = []
	for v in values:
		results.append(fun(v))
	return results

This can be transpiled into the following C++ template.

template <typename T1, typename T2>
auto map(T1 values, T2 fun) {
	std::vector<decltype(
		fun(std::declval<typename decltype(values)::value_type>()))> results{};
	for (auto v : values) {
		results.push_back(fun(v));
	}
	return results;
}

The parameters and the return types are deduced automatically In order to define the results vector we need to:

  1. Deduce the type for v returned from the values range using v_type = typename decltype(values)::value_type
  2. Deduce the return type of fun for call with parameter v decltype(fun(v))
  3. Because we dont know v at the time of definition we need to fake it std::declval<v_type>()
  4. This results in the fully specified value type of the results vector decltype(fun(std::declval<typename decltype(values)::value_type>()))

Trying it out

Requirements:

  • clang 3.5

Transpiling:

./py14.py fib.py > fib.cpp

Compiling:

clang++ -Wall -Wextra -std=c++14 -Ipy14/runtime fib.cpp

Run regression tests:

cd regtests
make

Run tests

pip install -r requirements.txt
py.test --cov=py14

More Examples

Probability Density Function (PDF)

def pdf(x, mean, std_dev):
	term1 = 1.0 / ((2 * math.pi) ** 0.5)
	term2 = (math.e ** (-1.0 * (x-mean) ** 2.0 / 2.0 * (std_dev ** 2.0)))
	return term1 * term2
template <typename T1, typename T2, typename T3>
auto pdf(T1 x, T2 mean, T3 std_dev) {
	auto term1 = 1.0 / std::pow(2 * py14::math::pi, 0.5);
	auto term2 = std::pow(py14::math::e, -1.0 * std::pow(x - mean, 2.0) / 2.0 *
												std::pow(std_dev, 2.0));
	return term1 * term2;
}

Fibonacci

def fib(n):
	if n == 1:
		return 1
	elif n == 0:
		return 0
	else:
		return fib(n-1) + fib(n-2)
template <typename T1> auto fib(T1 n) {
	if (n == 1) {
		return 1;
	} else {
		if (n == 0) {
			return 0;
		} else {
			return fib(n - 1) + fib(n - 2);
		}
	}
}

Bubble Sort

def sort(seq):
	L = len(seq)
	for _ in range(L):
		for n in range(1, L):
			if seq[n] < seq[n - 1]:
				seq[n - 1], seq[n] = seq[n], seq[n - 1]
	return seq
template <typename T1> auto sort(T1 seq) {
	auto L = seq.size();
	for (auto _ : rangepp::range(L)) {
		for (auto n : rangepp::range(1, L)) {
			if (seq[n] < seq[n - 1]) {
				std::tie(seq[n - 1], seq[n]) = std::make_tuple(seq[n], seq[n - 1]);
			}
		}
	}
	return seq;
}

Working Features

Only bare functions using the basic language features are supported.

  • classes
  • functions
  • lambdas
  • multiple inheritance
  • operator overloading
  • function and class decorators
  • getter/setter function decorators
  • list comprehensions
  • yield (generator functions)
  • function calls with *args and **kwargs

Language Keywords

  • global, nonlocal
  • while, for, continue, break
  • if, elif, else
  • try, except, raise
  • def, lambda
  • new, class
  • from, import, as
  • pass, assert
  • and, or, is, in, not
  • return
  • yield

Builtins

  • dir
  • type
  • hasattr
  • getattr
  • setattr
  • issubclass
  • isinstance
  • dict
  • list
  • tuple
  • int
  • float
  • str
  • round
  • range
  • sum
  • len
  • map
  • filter
  • min
  • max
  • abs
  • ord
  • chr
  • open

Data Structures

  • list
  • Set
  • String
  • Dict

More Repositories

1

pgfutter

Import CSV and JSON into PostgreSQL the easy way
Go
1,311
star
2

pipecat

Connect UNIX pipes and message queues
Go
435
star
3

pgclimb

Export data from PostgreSQL into different data formats
Go
386
star
4

nigit

Web server that wraps around programs and shell scripts and exposes them as API
Go
383
star
5

redis-pipe

Treat Redis Lists like Unix Pipes
Go
283
star
6

postgis-editor

An accessible PostGIS query editor and visualizer.
JavaScript
192
star
7

mapbox-gl-inspect

Inspection plugin for Mapbox GL JS
JavaScript
142
star
8

naturalearthtiles

Natural Earth vector tiles (MVT) and raster tiles free and ready to use.
PLpgSQL
89
star
9

hwk

A Haskell based awk and sed alternative
Haskell
67
star
10

osm-noise-pollution

Approximate global noise pollution with OSM data and very simple noise model
Shell
66
star
11

php-dos-attack

Exploit json_decode vulnerability of PHP
PHP
35
star
12

osm-activity

Show global OpenStreetMap activity on a map
JavaScript
30
star
13

swissdem

Digital Elevation Model for Switzerland from SRTM (1 arc second / 25m) as download
Shell
17
star
14

osm-lakelines

Calculate nice centered linestrings for labelling OpenStreetMap lakes
Shell
15
star
15

px-to-csv

Convert PC-Axis files to CSV
JavaScript
14
star
16

mbtoolbox

MBTiles tools for optimizing and verifying MBTiles files
Python
13
star
17

push-it

Plays an encouraging sound when you do a git push
Shell
13
star
18

ghrr

Create realtime apps on top of GitHub
JavaScript
12
star
19

sharpen

Solve algorithmic Python challenges to sharpen the tools.
Python
11
star
20

detectivegit

Detective git takes a look at your repo and shows the hotspots and possible bugs.
JavaScript
9
star
21

osm-qa-filter

Extract GeoJSON features from OSM QA tiles
JavaScript
9
star
22

osm-simple-features

Defines an opinionated mapping from OSM to simple GeoJSON features with multiple layers and defined schemas.
JavaScript
7
star
23

swissnames

Curated extracts from the free swissNAMES3D data set from swisstopo.
Shell
5
star
24

delptr

Informs the world about people who still use naked pointers in C++
JavaScript
5
star
25

location-history-to-geojson

Turn your Google Location History into a GeoJSON feature collection
JavaScript
3
star
26

lukasmartinelli.github.io

Personal blog and portfolio.
HTML
2
star
27

battle-of-britain-map

A Mapbox GL map showcasing the air battle of Britain
CSS
2
star
28

biketour

Tracking my bike tour from Switzerland to Greece
HTML
1
star