public override StatementEmitInfo GetStatementEmitInfo(PyEmitStyle style)
 {
     if (!false)
     {
         return(StatementEmitInfo.NormalSingleStatement);
     }
 }
        // Public Methods 

        public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style)
        {
            style = PyEmitStyle.xClone(style);
            if (!style.AsIncrementor)
            {
                switch (Expression)
                {
                case PyEmptyExpression _:
                    return;

                case PyMethodCallExpression methodCallExpression:
                    break;
                }
            }

            var code = Expression.GetPyCode(style);

            if (style.AsIncrementor)
            {
                writer.Write(code);
            }
            else
            {
                writer.WriteLn(code);
            }
        }
        public override string GetPyCode(PyEmitStyle style)
        {
            var join      = style == null || style.Compression == EmitStyleCompression.Beauty ? ", " : ",";
            var xstyle    = PyEmitStyle.xClone(style);
            var arguments = string.Join(join, Arguments.Select(i => i.GetPyCode(xstyle)));

            if (IsConstructorCall)
            {
                var a = string.Format("new {0}({1})", _className.NameForEmit(style), arguments);
                return(a);
            }

            var name = _name;

            if (!_className.IsEmpty)
            {
                name = _className.NameForEmit(style) + "::" + name;
            }
            else if (TargetObject != null)
            {
                var to = TargetObject;
                if (TargetObject is PyMethodCallExpression &&
                    (TargetObject as PyMethodCallExpression).IsConstructorCall)
                {
                    to = new PyParenthesizedExpression(to);
                }
                name = to.GetPyCode(style) + "." + name;
            }

            // Arguments
            var skipBrackets = CanSkipBrackets();
            var code         = string.Format(skipBrackets ? "{0} {1}" : "{0}({1})", name, arguments);

            return(code);
        }
Exemple #4
0
        // Public Methods 

        public void Emit(PySourceCodeEmiter emiter, PyEmitStyle style, string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException(nameof(filename));
            }

            var writer = new PySourceCodeWriter();
            var styleCurrentNamespace = style.CurrentNamespace;

            try
            {
                Emit(emiter, writer, style);

                {
                    var fi = new FileInfo(filename);
                    fi.Directory?.Create();
                    var codeStr = writer.GetCode();
                    var binary  = Encoding.UTF8.GetBytes(codeStr);
                    File.WriteAllBytes(fi.FullName, binary);
                }
            }
            finally
            {
                style.CurrentNamespace = styleCurrentNamespace;
            }
        }
Exemple #5
0
        // Private Methods 

        private static void EmitWithNamespace(PyNamespace ns, PySourceCodeEmiter emiter,
                                              PySourceCodeWriter writer,
                                              PyEmitStyle style, IEnumerable <IEmitable> classesInNamespace)
        {
            if (classesInNamespace == null)
            {
                return;
            }
            var inNamespace = classesInNamespace as IEmitable[] ?? classesInNamespace.ToArray();

            if (!inNamespace.Any())
            {
                return;
            }
            style.CurrentNamespace = ns;
            try
            {
                foreach (var cl in inNamespace)
                {
                    cl.Emit(emiter, writer, style);
                }
            }
            finally
            {
                style.CurrentNamespace = null;
            }
        }
Exemple #6
0
 public override string GetPyCode(PyEmitStyle style)
 {
     if (string.IsNullOrEmpty(UseAlias))
     {
         return(ModuleName.Name);
     }
     return(UseAlias);
 }
Exemple #7
0
        // Public Methods 

        public string GetPyCode(PyEmitStyle s)
        {
            s = s ?? new PyEmitStyle();
            var eq = s.Compression == EmitStyleCompression.Beauty ? " = " : "=";
            var d  = DefaultValue != null ? eq + DefaultValue.GetPyCode(s) : "";

            return(string.Format("{0}{1}", _name, d));
        }
 public override string GetPyCode(PyEmitStyle style)
 {
     if (style == null || style.Compression == EmitStyleCompression.Beauty)
     {
         return(string.Format("{0} {1} {2}", Left.GetPyCode(style), Operator, Right.GetPyCode(style)));
     }
     return(string.Format("{0}{1}{2}", Left.GetPyCode(style), Operator, Right.GetPyCode(style)));
 }
Exemple #9
0
        // Protected Methods 

        protected void EmitHeaderStatement(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style, string header, IPyStatement statement)
        {
            style = style ?? new PyEmitStyle();
            var iStyle = PyEmitStyle.xClone(style, ShowBracketsEnum.IfManyItems);

            if (style.UseBracketsEvenIfNotNecessary)
            {
                iStyle.Brackets = ShowBracketsEnum.Always;
            }

            var statementToEmit = PyCodeBlock.Reduce(statement);
            var emptyStatement  = !PyCodeBlock.HasAny(statementToEmit);


            if (emptyStatement)
            {
                header += "{}";
            }
            if (style.Compression == EmitStyleCompression.NearCrypto)
            {
                writer.Write(header);
            }
            else
            {
                writer.WriteLn(header);
            }
            if (emptyStatement)
            {
                return;
            }


            var myBracket = style.UseBracketsEvenIfNotNecessary;

            if (!myBracket)
            {
                var gf = statementToEmit.GetStatementEmitInfo(iStyle);
                if (gf != StatementEmitInfo.NormalSingleStatement)
                {
                    myBracket = true;
                }
            }
            writer.IncIndent();
            if (myBracket)
            {
                iStyle.Brackets = ShowBracketsEnum.Never;
                writer.OpenLn("{");
            }


            statementToEmit.Emit(emiter, writer, iStyle);
            if (myBracket)
            {
                writer.CloseLn("}");
            }

            writer.DecIndent();
        }
        // Public Methods 

        public override string GetPyCode(PyEmitStyle style)
        {
            var o = Increment ? "++" : "--";

            return(string.Format("{0}{1}{2}",
                                 Pre ? o : "",
                                 Operand.GetPyCode(style),
                                 Pre ? "" : o));
        }
Exemple #11
0
        public override string GetPyCode(PyEmitStyle style)
        {
            var form = style == null || style.Compression == EmitStyleCompression.Beauty
                ? "{0} ? {1} : {2}"
                : "{0}?{1}:{2}";

            return(string.Format(form, Condition.GetPyCode(style), WhenTrue.GetPyCode(style),
                                 WhenFalse.GetPyCode(style)));
        }
        public override string GetPyCode(PyEmitStyle style)
        {
            if (Initializers == null || Initializers.Length == 0)
            {
                return("array()");
            }
            style = style ?? new PyEmitStyle();
            var przecinek = style.Compression == EmitStyleCompression.Beauty ? ", " : ",";
            var www       = style.Compression == EmitStyleCompression.Beauty ? " => " : "=>";

            var list = new List <string>();

            foreach (var initializeValue in Initializers)
            {
                if (initializeValue is PyAssignExpression)
                {
                    var assignExpression = initializeValue as PyAssignExpression;
                    if (!string.IsNullOrEmpty(assignExpression.OptionalOperator))
                    {
                        throw new NotSupportedException();
                    }

                    if (assignExpression.Left is PyArrayAccessExpression)
                    {
                        var left = assignExpression.Left as PyArrayAccessExpression;
                        if (left.PyArray is PyThisExpression)
                        {
                            var o = left.Index + www + assignExpression.Right;
                            list.Add(o);
                        }
                        else
                        {
                            throw new NotSupportedException();
                        }
                    }
                    else if (assignExpression.Left is PyInstanceFieldAccessExpression)
                    {
                        var l1 = assignExpression.Left as PyInstanceFieldAccessExpression;
                        var fn = new PyConstValue(l1.FieldName);
                        var o  = fn.GetPyCode(style) + www + assignExpression.Right;
                        list.Add(o);
                    }
                    else
                    {
                        var o = assignExpression.Left.GetPyCode(style) + www + assignExpression.Right;
                        list.Add(o);
                    }
                }
                else
                {
                    list.Add(initializeValue.GetPyCode(style));
                }
            }

            return("[" + string.Join(przecinek, list) + "]");
        }
Exemple #13
0
        public string GetPyCode(PyEmitStyle style)
        {
            var tmp = Value?.GetPyCode(style);

            if (string.IsNullOrEmpty(Name))
            {
                return(tmp);
            }
            return($"{tmp} as {Name}");
        }
Exemple #14
0
        public override string GetPyCode(PyEmitStyle style)
        {
            if (Initializers.Count == 0)
            {
                return("dict()");
            }
            var initializers = Initializers.Select(a => a.Key.GetPyCode(style) + ":" + a.Value.GetPyCode(style));
            var code         = string.Join(", ", initializers);

            return("{" + code + "}");
        }
Exemple #15
0
        private static string Collect(PySourceCodeEmiter emiter, PyEmitStyle style, IPyValue[] collection)
        {
            var list   = new List <string>();
            var xStyle = PyEmitStyle.xClone(style);

            xStyle.AsIncrementor = true;
            foreach (var item in collection)
            {
                list.Add(item.GetPyCode(xStyle));
            }
            return(string.Join(", ", list));
        }
Exemple #16
0
        public override string GetPyCode(PyEmitStyle style)
        {
            var b = style != null && style.Compression != EmitStyleCompression.Beauty;

            //var a = PyValues.ToPyCodeValue(Value, b);
            switch (Value)
            {
            case null: return("None");

            case int _:
            case long _:
            case short _:
            case sbyte _:
                var longValue = Convert.ToInt64(Value);
                return(longValue.ToString(CultureInfo.InvariantCulture));

            case uint _:
            case ulong _:
            case ushort _:
            case byte _:
                var ulongValue = Convert.ToUInt64(Value);
                return(ulongValue.ToString(CultureInfo.InvariantCulture));

            case string stringValue:
                return(EscapeSingleQuote(stringValue));

            case bool boolValue:
                return(boolValue ? "True" : "False");

            case decimal decimalValue:
                return(FixDecimal(decimalValue.ToString(CultureInfo.InvariantCulture)));

            case float floatValue:
                return(FixDecimal(floatValue.ToString(CultureInfo.InvariantCulture)));

            case double doubleValue:
                return(FixDecimal(doubleValue.ToString(CultureInfo.InvariantCulture)));

            default:
            {
                var t = Value.GetType();
                if (t.IsEnum)
                {
                    return(EscapeSingleQuote(Value.ToString()));
                }
                throw new NotImplementedException(Value.GetType().ToString());
            }
            }
        }
        // Public Methods 

        public void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style)
        {
            foreach (var i in NestedClasses)
            {
                i.Emit(emiter, writer, style);
            }
            var saveStyleCurrentClass     = style.CurrentClass;
            var saveStyleCurrentNamespace = style.CurrentNamespace;

            try
            {
                if (IsEmpty)
                {
                    return;
                }
                if (style.CurrentNamespace == null)
                {
                    style.CurrentNamespace = PyNamespace.Root;
                }
                if (style.CurrentNamespace != Name.Namespace)
                {
                    throw new Exception("Unable to emit class into different namespace");
                }
                var e = "";
                if (!_baseTypeName.IsEmpty)
                {
                    e = " extends " + _baseTypeName.NameForEmit(style);
                }
                writer.OpenLnF("class {0}{1}:", Name.ShortName, e);
                style.CurrentClass = Name; // do not move this before "class XXX" is emited
                for (var orderGroup = 0; orderGroup < 3; orderGroup++)
                {
                    foreach (var field in Fields.Where(_ => FieldOrderGroup(_) == orderGroup))
                    {
                        field.Emit(emiter, writer, style);
                    }
                }
                foreach (var me in Methods)
                {
                    me.Emit(emiter, writer, style);
                }
                writer.CloseLn("");
            }
            finally
            {
                style.CurrentClass     = saveStyleCurrentClass;
                style.CurrentNamespace = saveStyleCurrentNamespace;
            }
        }
Exemple #18
0
        public override string GetPyCode(PyEmitStyle style)
        {
            if (TranslationInfo == null)
            {
                throw new ArgumentNullException("translationInfo");
            }
            if (TranslationInfo.IsStatic)
            {
                throw new NotSupportedException();
            }
            // jeśli nic nie podano to zakładam odczyt własności
            var a = MakeGetValueExpression();

            return(a.GetPyCode(style));
        }
Exemple #19
0
        // Private Methods 

        private static string Collect(PySourceCodeEmiter emiter, PyEmitStyle style, IPyStatement[] collection)
        {
            var list   = new List <string>();
            var xStyle = PyEmitStyle.xClone(style);

            xStyle.AsIncrementor = true;
            foreach (var item in collection)
            {
                var writer = new PySourceCodeWriter();
                writer.Clear();
                item.Emit(emiter, writer, xStyle);
                list.Add(writer.GetCode().Trim());
            }

            return(string.Join(", ", list));
        }
Exemple #20
0
        private void TranslateAndCreatePyFiles(TranslationInfo translationInfo, string outDir)
        {
            if (_verboseToConsole)
            {
                Console.WriteLine("Translate C# -> Py");
            }

            translationInfo.CurrentAssembly = CompiledAssembly;
            var assemblyTi = translationInfo.GetOrMakeTranslationInfo(CompiledAssembly);
            var ecBaseDir  = Path.Combine(outDir, assemblyTi.RootPath.Replace("/", "\\"));

            Console.WriteLine("Output root {0}", ecBaseDir);

            if (!string.IsNullOrEmpty(assemblyTi.PyPackageSourceUri))
            {
                DownloadAndUnzip(assemblyTi.PyPackageSourceUri, ecBaseDir, assemblyTi.PyPackagePathStrip);
                return; //??? czy return?
            }

            var translationState = new TranslationState(translationInfo);
            var translator       = new Translator.Translator(translationState);

            translator.Translate(Sandbox);

            var libName = assemblyTi.LibraryName;

            if (_verboseToConsole)
            {
                Console.WriteLine("Create Py output files");
            }
            {
                // Tworzenie plików Py
                var emitStyle = new PyEmitStyle();

                translationInfo.CurrentAssembly = CompiledAssembly; // dla pewności
                foreach (var module in translator.Modules /*.Where(i => i.Name.Library == libName && !i.IsEmpty) */)
                {
                    var fileName = module.ModuleName.MakeEmitPath(ecBaseDir, 1);
                    foreach (var modProcessor in translationInfo.ModuleProcessors)
                    {
                        modProcessor.BeforeEmit(module, translationInfo);
                    }
                    var emiter = new PySourceCodeEmiter();
                    module.Emit(emiter, emitStyle, fileName);
                }
            }
        }
Exemple #21
0
        public virtual void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter code, PyEmitStyle style)
        {
            // public function addFunction($function, $namespace = '')
            var argumentsCode = Arguments.Select(u => u.GetPyCode(style)).ToList();
            var mk            = GetPyMethodKind();

            switch (mk)
            {
            case PyMethodKind.ClassStatic:
                code.WriteLn("@staticmethod");
                argumentsCode.Insert(0, GetCurrentClassAlias());
                break;

            case PyMethodKind.OutOfClass:
                break;

            case PyMethodKind.ClassInstance:
                argumentsCode.Insert(0, "self");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var param = Arguments == null ? "" : string.Join(", ", argumentsCode);

            code.OpenLnF("def {0}({1}):", Name, param);
            {
                var g = GetGlobals();
                if (!string.IsNullOrEmpty(g))
                {
                    code.WriteLnF("global {0};", g);
                }
            }
            foreach (var statement in Statements)
            {
                var g = PyEmitStyle.xClone(style);
                g.Brackets      = ShowBracketsEnum.Never;
                g.CurrentMethod = this;
                statement.Emit(emiter, code, g);
            }

            code.CloseLn("");
        }
        public override string GetPyCode(PyEmitStyle style)
        {
            if (Expression == null)
            {
                throw new Exception("Unable to get code from empty expression");
            }
            var ex = PyParenthesizedExpression.Strip(Expression);
            var a  = Expression.GetPyCode(style);

            if (ByRef)
            {
                throw new NotSupportedException("'By ref' argument is not supported");
            }
            if (!string.IsNullOrEmpty(Name))
            {
                a = Name + "=" + a;
            }
            return(a);
        }
Exemple #23
0
        // Public Methods 


        public void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style)
        {
            var c = ConstValue;

            if (IsStatic && c == null)
            {
                c = PyConstValue.DefaultForType(_valueType);
            }
            if (c == null)
            {
                return;
            }
            if (!IsStatic)
            {
                throw new Exception(
                          "Only static fields with initialization are allowed. Move instance field initialization to constructior.");
            }
            ScanForDangerousCode(ConstValue);
            writer.WriteLn(Name + " = " + c.GetPyCode(style));
        }
Exemple #24
0
        public string GetPyCode(PyEmitStyle style)
        {
            /*
             * echo preg_replace_callback('~-([a-z])~', function ($match) {
             * return strtoupper($match[1]);
             * }, 'hello-world');
             * // outputs helloWorld
             */
            var s = PyEmitStyle.xClone(style);

            s.AsIncrementor = true;
            var e   = new PySourceCodeEmiter();
            var wde = new PySourceCodeWriter();

            wde.Clear();
            MethodDefinition.Emit(e, wde, s);
            var code = wde.GetCode().Trim();

            return(code);
        }
Exemple #25
0
        // Public Methods 

        public void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style)
        {
            if (Statements.Count == 0)
            {
                return;
            }
            var bracketStyle = style == null ? ShowBracketsEnum.IfManyItems : style.Brackets;
            var brack        =
                bracketStyle == ShowBracketsEnum.Never
                    ? false
                    : bracketStyle == ShowBracketsEnum.Always
                        ? true
                        : Statements == null || !(Statements.Count == 1);

            brack = false;
            if (Statements != null && Statements.Count == 1 &&
                bracketStyle == ShowBracketsEnum.IfManyItems_OR_IfStatement)
            {
                if (Statements[0] is PyIfStatement)
                {
                    brack = true;
                }
            }

            var iStyle = PyEmitStyle.xClone(style, ShowBracketsEnum.Never);


            if (brack)
            {
                writer.OpenLn("{");
            }
            foreach (var i in Statements)
            {
                i.Emit(emiter, writer, iStyle);
            }
            if (brack)
            {
                writer.CloseLn("}");
            }
        }
Exemple #26
0
 public StatementEmitInfo GetStatementEmitInfo(PyEmitStyle style)
 {
     return(StatementEmitInfo.NormalSingleStatement); // sam troszczę się o swoje nawiasy
 }
Exemple #27
0
        // Public Methods 

        public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style)
        {
            writer.OpenLnF("switch ({0}) {{", Expression.GetPyCode(style));
            foreach (var sec in Sections)
            {
                foreach (var l in sec.Labels)
                {
                    writer.WriteLnF("{0}{1}:",
                                    l.IsDefault ? "" : "case ",
                                    l.IsDefault ? "default" : l.Value.GetPyCode(style));
                }
                writer.IncIndent();
                sec.Statement.Emit(emiter, writer, style);
                writer.DecIndent();
            }

            writer.CloseLn("}");
        }
Exemple #28
0
 public override string GetPyCode(PyEmitStyle style)
 {
     return(_expression);
 }
Exemple #29
0
        // Public Methods 

        public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style)
        {
            //   with tf.name_scope('hidden2') as name:
            writer.WriteLnF("with {0}:", Variable.GetPyCode(style));
            writer.Intent++;
            foreach (var sec in Statements)
            {
                sec.Emit(emiter, writer, style);
            }
            writer.Intent--;
        }
Exemple #30
0
        // Public Methods 

        public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style)
        {
            var pyIncrementrors = Collect(emiter, style, Incrementors);
            var pyInitVariables = Collect(emiter, style, InitVariables);

            style = style ?? new PyEmitStyle();

            var header =
                style.Compression == EmitStyleCompression.Beauty
                    ? "for({0}; {1}; {2})"
                    : "for({0};{1};{2})";

            header = string.Format(header, pyInitVariables, Condition.GetPyCode(style), pyIncrementrors);

            EmitHeaderStatement(emiter, writer, style, header, Statement);
        }