// 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; } }
// 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 Methods public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { style = style ?? new PyEmitStyle(); var header = string.Format("while({0}):", Condition.GetPyCode(style)); EmitHeaderStatement(emiter, writer, style, header, Statement); }
// 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; } }
// 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 void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { if (ReturnValue == null) { writer.WriteLn("return"); } else { writer.WriteLnF("return {0}", ReturnValue.GetPyCode(style)); } }
// 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--; }
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)); }
// Public Methods public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { var s = style?.Compression ?? EmitStyleCompression.Beauty; if (s == EmitStyleCompression.NearCrypto) { writer.Write("continue;"); } else { writer.WriteLn("continue;"); } }
//LangType ItemType, string VarName, IValue Collection, IStatement Statement public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { style = style ?? new PyEmitStyle(); var arrayOperator = style.Compression == EmitStyleCompression.Beauty ? " => " : "=>"; var header = OneVariable ? "for {3} in {0}:" : "foreach({0} as {1}{2}{3}):"; header = string.Format(header, Collection.GetPyCode(style), _keyVarname, arrayOperator, _valueVarname); EmitHeaderStatement(emiter, writer, style, header, Statement); }
protected static CompilationTestInfo ParseCs(string code, bool translate, Info info = null) { var project = CreateOneFileProject(code, info?.Ref); var c = new Cs2PyCompiler { CSharpProject = project }; c.TranslationAssemblies.Add(typeof(AssemblySandbox).Assembly); c.ReferencedAssemblies.Add(typeof(Tensorflow.TensorShape).Assembly); c.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly); c.ReferencedAssemblies.Add(typeof(System.Data.Linq.Binary).Assembly); var filename = Path.GetTempFileName().Replace(".tmp", ".dll"); var er = c.CompileCSharpProject(c.Sandbox, filename); if (!er.Success && er.Diagnostics.Any()) { throw new Exception(er.Diagnostics[0].GetMessage()); } Assert.True(er.Success); var translationInfo = c.ParseCsSource(); if (!translate) { return(new CompilationTestInfo(c, translationInfo, null)); } var translationState = new TranslationState(translationInfo); var translator = new Translator(translationState); translator.Info.CurrentAssembly = c.CompiledAssembly; translator.Translate(c.Sandbox); var compare = info?.Compare; if (compare != null) { compare = compare.Trim(); if (!compare.StartsWith("'''")) { compare = "'''\r\nGenerated with cs2py\r\n'''\r\n" + compare; } var emiter = new PySourceCodeEmiter(); var writer = new PySourceCodeWriter(); translator.Modules[0].Emit(emiter, writer, new PyEmitStyle()); var pyCode = writer.GetCode(); Assert.Equal(compare.Trim(), pyCode.Trim()); } return(new CompilationTestInfo(c, translationInfo, translator)); }
// 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; } }
// 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); }
// 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)); }
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); } } }
// 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("}"); }
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 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)); }
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); }
// 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("}"); } }
public void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { Code.Emit(emiter, writer, style); }
public void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { writer.WriteLn(GetPyCode()); }
// Public Methods public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter code, PyEmitStyle style) { Refactor(); base.Emit(emiter, code, style); }
public void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { var nsManager = new PyModuleNamespaceManager(); style.CurrentNamespace = null; if (!string.IsNullOrEmpty(_topComments)) { writer.WriteLn("'''\r\n" + _topComments.Trim() + "\r\n'''"); } var module = this; { // var noBracketStyle = PyEmitStyle.xClone(style, ShowBracketsEnum.Never); { // top code var collectedTopCodeBlock = new PyCodeBlock(); collectedTopCodeBlock.Statements.AddRange(ConvertRequestedToCode()); collectedTopCodeBlock.Statements.AddRange(ConvertDefinedConstToCode()); if (TopCode != null) { collectedTopCodeBlock.Statements.AddRange(TopCode.Statements); } nsManager.Add(collectedTopCodeBlock.Statements); } foreach (var m in Methods) { m.Emit(emiter, writer, style); } { var classesGbNamespace = module.Classes.GroupBy(u => u.Name.Namespace); foreach (var classesInNamespace in classesGbNamespace.OrderBy(i => !i.Key.IsRoot)) { foreach (var c in classesInNamespace) { nsManager.Add(c); } } } if (BottomCode != null) { nsManager.Add(BottomCode.Statements); } if (nsManager.Container.Any()) { if (nsManager.OnlyOneRootStatement) { foreach (var cl in nsManager.Container[0].Items) { cl.Emit(emiter, writer, style); } } else { foreach (var ns in nsManager.Container) { EmitWithNamespace(ns.Name, emiter, writer, style, ns.Items); } } } } }
// Public Methods public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { var isBeauty = style == null || style.Compression == EmitStyleCompression.Beauty; var ifTrueAny = PyCodeBlock.HasAny(_ifTrue); var ifFalseAny = PyCodeBlock.HasAny(_ifFalse); if (!ifTrueAny && !ifFalseAny) { return; } writer.OpenLnF("if{1}({0}){2}", Condition.GetPyCode(style), isBeauty ? " " : "", ifTrueAny ? "" : "{}"); if (ifTrueAny) { var iStyle = PyEmitStyle.xClone(style, ShowBracketsEnum.IfManyItems_OR_IfStatement); if (style != null && style.UseBracketsEvenIfNotNecessary) { iStyle.Brackets = ShowBracketsEnum.Always; } var bound = PyCodeBlock.Bound(_ifTrue); bound.Emit(emiter, writer, iStyle); } writer.DecIndent(); if (!ifFalseAny) { return; } var oneLine = _ifFalse is PyIfStatement; var oldIndent = writer.Intent; { if (oneLine) { writer.Write("else "); writer.SkipIndent = true; } else { writer.OpenLn("else"); } var myBracket = style != null && style.UseBracketsEvenIfNotNecessary; var iStyle = PyEmitStyle.xClone(style, myBracket ? ShowBracketsEnum.Never : ShowBracketsEnum.IfManyItems_OR_IfStatement); if (!myBracket) { var gf = _ifFalse.GetStatementEmitInfo(iStyle); if (gf != StatementEmitInfo.NormalSingleStatement) { myBracket = true; } } if (myBracket) { iStyle.Brackets = ShowBracketsEnum.Never; writer.OpenLn("{"); } _ifFalse.Emit(emiter, writer, iStyle); if (myBracket) { writer.CloseLn("}"); } } writer.Intent = oldIndent; }
public override void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style) { writer.WriteLn("break;"); }
// Public Methods public abstract void Emit(PySourceCodeEmiter emiter, PySourceCodeWriter writer, PyEmitStyle style);