Git Product home page Git Product logo

py2star's Introduction

py2star

Converts python files to starlark files

Get started quickly

Setup

python -m venv venv
source venv/bin/activate
python setup.py install

Run

cd src/py2star
python cli.py larkify ~/src/pycryptodome/lib/Crypto/SelfTest/PublicKey/test_RSA.py > test_RSA.star
python cli.py tests test_RSA.star >> test_RSA.star

Differences with Python

The list of differences between Starlark and Python are documented at https://bazel.build site:

Some High-level Differences

  • Global variables are immutable.
  • for statements are not allowed at the top-level. Use them within functions instead.
  • if statements are not allowed at the top-level. However, if expressions can be used: first = data[0] if len(data) > 0 else None.
  • Deterministic order for iterating through Dictionaries.
  • Recursion is not allowed.
  • Modifying a collection during iteration is an error.
  • Except for equality tests, comparison operators <, <=, >=, >, etc. are not defined across value types. In short: 5 < 'foo' will throw an error and 5 == "5" will return False.
  • In tuples, a trailing comma is valid only when the tuple is between parentheses, e.g. write (1,) instead of 1,.
  • Dictionary literals cannot have duplicated keys. For example, this is an error: {"a": 4, "b": 7, "a": 1}.
  • Strings are represented with double-quotes (e.g. when you call repr).
  • Strings aren't iterable (WORKAROUND: use .elems() to iterate over it.)

The following Python features are attempted to be automatically converted:

  • most builtin functions, most methods.
  • set types (WORKAROUND: use sets.star instead)
  • [ ]implicit string concatenation (use explicit + operator).
  • Chained comparisons (e.g. 1 < x < 5)`.
  • class (see larky.struct function).
  • import (see load statement).
  • while.
  • generators and generator expressions.
  • is and is not (use == and != instead, respectively).
  • raise (see fail for fatal errors).
  • try, except, finally. (see fail for fatal errors).
  • yield.
  • global, nonlocal.

Automatic Conversion

  • py2star.fixes.fix_declass -- de-classes and de-indents a class

So, it goes from:

class Foo(object):
    def bar(self):
        return "baz"

To:

def bar(self):
    return "baz"

py2star's People

Contributors

la-luo avatar mahmoudimus avatar moehajj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

py2star's Issues

slice mutation with list

__setslice__(i, j, sequence) i.e. seq[i:j] = sequence

    def __setslice__(i, j, sequence):
        for atom in sequence:
            if i >= j:
                break
            _seq.remove(i)
            _seq.insert(i, atom)
            i += 1

Checklist

  • raise XXXX => fail()
  • self => callablestruct (?)
  • is => ==
  • is not => !=

Desugar decorators

Remove and desugar decorators. In python, a decorator is syntactic sugar for: func = decorator(func), we can just desugar this.

Also, built-in decorators such as @classmethod and @staticmethod do not exist and may be safely re-written.

Some misc issues

  • codecs.encode() transform can mess up
  • while True: ... does not transform properly
  • dict.fromkeys(p256_names, p256) => {k: p256 for k in p256_names}

Option to automatically unwrap errors

raise ValueError("Foo")

becomes:

return Error("Foo")

but we would like it to be:

return Error("Foo").unwrap() # notice the unwrap 

This should be an option that we pass in to disable/enable this behavior as sometimes Result/Error object pattern is not desired and immediate fail is necessary.

Convert constructors

Class

class BytesIO_EOF(object):
    """This class differs from BytesIO in that a ValueError exception is
    raised whenever EOF is reached."""

    def __init__(initial_bytes):
        _buffer = initial_bytes
        _index = 0
        _bookmark  = None
  
    def set_bookmark():
        _bookmark = _index

Converting to this function

def BytesIO_EOF(initial_bytes):
    """This class differs from BytesIO in that a ValueError exception is
    raised whenever EOF is reached."""

       self = larky.mutablestruct(
             _buffer = initial_bytes
             _index = 0
             _bookmark  = None
         )

    def set_bookmark(self):
           self._bookmark = self._index

    return larky.struct(
             self = self,
             set_bookmark=larky.partial(set_bookmark, self)
             __class__='BytesIO_EOF'
         )
    return self
    

Missing prefixes when using `@property` annotation

Missing larky. prefix for property() method, and self. prefix for internal method variable.

Example:

input .py:

@property
def name(self):
    return self.get_name()

output .star:

def name():
    return self.get_name()
self.name = name
name = property(name)

should be:
~ ~name = larky.property(name)~ ~

(edit by @mahmoudimus ):

def name():
    return self.get_name()
self.name = larky.property(name)

for/else

for i in range(len(s)):
     if i < 5:
        break
else:
    print("s has length >= 5!")

to:

didbreak = False
for i in range(len(s)):
     if i < 5:
        didbreak = True
        break
if not didbreak:
    print("s has length >= 5!")

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.