public void Translate(string filename, TextReader input, TextWriter output) { Debug.Print("Translating module {0} in namespace {1}", moduleName, nmspace); var lex = new Lexer(filename, input); var flt = new CommentFilter(lex); var par = new Parser(filename, flt, true, logger); var stm = par.Parse(); var types = new TypeReferenceTranslator(new Dictionary <Node, DataType>()); TranslateModuleStatements(stm, types, output); }
public void TranslateModuleStatements( IEnumerable <Statement> stm, TypeReferenceTranslator types, TextWriter output) { var unt = new CodeCompileUnit(); var gen = new CodeGenerator(unt, nmspace, Path.GetFileNameWithoutExtension(moduleName)); var xlt = new ModuleTranslator(types, gen); xlt.Translate(stm); var pvd = new CSharpCodeProvider(); pvd.GenerateCodeFromCompileUnit(unt, output, new CodeGeneratorOptions { }); }
public static async Task ConvertFolderAsync(string sourcePath, string targetPath, ILogger logger) { try { var fs = new FileSystem(); var options = new Dictionary <string, object>(); var typeAnalysis = new AnalyzerImpl(fs, logger, options, DateTime.Now); typeAnalysis.Analyze(sourcePath); typeAnalysis.Finish(); var types = new TypeReferenceTranslator(typeAnalysis.BuildTypeDictionary()); var walker = new DirectoryWalker(fs, sourcePath, "*.py"); await walker.EnumerateAsync(state => { foreach (var file in fs.GetFiles(state.DirectoryName, "*.py", SearchOption.TopDirectoryOnly)) { var path = fs.GetFullPath(file); var xlator = new Translator( state.Namespace, fs.GetFileNameWithoutExtension(file), fs, logger); var module = typeAnalysis.GetAstForFile(path); var relativePath = MakeRelative(sourcePath, path); var targetFilePath = Path.ChangeExtension(MakeAbsolute(targetPath, relativePath), ".py.cs"); var targetFileDirectory = Path.GetDirectoryName(targetFilePath); if (!Directory.Exists(targetFileDirectory)) { Directory.CreateDirectory(targetFileDirectory); } xlator.TranslateModuleStatements( module.body.stmts, types, targetFilePath); } }); logger.Inform(Resources.Done); } catch (Exception ex) { logger.Error(Resources.ErrUnexpectedConversionError, ex.Message); logger.Inform(Resources.ConversionWasAborted); } }
public void TranslateModuleStatements( IEnumerable <Statement> stm, TypeReferenceTranslator types, TextWriter output) { try { var unt = new CodeCompileUnit(); var gen = new CodeGenerator(unt, nmspace, Path.GetFileNameWithoutExtension(moduleName)); var xlt = new ModuleTranslator(types, gen); xlt.Translate(stm); var pvd = new CSharpCodeProvider(); pvd.GenerateCodeFromCompileUnit(unt, output, new CodeGeneratorOptions { }); } catch (NodeException nex) { logger.Error($"{nex.Node.Filename}({nex.Node.Start}): {nex.Message}"); } }
string Xlat(string pyExp) { var rdr = new StringReader(pyExp); var lex = new Lexer("foo.py", rdr); var par = new Parser("foo.py", lex); var exp = par.test(); Debug.Print("{0}", exp); var sym = new SymbolGenerator(); var types = new TypeReferenceTranslator(new Dictionary <Node, DataType>()); var xlt = new ExpTranslator(types, new CodeGenerator(new CodeCompileUnit(), "", "test"), sym); var csExp = exp.Accept(xlt); var pvd = new CSharpCodeProvider(); var writer = new StringWriter(); pvd.GenerateCodeFromExpression(csExp, writer, new CodeGeneratorOptions { }); return(writer.ToString()); }
private (string code, bool isDerived, CodeDependencies dependencies) GenerateClassDeclaration(Type type) { var isDerived = false; var deps = CodeDependencies.Empty; var declarationParts = new List <string>(); // Type name with generic type parameters (including constraints). declarationParts.Add(type.GetNameWithGenericTypeParameters(t => { var constraintTranslations = t.GetGenericParameterConstraints() .Except(new[] { typeof(ValueType) }) .Select(TypeReferenceTranslator.Translate); deps = constraintTranslations.Select(x => x.Dependencies).Aggregate(deps, (d, next) => d.Merge(next)); return(!constraintTranslations.Any() ? string.Empty : $" extends {string.Join(" & ", constraintTranslations.Select(x => x.ReferencedTypeName))}"); })); // Extending the base class. if (!Configuration.FlattenBaseTypes && type.BaseType != typeof(object)) { var baseTypeTranslation = TypeReferenceTranslator.Translate(type.BaseType); declarationParts.Add($"extends { baseTypeTranslation.ReferencedTypeName }"); deps = deps.Merge(baseTypeTranslation.Dependencies); isDerived = true; } // Implementing interfaces. var interfaces = type.GetSelfImplementedInterfaces(); if (interfaces.Any()) { var interfaceTranslations = interfaces.Select(TypeReferenceTranslator.Translate); declarationParts.Add($"implements { string.Join(", ", interfaceTranslations.Select(t => t.ReferencedTypeName)) }"); deps = interfaceTranslations.Select(t => t.Dependencies).Aggregate(deps, (d, next) => d.Merge(next)); } return(string.Join(" ", declarationParts), isDerived, deps); }
private string GeneratePropertyDefinitions(Type type, ITemplatingEngine templatingEngine, out CodeDependencies dependencies) { var propertyCodeSnippets = new List <string>(); var deps = CodeDependencies.Empty; foreach (var property in type.GetProperties()) { Logger.WriteInformation($"Translating property {property.Name} on type {type}."); var typeReferenceTranslation = TypeReferenceTranslator.Translate(property.PropertyType); deps = deps.Merge(typeReferenceTranslation.Dependencies); propertyCodeSnippets.Add(templatingEngine.UseTemplate("InterfacePropertyDefinition", new Dictionary <string, string> { { "PropertyName", GetTypeScriptPropertyName(property) }, { "Documentation", GenerateDocumentationComment(property) }, { "PropertyType", typeReferenceTranslation.ReferencedTypeName } })); } dependencies = deps; return(string.Join(Environment.NewLine, propertyCodeSnippets)); }
private string XlatModule(string pyModule) { var rdr = new StringReader(pyModule); var lex = new Syntax.Lexer("foo.py", rdr); var par = new Syntax.Parser("foo.py", lex); var stm = par.Parse();; var unt = new CodeCompileUnit(); var gen = new CodeGenerator(unt, "test", "testModule"); var types = new TypeReferenceTranslator(new Dictionary <Node, DataType>()); var xlt = new ModuleTranslator(types, gen); xlt.Translate(stm); var pvd = new CSharpCodeProvider(); var writer = new StringWriter(); pvd.GenerateCodeFromCompileUnit( unt, writer, new CodeGeneratorOptions { }); return(writer.ToString()); }
static void Main(string[] args) { var fs = new FileSystem(); var logger = new ConsoleLogger(); if (args.Length == 0) { var xlator = new Translator("", "module_name", fs, logger); xlator.Translate("-", Console.In, Console.Out); Console.Out.Flush(); return; } if (args[0].ToLower() == "-r") { var startDir = args.Length == 2 ? args[1] : Directory.GetCurrentDirectory(); var options = new Dictionary <string, object>(); #if !NOT_READY_FOR_TYPES var typeAnalysis = new AnalyzerImpl(fs, logger, options, DateTime.Now); typeAnalysis.Analyze(startDir); typeAnalysis.Finish(); var types = new TypeReferenceTranslator( typeAnalysis.BuildTypeDictionary()); //Console.WriteLine($"== Type dictionary: {types.Count}"); //foreach (var de in types.OrderBy(d => d.Key.ToString())) //{ // Console.WriteLine("{0}: {1} {2}", de.Key, de.Key.Start, de.Value); //} var walker = new DirectoryWalker(fs, startDir, "*.py"); walker.Enumerate(state => { foreach (var file in fs.GetFiles(state.DirectoryName, "*.py", SearchOption.TopDirectoryOnly)) { var path = fs.GetFullPath(file); var xlator = new Translator( state.Namespace, fs.GetFileNameWithoutExtension(file), fs, logger); var module = typeAnalysis.GetAstForFile(path); xlator.TranslateModuleStatements( module.body.stmts, types, Path.ChangeExtension(path, ".py.cs")); } }); #else var walker = new DirectoryWalker(fs, startDir, "*.py"); walker.Enumerate(walker.ProcessDirectoryFiles); #endif } else { foreach (var fileName in args) { var xlator = new Translator( "", fs.GetFileNameWithoutExtension(fileName), fs, new ConsoleLogger()); xlator.TranslateFile(fileName, fileName + ".cs"); } } }