Giter Site home page Giter Site logo

pytocs's Introduction

pytocs

Join the chat at https://gitter.im/uxmal/pytocs

Converts Python source to C#

pytocs is a command line tool I wrote as a hobby project to convert Python source code to C#. I've uploaded it here in case someone finds it useful.

How to run pytocs

Just git clone the project, and use Visual Studio or MSBuild to compile the pytocs.sln file. If you're unable or unwilling to build pytocs from source, the latest continuous integration build is available at appveyor.com.

Examples

To convert a Python file, hand it to pytocs:

pytocs foo.py

To convert all files in a directory (recursively), use the -r parameter:

pytocs -r 

The following python fragment:

# Some code below
def hello():
   print "Hello World";

Translates to:

public static class hello {

    public static object hello() {
	    Console.WriteLine("Hello World");
    }
}

A more ambitious sample:

class MyClass:
    # member function calling other function
    def calc_sum(self, x, y):
       return self.frobulate('+', x, y)

    # arithmetic and exceptions
    def frobulate(self, op, x, y):
        if op == '+':
            return x + y
        elif op == '-':
            return x - y
        else:
            raise ValueError("Unexpected argument %s" % op)

    # static method using for..in and enumerate, with tuple comprehension
    def walk_list(lst):
        for (i,strg) in lst.iterate():
            print "index: %d strg: %s\n" % (i, strg)
 
    # list comprehension, generating linQ output.
    def apply_map(mapfn, filterfn):
        return [mapfn(n) for n in lst if filterfn]

Translates to:

using System;

using System.Linq;

public static class readme {
    
    public class MyClass {
        
        // member function calling other function
        public virtual object calc_sum(object x, object y) {
            return this.frobulate("+", x, y);
        }
        
        // arithmetic and exceptions
        public virtual object frobulate(object op, object x, object y) {
            if (op == "+") {
                return x + y;
            } else if (op == "-") {
                return x - y;
            } else {
                throw new ValueError(String.Format("Unexpected argument %s", op));
            }
        }
        
        // static method using for..in and enumerate, with tuple comprehension
        public static object walk_list(object lst) {
            foreach (var _tup_1 in lst.iterate()) {
                var i = _tup_1.Item1;
                var strg = _tup_1.Item2;
                Console.WriteLine(String.Format("index: %d strg: %s\n", i, strg));
            }
        }
        
        // list comprehension
        public static object apply_map(object mapfn, object filterfn) {
            return (from n in lst
                where filterfn
                select mapfn(n)).ToList();
        }
    }
}

Roadmap

The next big items on the list are:

  • Take the types that are inferred and apply them to the code to get away from everything being object.
  • Place local variable declarations at the statement that dominates all definitions of said variables.

pytocs's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytocs's Issues

Exceptions/Errors construction after translation

The following code is a valid python code:

def funcy():
    raise NotImplementedError()

should be translated to

public void funcy() {
    throw new NotImplementedError();
}

Currently it is translated to:

public void funcy() {
    throw NotImplementedError();
}

Also, NotImplementedError should be translated to NotImplementedException which is the C# version.

Async

Hi
This Application Not Support 'Async' and 'Await' Terms.

{"- (1): Expected token type NEWLINE, but saw ID."}

When I open the project in visual studio and try to run the command 'pytocs hello.py' i get an exception.

at Pytocs.Syntax.Parser.Expect(TokenType tokenType) in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Syntax\Parser.cs:line 460
at Pytocs.Syntax.Parser.simple_stmt() in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Syntax\Parser.cs:line 822
at Pytocs.Syntax.Parser.stmt() in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Syntax\Parser.cs:line 792
at Pytocs.Syntax.Parser.d__4.MoveNext() in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Syntax\Parser.cs:line 336
at Pytocs.Translate.ModuleTranslator.Translate(IEnumerable1 statements) in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Translate\ModuleTranslator.cs:line 42 at Pytocs.Translator.TranslateModuleStatements(IEnumerable1 stm, State moduleScope, TextWriter output) in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Translator.cs:line 78
at Pytocs.Translator.Translate(String filename, TextReader input, TextWriter output) in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Translator.cs:line 55
at Pytocs.Program.Main(String[] args) in C:\Users\b\Downloads\pytocs-master\pytocs-master\src\Program.cs:line 37

how to use pytocs

I am new to python and was unable to use your pytocs to convert to c# code can you just specify what we have to do install pytocs or how to use it

Unordered __init__ arguments

The arguments in the __init__ function are unordered and some don't have default value.
This causes the parsing to fail.
Removing all default values and astrix fixed fixes the parsing.

# this code is taken from official tensorflow repository
class OffPolicyRLModel(BaseRLModel):
    def __init__(self, policy, env, replay_buffer, verbose=0, *, requires_vec_env, policy_base, policy_kwargs=None):
        super(OffPolicyRLModel, self).__init__(policy, env, verbose=verbose, requires_vec_env=requires_vec_env,
                                               policy_base=policy_base, policy_kwargs=policy_kwargs)

        self.replay_buffer = replay_buffer

    @abstractmethod
    def funcy(self):
        pass
C:\Users\yoyo\Desktop\pytocs>pytocs ./BaseOptimizer.py

Unhandled Exception: System.InvalidOperationException: ./BaseOptimizer.py(2): Expected token type ID, but saw COMMA.
   at Pytocs.Syntax.Parser.Error(String str)
   at Pytocs.Syntax.Parser.Expect(TokenType tokenType)
   at Pytocs.Syntax.Parser.id()
   at Pytocs.Syntax.Parser.fpdef()
   at Pytocs.Syntax.Parser.typedargslist()
   at Pytocs.Syntax.Parser.parameters()
   at Pytocs.Syntax.Parser.funcdef()
   at Pytocs.Syntax.Parser.compound_stmt()
   at Pytocs.Syntax.Parser.stmt()
   at Pytocs.Syntax.Parser.suite()
   at Pytocs.Syntax.Parser.classdef()
   at Pytocs.Syntax.Parser.compound_stmt()
   at Pytocs.Syntax.Parser.stmt()
   at Pytocs.Syntax.Parser.<Parse>d__4.MoveNext()
   at Pytocs.Translate.ModuleTranslator.Translate(IEnumerable`1 statements)
   at Pytocs.Translator.TranslateModuleStatements(IEnumerable`1 stm, TypeReferenceTranslator types, TextWriter output)
   at Pytocs.Translator.Translate(String filename, TextReader input, TextWriter output)
   at Pytocs.Translator.TranslateFile(String inputFileName, String outputFileName)
   at Pytocs.Program.Main(String[] args)

Python integers division should give a C# result of float/double type

Currently, the code is just forwarded ‘as is’ during conversion and gives a C# result of type integer. The problem appy to Python (3.x and more).

Example:

Py: b=3; r= 1/b # r = 0.3333333333333
C#: int b=3; var r= 1/b; // r = 0 !!!
C# (expected example): int b=3; var r= 1/(float)(b); // r = 0.3333333333333

It doesn't wanna run.

When I try to run the command, it gives me this error (Sorry it's danish):

Ikke-afviklet undtagelse: System.InvalidOperationException: -(1): Expected token type NEWLINE but saw ID.
   ved Pytocs.Core.Syntax.Parser.Error(String str, Object[] args)
   ved Pytocs.Core.Syntax.Parser.Expect(TokenType tokenType)
   ved Pytocs.Core.Syntax.Parser.simple_stmt()
   ved Pytocs.Core.Syntax.Parser.stmt()
   ved Pytocs.Core.Syntax.Parser.<Parse>d__4.MoveNext()
   ved Pytocs.Core.Translate.ModuleTranslator.Translate(IEnumerable`1 statements)
   ved Pytocs.Core.Translator.TranslateModuleStatements(IEnumerable`1 stm, TypeReferenceTranslator types, TextWriter output)
   ved Pytocs.Core.Translator.Translate(String filename, TextReader input, TextWriter output)
   ved Pytocs.Cli.Program.Main(String[] args)

What should I do?

Thanks

Exception/Errors without parentheses

This is a valid a python code:

raise NotImplementedError

which translates to:

throw NotImplementedError;

And should be translated to:

throw NotImplementedError();

A Warm Thank You

I had no other way to contact you.

Thank you for coming up with such a project.

The Python Syntax and Semantics are too powerful to remain to just a handful of interpreted implementations.

If we all work hard on Python Transpilers, we will one day live in a world where things will be much simplified concerning this regard. Keep up the amazing work !

Unpacking **kwargs onto a new dictionary

The following code fails due to the **kwargs

def funcy(*args, **kwargs):
  dictionary = {'a': 'str', **kwargs}	
  dictionary_inside_tuple = (1,{'a': 'str', **kwargs})
  return dictionary

print(funcy(key='value'))

output:
{'a': 'str', 'key': 'value'}

Exception:

Unhandled Exception: System.InvalidOperationException: C:\Users\Eli-PC\Desktop\pytocs\this\common\vec_env\subproc_vec_env.py(2): Expected token type RBRACE but saw OP_STARSTAR.
   at Pytocs.Core.Syntax.Parser.Error(String str, Object[] args)
   at Pytocs.Core.Syntax.Parser.Expect(TokenType tokenType)
   at Pytocs.Core.Syntax.Parser.atom()
   at Pytocs.Core.Syntax.Parser.atom_expr()
   at Pytocs.Core.Syntax.Parser.power()
   at Pytocs.Core.Syntax.Parser.factor()
   at Pytocs.Core.Syntax.Parser.term()
   at Pytocs.Core.Syntax.Parser.arith_expr()
   at Pytocs.Core.Syntax.Parser.shift_expr()
   at Pytocs.Core.Syntax.Parser.and_expr()
   at Pytocs.Core.Syntax.Parser.xor_expr()
   at Pytocs.Core.Syntax.Parser.expr()
   at Pytocs.Core.Syntax.Parser.comparison()
   at Pytocs.Core.Syntax.Parser.not_test()
   at Pytocs.Core.Syntax.Parser.and_test()
   at Pytocs.Core.Syntax.Parser.or_test()
   at Pytocs.Core.Syntax.Parser.test()
   at Pytocs.Core.Syntax.Parser.testlist_star_expr()
   at Pytocs.Core.Syntax.Parser.expr_stmt()
   at Pytocs.Core.Syntax.Parser.small_stmt()
   at Pytocs.Core.Syntax.Parser.simple_stmt()
   at Pytocs.Core.Syntax.Parser.stmt()
   at Pytocs.Core.Syntax.Parser.suite()
   at Pytocs.Core.Syntax.Parser.funcdef()
   at Pytocs.Core.Syntax.Parser.compound_stmt()
   at Pytocs.Core.Syntax.Parser.stmt()
   at Pytocs.Core.Syntax.Parser.<Parse>d__4.MoveNext()
   at Pytocs.Core.Translate.ModuleTranslator.Translate(IEnumerable`1 statements)
   at Pytocs.Core.Translator.TranslateModuleStatements(IEnumerable`1 stm, TypeReferenceTranslator types, TextWriter output)
   at Pytocs.Core.Translator.TranslateFile(String inputFileName, String outputFileName)
   at Pytocs.Cli.Program.Main(String[] args)

Functions that return no value should be translated as "void"

The following Python function definition:

def greet_user(username):
    print("hello " + username)

should be translated to

public static void greet_user(string username) {
    print("hello" + username);
}

but currently we're generating object as the return type.

Roadmap Question

Hi
First, let me say this project is really well coded and works great!
Still, in the converted project are more than 10'000 errors (according to Visual Studio). One big chunk would be the announced type detection. For me, this seems to be a non-trivial thing to do. Do you have an idea when you will implement it? Is there a beta version or do you have an idea how to implement it? How could we support you?
I don't want to pressure you, just asking.

HI

how can i use this ?please explain me clearly

EXPECTED Token type NEWLINE, but saw ID

Hi. Thank you for your lib
But i can't use it. I mean, i run my cmd.exe and go to build folder
And use :
Pytocs.exe -> foo.py (then i have something like this output)
`
public static class module_name {

static module_name() {
    foo.py;
}

}
`
if i use in cmd Pytocs.exe -> pytocs foo.py i have this error :
System.InvalidOperationException: -(1): Expected token type NEWLINE, but saw ID.

My PY File :

def meshgrid2(*arrs):
    arrs = tuple(reversed(arrs))  #edit
    lens = map(len, arrs)
    dim = len(arrs)

    sz = 1
    for s in lens:
        sz*=s

    ans = []    
    for i, arr in enumerate(arrs):
        slc = [1]*dim
        slc[i] = lens[i]
        arr2 = asarray(arr).reshape(slc)
        for j, sz in enumerate(lens):
            if j!=i:
                arr2 = arr2.repeat(sz, axis=j) 
        ans.append(arr2)

    return tuple(ans)

Sorry for bad eng and thank you for attention

code that uses the struct module for reading bytes in file headers is not converted

It seems like python code that uses the struct module is not converted to compileable standalone C#. (it would probably get syntax errors).

Code like this for example:

    offset = 0
    # version = struct.unpack_from(b'<26s26x', file_data, offset)[0]
    offset += 52
    entry_count = struct.unpack_from(b'<I4x', file_data, offset)[0]
    print(entry_count)
    offset += 12
    # file_timer = struct.unpack_from(b'<I', file_data, offset)[0]
    offset += 4
    xml_size_file = struct.unpack_from(b'<I', file_data, offset)[0]
    print(xml_size_file)
    offset += 4
    theunpack_offset = offset + xml_size_file

Is not converted properly, it still looks almost exactly alike in the output C# code.

Also, if I try to manually convert it to look like this:

        private enum KOM_DATA {
            KOM_HEADER_SIZE = 27,
            KOM_ENTRY_COUNT_SIZE = 8,
            KOM_FILE_TIMER_SIZE = 4,
            KOM_XML_SIZE_FILE_SIZE = 4
        };

            System.IO.FileStream reader = new System.IO.FileStream(System.Windows.Forms.Application.StartupPath + "\\koms\\" + komfile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] headerbuffer = new byte[System.Convert.ToInt32(KOM_DATA.KOM_HEADER_SIZE)];
            byte[] entry_count_buffer = new byte[System.Convert.ToInt32(KOM_DATA.KOM_ENTRY_COUNT_SIZE)];
            byte[] file_timer_buffer = new byte[System.Convert.ToInt32(KOM_DATA.KOM_FILE_TIMER_SIZE)];
            byte[] xml_size_file_buffer = new byte[System.Convert.ToInt32(KOM_DATA.KOM_XML_SIZE_FILE_SIZE)];
            int offset = 0;
            reader.Read(headerbuffer, offset, System.Convert.ToInt32(KOM_DATA.KOM_HEADER_SIZE));
            string headerstring = System.Text.Encoding.UTF8.GetString(headerbuffer);
            offset += 52;
            reader.Read(entry_count_buffer, offset, System.Convert.ToInt32(KOM_DATA.KOM_ENTRY_COUNT_SIZE));
            offset += 12;
            reader.Read(file_timer_buffer, offset, System.Convert.ToInt32(KOM_DATA.KOM_FILE_TIMER_SIZE));
            offset += 4;
            reader.Read(xml_size_file_buffer, offset, System.Convert.ToInt32(KOM_DATA.KOM_XML_SIZE_FILE_SIZE));
            MessageManager.ShowInfo(System.Convert.ToInt32(entry_count_buffer).ToString(), "Debug!");
            MessageManager.ShowInfo(System.Convert.ToInt32(file_timer_buffer).ToString(), "Debug!");
            MessageManager.ShowInfo(System.Convert.ToInt32(xml_size_file_buffer).ToString(), "Debug!");

The program would crash at the second read into the file to get the data it needs to extract.

Pytocs should convert range to Enumerable.Range

The following code:

def main():
 x = range(6)
 for n in x:
  print(n)

Will be translated to:

public static class Program {    
    public static object main() {
        var x = range(6);
        foreach (var n in x) {
            Console.WriteLine(n);
        }
    }
}

Expected result is:

using System.Linq;
public static class Program {    
    public static object main() {
        var x = Enumerable.Range(0,6);
        foreach (var n in x) {
            Console.WriteLine(n);
        }
    }
}

Also should convert range(a, b); to Enumerable.Range(a,b-a)

Can I use this on my python code that I currently have to embed python on?

I would love to convert this code to C# and drop the python dependency required to run this file in my python embedded interpreters, the main file is located here:

https://github.com/Elskom/Els_kom_new/blob/master/Tools/komformat.py

This would allow me to reduce build time by not:

  1. Cloning cpython branch 3.6
  2. Building branch 3.6
  3. Doing frequent git pull on branch 3.6 requiring an rebuild of python before building my code.

All of this would greatly reduce not only the compile time I get locally but also in AppVeyor CI.

I am also even debating an plugin system where people can even plug into this and detatch all of the things related to packing and unpacking these from the core, and load them and only invoke them when the file is detected that said plugin works for said file. This would even make maintenence time even more easier.

Also does this support python 3.x?

1>------ Build started: Project: pytocs, Configuration: Release Any CPU ------
1>E:\Users\Elsword\Desktop\pytocs\src\Translate\StatementTranslator.Tests.cs(1308,7,1308,13): error CS1024: Preprocessor directive expected
1>E:\Users\Elsword\Desktop\pytocs\src\Translate\StatementTranslator.Tests.cs(1332,7,1332,13): error CS1024: Preprocessor directive expected
1>E:\Users\Elsword\Desktop\pytocs\src\Translate\StatementTranslator.Tests.cs(1335,7,1335,14): error CS1024: Preprocessor directive expected
1>E:\Users\Elsword\Desktop\pytocs\src\Translate\StatementTranslator.Tests.cs(1366,3,1366,7): error CS1024: Preprocessor directive expected
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Simple easy helpful change

At lexer.py, line 225, please output filename, otherwise the user does not know which file is causing the error.
Suggestion:
throw new FormatException(string.Format("Indentation of {0} line {1} is incorrect .", filename, LineNumber));

C# fields are generated incorrectly for derived subclasses

Given the following Python code:

class BaseClass:
    def frobit(self, input):
        this.input = input

class DerivedClass(BaseClass):
    def fooit(self):
        this.input.foo()

we expect pytocs to deduce that BaseClass has a field input and DerivedClass inherits it. Instead, pytocs generates the following incorrect code for DerivedClass (simplified for clarity):

class DerivedClass : BaseClass {
    public object input;    // <-- should have inherited this field from BaseClass
    public virtual object fooit() {
         this.input.foo();
    }
}

How to best troubleshoot or fix NotImplementedExceptions()

I'm trying to run this on a python project and am getting NotImplementedExceptions on some files when I use -r for a few of the subfolders. If I process the files by naming each as an argument instead of using -r, it processes without error.

The stack trace that I get most often is

System.NotImplementedException: The method or operation is not implemented.
   at Pytocs.Core.TypeInference.TypeTransformer.VisitAsync(AsyncStatement a)
   at Pytocs.Core.Syntax.AsyncStatement.Accept[T](IStatementVisitor`1 v)
   at Pytocs.Core.TypeInference.TypeTransformer.VisitSuite(SuiteStatement b)
   at Pytocs.Core.Syntax.SuiteStatement.Accept[T](IStatementVisitor`1 v)
   at Pytocs.Core.TypeInference.TypeTransformer.VisitClass(ClassDef c)
   at Pytocs.Core.Syntax.ClassDef.Accept[T](IStatementVisitor`1 v)
   at Pytocs.Core.TypeInference.TypeTransformer.VisitSuite(SuiteStatement b)
   at Pytocs.Core.Syntax.SuiteStatement.Accept[T](IStatementVisitor`1 v)
   at Pytocs.Core.TypeInference.TypeTransformer.VisitModule(Module m)
   at Pytocs.Core.TypeInference.AnalyzerImpl.LoadModule(Module ast)
   at Pytocs.Core.TypeInference.AnalyzerImpl.LoadFile(String path)
   at Pytocs.Core.TypeInference.AnalyzerImpl.LoadFileRecursive(String fullname)
   at Pytocs.Core.TypeInference.AnalyzerImpl.LoadFileRecursive(String fullname)
   at Pytocs.Core.TypeInference.AnalyzerImpl.Analyze(String path)
   at Pytocs.Cli.Program.Main(String[] args)

When debugging, its complaining about a method like the first async one (check_for_next_number_button) on line 26 in this example file

import logging
import string
from typing import Iterator
import attr
from this_project import BaseClass
from this_project.utils import MyContext

logger = logging.getLogger(__name__)

@attr.s(auto_attribs=True)
class SomeClass(BaseClass):
    remaining_numbers: Iterator[str] = attr.ib(init=False)
    current_number: str = attr.ib(init=False)

    def __attrs_post_init__(self):
        self.remaining_numbers = iter(string.ascii_uppercase)
        self.current_number = next(self.remaining_numbers)

    @property
    def next_number_xpath(self) -> str:
        xpath = "//a[./text()='{0}']".format(self.current_number)
        logger.debug("Generated XPath {0} in {1}"
                     .format(xpath, type(self).__name__))
        return xpath

    async def check_for_next_number_button(self,
                                         my_context: MyContext) -> bool:
        """ Some comment
        spanning multiple lines """
        return self.current_number != 'Z'

    async def get_next_result_number(self, my_context: MyContext):
        self.current_number = next(self.remaining_numbers)
        await super(SomeClass, self).get_next_result_number(
            my_context=my_context)

If I run it for the root of the project, I get similar errors but on Assign or Expr (i forget which). I tried copy/pasting the VisitAsync implementation from StatementTranslator to TypeTranslator but that just led me to another error so I figured I should just stop and ask a few questions.

What does the TypeAnalyzer used by the -r switch intend to do?

Is addressing the problems I'm seeing going to work by just wiring up the methods to accept (like the copy pasted VisitAsync)?

pytocs pythonfilename.py

pytocs GrayScale.py

Unhandled Exception: System.InvalidOperationException: -(1): Expected token type NEWLINE, but saw ID.
at Pytocs.Syntax.Parser.Error(String str) in D:\pytocs-master\src\Syntax\Parser.cs:line 370
at Pytocs.Syntax.Parser.Expect(TokenType tokenType) in D:\pytocs-master\src\Syntax\Parser.cs:line 461
at Pytocs.Syntax.Parser.simple_stmt() in D:\pytocs-master\src\Syntax\Parser.cs:line 826
at Pytocs.Syntax.Parser.stmt() in D:\pytocs-master\src\Syntax\Parser.cs:line 790
at Pytocs.Syntax.Parser.d__4.MoveNext() in D:\pytocs-master\src\Syntax\Parser.cs:line 337
at Pytocs.Translate.ModuleTranslator.Translate(IEnumerable1 statements) in D:\pytocs-master\src\Translate\ModuleTranslator.cs:line 42 at Pytocs.Translator.TranslateModuleStatements(IEnumerable1 stm, State moduleScope, TextWriter output) in D:\pytocs-master\src\Translator.cs:line 87
at Pytocs.Translator.Translate(String filename, TextReader input, TextWriter output) in D:\pytocs-master\src\Translator.cs:line 56
at Pytocs.Program.Main(String[] args) in D:\pytocs-master\src\Program.cs:line 37

Decomposing tuples shouldn't be necessary with modern C#

Pytocs seems to be targeting versions of C# where tuple decomposition wasn't part of the language. The following code:

(a, b, c) = read_tuple()

will be translated into:

_tup_1 = read_tuple();
var a = _tup_1.Item1;
var b = _tup_1.Item2;
var c = _tup_1.Item3

when it could be translated to:

var (a, b, c) = read_tuple();

Token Real() Convert.ToDouble problem in other Cultures

Hi!

I found an error about the Lexer.cs.
I try to convert a py source, and my country settings are Hungarian, and the separator here is a comma, not point.

Please change this:
private Token Real() { return Token(TokenType.REAL, Convert.ToDouble(sb.ToString()), State.Base) }

To

private Token Real() { return Token(TokenType.REAL, Convert.ToDouble(sb.ToString(), CultureInfo.InvariantCulture), State.Base) }

Thanks.

Join SciSharp STACK

Hi CSharp Enthusiasts,

I think you would be interested in .NET ecosystem in AI.
Check the SciSharp STACK. There are several projects needs to convert Python code to CSharp.
It would be great if pytocs could be a member project of SciSharp STACK.

Importing & Converting Python Libraries

This has been done by 2 major transpilers before and it would be tremendously useful.

Pytocs would look what libraries are imported and visit their source and if they are not tied to any OS functionality, they would be converted and imported in C sharp.

What is your view ?

Pytocs should parse docstrings looking for type annotations

Many Python projects use comments in doc strings as type annotations, e.g.

"""
:param str sender
:param str recipient
:param int copies
:rtype int
"""
def send_copies_to(sender, recipient, copies():
# more code here

which would translate to:

public static int send_copies_to(string senders, send recipient, int copies) {
// More code here

ASK

Hello i wanna ask, how to run in visual studio ?

Numeric literals are always converted to decimal and lose visual separators

The Python statement

a = 0xFFEF

is converted to

a =65519;

Users will likely prefer that to be

a = 0xFFEF;

Similarly, the visual separator characters '_' are lost, so the clarity of

one_billion = 1_000_000_000

is lost:

one_billion = 1000000000;

C# now has separator characters too -- in fact the same symbol _ is used -- so pytocs should respect that as well.

The lexer needs to be modified so that, it still recognizes the literals as "literal number", "literal floating point number" but doesn't perform conversion to a number the way it does today.

Pytocs should recognize and respect Python type annotations

Today, Pytocs is confused by Python type annotations like the following:

def greeting(name: str) -> str:
     return 'Hello ' + str

Pytocs should be able to parse such type annotations and then, during type inference, should use the type annotations directly in the generated code, yielding:

public static string greeting(string name) {
     return "Hello " + str;
}

Comments are lost or misplaced

As the current README.md shows, the Python comments are not placed in their correct locations. The sequence

if foo:
   bar()
# We just called bar
baz()

turns into

if (foo) {
    bar();
    // We just called bar
}
baz();

instead of the expected

if (foo) {
    bar();
}
// We just called bar
baz();

Hmmm... your example on the README.md page does not compile

Is the example on your README.md web page meant to compile with a Microsoft compiler? I put your example in Visual Studio 2017 and it will not compile. For example:

    // list comprehension, generating linQ output.
    public static object apply_map(object mapfn, object filterfn) {
        return (from n in lst
            where filterfn
            select mapfn(n)).ToList();
    }

"lst" is not defined. There are numerous other errors. Am I missing something?

Charles

Python global statement not supported

Any global statement on a global variable. encountered in a python function is not taked into account and any further assignment of this global variable from a function lead to new local scope variable created using C# 'var' type.

It would be important to have Python global statement supported in order to allow write access to a global symbols from a python function.

Shift+Enter crashes pytocs

Hitting Shift+Enter in pytocs crashes it with this error:

Unhandled Exception: System.InvalidOperationException: -(2): Expected token type ID, but saw NEWLINE.
  at Pytocs.Syntax.Parser.Error(String str) in C:\projects\pytocs\src\Syntax\Parser.cs:line 375
  at Pytocs.Syntax.Parser.Expect(TokenType tokenType) in C:\projects\pytocs\src\Syntax\Parser.cs:line 466
  at Pytocs.Syntax.Parser.funcdef() in C:\projects\pytocs\src\Syntax\Parser.cs:line 516
  at Pytocs.Syntax.Parser.compound_stmt() in C:\projects\pytocs\src\Syntax\Parser.cs:line 1333
  at Pytocs.Syntax.Parser.stmt() in C:\projects\pytocs\src\Syntax\Parser.cs:line 796
  at Pytocs.Syntax.Parser.<Parse>d__4.MoveNext() in C:\projects\pytocs\src\Syntax\Parser.cs:line 342
  at Pytocs.Translate.ModuleTranslator.Translate(IEnumerable`1 statements) in C:\projects\pytocs\src\Translate\ModuleTranslator.cs:line 41
  at Pytocs.Translator.TranslateModuleStatements(IEnumerable`1 stm, TypeReferenceTranslator types, TextWriter output) in C:\projects\pytocs\src\Translator.cs:line 99
  at Pytocs.Translator.Translate(String filename, TextReader input, TextWriter output) in C:\projects\pytocs\src\Translator.cs:line 58
  at Pytocs.Program.Main(String[] args) in C:\projects\pytocs\src\Program.cs:line 39

The program then stops responding and gets forcefully shutdown by windows.

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.