Giter Site home page Giter Site logo

pyrs's Introduction

Python to Rust transpiler

This project started as Python to Rust syntax converter. It is not aimed at producing ready-to-compile code, but some basic stuff can be compiled easily (see Examples).

It generates unidiomatic non-optimized code with unnecessary allocations, but can reduce amount of edits you have to do when porting Python projects.

Only basic subset of Python is supported right now and the end goal is to support common cases at least as a placeholders.

The project is in experimental, so it may crash or silently skip some statements, so be careful.

Based on Lukas Martinelli Py14 and Py14/python-3 branch by Valentin Lorentz.

Example

Original Python version.

if __name__ == "__main__":
    things = ["Apple", "Banana", "Dog"]
    animals = []
    for thing in things:
        if thing == "Dog":
            animals.append(thing)
    
    print(animals)

Transpiled Rust code.

use std::*;

fn main() {
    let mut things = vec!["Apple", "Banana", "Dog"];
    let mut animals = vec![];
    for thing in things {
        if thing == "Dog" {
            animals.push(thing);
        }
    }
    println!("{:?}", animals);
}

Trying it out

Requirements:

  • python 3
  • rustc

Transpiling:

python3 ./pyrs.py test.py > test.rs

Formatting(optional):

rustfmt test.rs

Compiling:

rustc test.rs

Using in directory mode

It is possible to convert whole directory recursively. It won't throw exception if some files cannot be converted. The following command will create projectname-pyrs folder alonside your project directory. Relative path is also supported. This mode invokes rustfmt automatically for every file.

python3 ./pyrs.py /home/user/projectname

More examples

if __name__ == "__main__":
   numbers = [1,5,10]
   multiplied = list(map(lambda num: num*3, numbers))
   
   comprehended = [n - 5 for n in multiplied if n != 3]

   print("result is", comprehended)

Transpiles to

fn main() {
    let mut numbers = vec![1, 5, 10];
    let multiplied = numbers.iter().map(|num| num * 3).collect::<Vec<_>>();
    let comprehended = multiplied
        .iter()
        .cloned()
        .filter(|&n| n != 3)
        .map(|n| n - 5)
        .collect::<Vec<_>>();
    println!("{:?} {:?} ", "result is", comprehended);
}

Classes

from chain.block import Block

class Genesis(Block):
    def __init__(self, creation_time):
        self.timestamp = creation_time
        self.prev_hashes = []
        self.precalculated_genesis_hash = Block.get_hash(self)
    
    def get_hash(self):
          return self.precalculated_genesis_hash

Will yield

use chain::block::Block;

struct Genesis {
    timestamp: ST0,
    prev_hashes: ST1,
    precalculated_genesis_hash: ST2,
}

impl Genesis {
    fn __init__<T0>(&self, creation_time: T0) {
        self.timestamp = creation_time;
        self.prev_hashes = vec![];
        self.precalculated_genesis_hash = Block::get_hash(self);
    }
    fn get_hash<RT>(&self) -> RT {
        return self.precalculated_genesis_hash;
    }
}

This one won't compile. All unknown types are labeled. T stands for Type, RT is for Return Type and ST is for Struct Type. Ordering them this way enables you finding and replacing them in the future.

Monkeytype

Python 3.5+ type annotations can be transpiled:

def cut(apple: Fruit, knife: Tool) -> Slice:
fn cut(apple: Fruit, knife: Tool) -> Slice {

I would highly suggest to generate type annotations using MonkeyType. This will allow to mitigate aforementioned generic types problem for classes and functions. More info on how to do that can be found in this post.

Todo list

  • Basic type inference for struct declaration
  • Use constructors for guessing struct member types
  • Return type inference
  • Mutability based on usage

Working Features

Only bare functions using the basic language features are supported. Some of them work partially.

  • classes
  • functions
  • lambdas
  • list comprehensions
  • inheritance
  • operator overloading
  • function and class decorators
  • getter/setter function decorators
  • 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

  • dict
  • list
  • tuple
  • int
  • float
  • str
  • round
  • range
  • range_step
  • sum
  • len
  • map
  • filter

Data Structures

  • list
  • Set
  • String
  • Dict

pyrs's People

Contributors

ghuls avatar jayvdb avatar joshmcguigan avatar konchunas avatar lukasmartinelli avatar molysgaard avatar progval avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.