public void Translate(AssemblySandbox sandbox) { var classes = Info.GetClasses(); if (Info.CurrentAssembly == null) { throw new Exception("Info.CurrentAssembly is null"); } var fullName = Info.CurrentAssembly.FullName; var classesToTranslate = Info.ClassTranslations.Values .Where(u => u.Type.Assembly.FullName == fullName).ToArray(); // classesToTranslate = (from i in _info.ClassTranslations.Values // where i.Type.Assembly.FullName == _info.CurrentAssembly.FullName // select this.ge.ToArray(); var interfaces = Info.GetInterfaces(); // var interfacesToTranslate = info.ClassTranslations.Values.Where(u => u.Type.Assembly == info.CurrentAssembly).ToArray(); foreach (var classTranslationInfo in classesToTranslate) { TranslateClass(classTranslationInfo, interfaces, classes); } { var emptyModules = Modules.Where(a => a.IsEmpty).ToArray(); foreach (var module in Modules) { // if (module.IsEmpty) } } }
public void AssemblySandboxWin32Call() { var sandbox1 = new AssemblySandbox(); var assetsFolder = Path.Combine(Directory.GetParent(GetType().Assembly.Location).FullName, "Assets"); sandbox1.LoadAssembly(Path.Combine(assetsFolder, "1", "ManagedLibrary.dll"), false); try { sandbox1.Reflection.InvokeStaticMethod("ManagedLibrary.Class1", "TestCallUnmanaged"); Assert.Fail(); } catch (DllNotFoundException) { } catch (Exception) { Assert.Fail(); } sandbox1.LoadAssembly(Path.Combine(assetsFolder, "2", "UnmanagedLibrary.dll"), false); var result = sandbox1.Reflection.InvokeStaticMethod("ManagedLibrary.Class1", "TestCallUnmanaged"); Assert.IsInstanceOfType(result, typeof(int)); Assert.AreEqual(123, (int)result); sandbox1.Dispose(); }
/// <summary> /// Initializes a new instance of the <see cref="CompiledProgramRunner"/> class. /// </summary> /// <param name="baZicInterpreter">The <see cref="BaZicInterpreterCore"/> that called this class.</param> /// <param name="program">The <see cref="BaZicProgram"/> to compile and run.</param> /// <param name="assemblySandbox">The sandbox that contains the required assemblies.</param> internal CompiledProgramRunner(BaZicInterpreterCore baZicInterpreter, BaZicProgram program, AssemblySandbox assemblySandbox) { Requires.NotNull(baZicInterpreter, nameof(baZicInterpreter)); Requires.NotNull(program, nameof(program)); Requires.NotNull(assemblySandbox, nameof(assemblySandbox)); _baZicInterpreter = baZicInterpreter; _program = program; _assemblySandbox = assemblySandbox; }
static void Main(string[] args) { AssemblySandbox.Init(); var showUsage = true; Console.Write(" "); Console.ForegroundColor = ConsoleColor.Green; Console.Write("C# to Py"); Console.ResetColor(); Console.WriteLine(" compiler ver. {0}", typeof(Program).Assembly.GetName().Version); Console.WriteLine(" Lang.Python ver. {0}", typeof(RequiredTranslatorAttribute).Assembly.GetName().Version); try { var processingContext = new ArgumentProcessingContext(); processingContext.Parse(args); if (processingContext.files.Count < 2) { throw new Exception("Invalid input options, unknown csproj file or output directory"); } if (processingContext.files.Count > 2) { throw new Exception("Unknown parameter " + processingContext.files[2]); } processingContext.Engine.CsProject = processingContext.files.First(); processingContext.Engine.OutDir = processingContext.files.Last(); using (new AppConfigManipulator()) { DoCompilation(processingContext.Engine, ref showUsage); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Success"); Console.ResetColor(); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error:"); Console.ResetColor(); while (exception != null) { Console.WriteLine(" " + exception.Message + "\r\n"); exception = exception.InnerException; } if (showUsage) { Usage(); } } Console.WriteLine("press any key..."); Console.ReadKey(); }
/// <summary> /// Initializes a new instance of the <see cref="BaZicInterpreterCore"/> class. /// </summary> /// <param name="middleware">The middleware</param> /// <param name="assemblySandbox">The assembly sandbox.</param> /// <param name="program">The <see cref="BaZicProgram"/> to interpret.</param> private BaZicInterpreterCore(BaZicInterpreterMiddleware middleware, AssemblySandbox assemblySandbox, BaZicProgram program) : this(middleware, assemblySandbox) { Requires.NotNull(program, nameof(program)); _stateChangedHistory = new List <BaZicInterpreterStateChangeEventArgs>(); ChangeState(this, new BaZicInterpreterStateChangeEventArgs(BaZicInterpreterState.Ready)); Program = program; }
public void AssemblySandboxLoadType() { var sandbox1 = new AssemblySandbox(); try { Type.GetType("System.Windows.UIElement", true, false); Assert.Fail(); } catch (TypeLoadException) { } catch { Assert.Fail(); } try { sandbox1.GetTypeRef("System.Windows.UIElement"); Assert.Fail(); } catch (TypeLoadException) { } catch { Assert.Fail(); } sandbox1.LoadAssembly("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); try { Type.GetType("System.Windows.UIElement", true, false); Assert.Fail(); } catch (TypeLoadException) { } catch { Assert.Fail(); } Assert.AreEqual(1, sandbox1.GetAssemblies().Count); Assert.IsNotNull(sandbox1.GetTypeRef("System.Windows.UIElement", "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")); Assert.AreEqual(1, sandbox1.GetAssemblies().Count); Assert.IsNotNull(sandbox1.GetTypeRef("System.Windows.UIElement")); Assert.AreEqual(6, sandbox1.GetAssemblies().Count); sandbox1.Dispose(); }
/// <summary> /// Initializes a new instance of the <see cref="BaZicInterpreterCore"/> class. /// </summary> /// <param name="middleware">The middleware</param> /// <param name="assemblySandbox">The assembly sandbox.</param> /// <param name="inputCode">The BaZic code to interpret.</param> /// <param name="xamlCode">The XAML code to interpret that represents the user interface.</param> /// <param name="resourceFilePaths">Paths to the resources files (like PNG or JPG) required for the XAML code.</param> /// <param name="optimize">(optional) Defines whether the generated syntax tree must be optimized for the interpreter or not.</param> private BaZicInterpreterCore(BaZicInterpreterMiddleware middleware, AssemblySandbox assemblySandbox, string inputCode, string xamlCode, IEnumerable <string> resourceFilePaths, bool optimize = false) : this(middleware, assemblySandbox) { var parser = new BaZicParser(); var parsingResult = parser.Parse(inputCode, xamlCode, resourceFilePaths, optimize); if (parsingResult.Issues.InnerExceptions.OfType <BaZicParserException>().Count(issue => issue.Level == BaZicParserExceptionLevel.Error) != 0 || (!parsingResult.Issues.InnerExceptions.OfType <BaZicParserException>().Any() && parsingResult.Issues.InnerExceptions.Count > 0)) { throw parsingResult.Issues; } Program = parsingResult.Program; }
/// <summary> /// Initializes a new instance of the <see cref="BaZicInterpreterCore"/> class. /// </summary> /// <param name="middleware">The middleware</param> /// <param name="assemblySandbox">The assembly sandbox.</param> private BaZicInterpreterCore(BaZicInterpreterMiddleware middleware, AssemblySandbox assemblySandbox) { Requires.NotNull(middleware, nameof(middleware)); Requires.NotNull(assemblySandbox, nameof(assemblySandbox)); _middleware = middleware; _stateChangedHistory = new List <BaZicInterpreterStateChangeEventArgs>(); ChangeState(this, new BaZicInterpreterStateChangeEventArgs(BaZicInterpreterState.Ready)); RunningStateManager = new RunningStateManager(this); _assemblySandbox = assemblySandbox; Reflection = _assemblySandbox.Reflection; }
/// <summary> /// Runs C# project compilation and fills <see cref="ProjectCompilation">ProjectCompilation</see> /// and <see cref="CompiledAssembly">CompiledAssembly</see>. /// </summary> /// <param name="sandbox"></param> /// <param name="dllFilename"></param> /// <returns></returns> public EmitResult CompileCSharpProject(AssemblySandbox sandbox, string dllFilename) { // must be public !!!!!!!!!! ProjectCompilation = _cSharpProject.GetCompilationAsync().Result; ProjectCompilation = ProjectCompilation.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); ProjectCompilation = ProjectCompilation.WithReferences(_cSharpProject.MetadataReferences); foreach (var i in ProjectCompilation.References) { Console.WriteLine(" linked with {0}", i.Display); } var tmp = sandbox.EmitCompiledAssembly(ProjectCompilation, out var result, dllFilename); CompiledAssembly = tmp?.WrappedAssembly; return(result); }
public void AssemblySandboxLoadFromPath() { var sandbox1 = new AssemblySandbox(); var sandbox2 = new AssemblySandbox(); Assert.AreEqual(0, sandbox1.GetAssemblies().Count); Assert.AreEqual(0, sandbox2.GetAssemblies().Count); sandbox1.LoadAssembly(@"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\PresentationCore\v4.0_4.0.0.0__31bf3856ad364e35\PresentationCore.dll"); Assert.AreEqual("PresentationCore", sandbox1.GetAssemblies().Single().Name); Assert.AreEqual(0, sandbox2.GetAssemblies().Count); sandbox1.LoadAssembly("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); Assert.AreEqual("PresentationCore", sandbox1.GetAssemblies().Single().Name); Assert.AreEqual(0, sandbox2.GetAssemblies().Count); sandbox1.Dispose(); sandbox2.Dispose(); }
public void AssemblySandboxLoadFromFullName() { var sandbox1 = new AssemblySandbox(); var sandbox2 = new AssemblySandbox(); Assert.AreEqual(0, sandbox1.GetAssemblies().Count); Assert.AreEqual(0, sandbox2.GetAssemblies().Count); sandbox1.LoadAssembly("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); Assert.AreEqual("PresentationCore", sandbox1.GetAssemblies().Single().Name); Assert.AreEqual(0, sandbox2.GetAssemblies().Count); sandbox1.LoadAssembly("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); Assert.AreEqual("PresentationCore", sandbox1.GetAssemblies().Single().Name); Assert.AreEqual(0, sandbox2.GetAssemblies().Count); sandbox1.Dispose(); sandbox2.Dispose(); }
// Private Methods /* * static IPhpStatement[] MkArray(IPhpStatement x) * { * return new IPhpStatement[] { x }; * } */ // Public Methods public void Translate(AssemblySandbox sandbox) { var classes = Info.GetClasses(); var classesToTranslate = Info.ClassTranslations.Values .Where(u => u.Type.Assembly.FullName == Info.CurrentAssembly.FullName).ToArray(); // classesToTranslate = (from i in _info.ClassTranslations.Values // where i.Type.Assembly.FullName == _info.CurrentAssembly.FullName // select this.ge.ToArray(); var interfaces = Info.GetInterfaces(); // var interfacesToTranslate = info.ClassTranslations.Values.Where(u => u.Type.Assembly == info.CurrentAssembly).ToArray(); foreach (var classTranslationInfo in classesToTranslate) { if (classTranslationInfo.Skip) { Debug.Write(""); } PhpClassDefinition phpClass; var phpModule = GetOrMakeModuleByName(classTranslationInfo.ModuleName); // var assemblyTI = _info.GetOrMakeTranslationInfo(_info.CurrentAssembly); { PhpQualifiedName phpBaseClassName; { var netBaseType = classTranslationInfo.Type.BaseType; if ((object)netBaseType == null || netBaseType == typeof(object)) { phpBaseClassName = PhpQualifiedName.Empty; } else { // _state.Principles.CurrentTyp is null so we will obtain absolute name phpBaseClassName = _state.Principles.GetPhpType(netBaseType, true, null); // absolute name var baseTypeTranslationInfo = _state.Principles.GetOrMakeTranslationInfo(netBaseType); if (baseTypeTranslationInfo.Skip) { phpBaseClassName = PhpQualifiedName.Empty; } } } phpClass = phpModule.FindOrCreateClass(classTranslationInfo.ScriptName, phpBaseClassName); } _state.Principles.CurrentType = classTranslationInfo.Type; _state.Principles.CurrentAssembly = _state.Principles.CurrentType.Assembly; Console.WriteLine(classTranslationInfo.ModuleName); IClassMember[] members; if (classTranslationInfo.Type.IsInterface) { var sources = interfaces.Where(i => i.FullName == classTranslationInfo.Type.FullName).ToArray(); members = (from i in sources from j in i.ClassDeclaration.Members select j).ToArray(); { var fileNames = classTranslationInfo.Type.GetCustomAttributes <RequireOnceAttribute>() .Select(i => i.Filename).Distinct().ToArray(); if (fileNames.Any()) { var b = fileNames.Select(u => new PhpConstValue(u)).ToArray(); phpModule.RequiredFiles.AddRange(b); } } } else { var sources = classes.Where(i => i.FullName == classTranslationInfo.Type.FullName).ToArray(); members = (from i in sources from j in i.ClassDeclaration.Members select j).ToArray(); { var fileNames = classTranslationInfo.Type.GetCustomAttributes <RequireOnceAttribute>() .Select(i => i.Filename).Distinct().ToArray(); if (fileNames.Any()) { var b = fileNames.Select(u => new PhpConstValue(u)).ToArray(); phpModule.RequiredFiles.AddRange(b); } } } { var c = members.OfType <ConstructorDeclaration>().ToArray(); if (c.Length > 1) { throw new Exception("PHP supports only one constructor per class"); } if (c.Any()) { TranslateConstructor(phpClass, c.First()); } } { foreach (var methodDeclaration in members.OfType <MethodDeclaration>()) { TranslateMethod(phpClass, methodDeclaration); } } { foreach (var pDeclaration in members.OfType <CsharpPropertyDeclaration>()) { TranslateProperty(phpClass, pDeclaration); } } { foreach (var constDeclaration in members.OfType <FieldDeclaration>()) { TranslateField(phpModule, phpClass, constDeclaration); } } _state.Principles.CurrentType = null; { if (classTranslationInfo.IsPage) { { var ati = Info.GetOrMakeTranslationInfo(Info.CurrentAssembly); if (ati.DefaultTimezone.HasValue) { // date_default_timezone_set('America/Los_Angeles'); var a = new PhpValueTranslator(_state); var aa = a.Visit(new ConstValue(ati.DefaultTimezone.Value)); var dateDefaultTimezoneSet = new PhpMethodCallExpression("date_default_timezone_set", aa); phpModule.BottomCode.Statements.Add(new PhpExpressionStatement(dateDefaultTimezoneSet)); } } { var mti = MethodTranslationInfo.FromMethodInfo(classTranslationInfo.PageMethod, classTranslationInfo); var callMain = new PhpMethodCallExpression(mti.ScriptName); callMain.SetClassName( classTranslationInfo.ScriptName, mti ); phpModule.BottomCode.Statements.Add(new PhpExpressionStatement(callMain)); } } } { var moduleCodeRequests = new List <ModuleCodeRequest>(); var codeRequests = (phpModule as ICodeRelated).GetCodeRequests().ToArray(); { var classCodeRequests = (from request in codeRequests.OfType <ClassCodeRequest>() where request.ClassName != null select request.ClassName.FullName) .Distinct() .ToArray(); foreach (var req in classCodeRequests) { var m = Info.ClassTranslations.Values.Where(i => i.ScriptName.FullName == req).ToArray(); if (m.Length != 1) { throw new NotSupportedException(); } var mm = m[0]; if (mm.DontIncludeModuleForClassMembers) { continue; } var includeModule = mm.IncludeModule; if (includeModule == null || mm.ModuleName == phpModule.Name) { continue; } var h = new ModuleCodeRequest(includeModule, "class request: " + req); moduleCodeRequests.Add(h); } } { var moduleRequests = (from i in codeRequests.OfType <ModuleCodeRequest>() where i.ModuleName != null select i).Union(moduleCodeRequests).ToArray(); var moduleNames = (from mReq in moduleRequests where mReq.ModuleName != phpModule.Name let mName = mReq.ModuleName where mName != null select mName ).Distinct().ToArray(); foreach (var i in moduleNames.Where(x => !PhpCodeModuleName.IsFrameworkName(x))) { AppendCodeReq(i, phpModule); } } } } { var emptyModules = Modules.Where(a => a.IsEmpty).ToArray(); foreach (var module in Modules) { // if (module.IsEmpty) } } }
/// <summary> /// Tworzy instancję obiektu /// <param name="sandbox"></param> /// </summary> public TranslationInfo(AssemblySandbox sandbox) { Sandbox = sandbox; }
/// <summary> /// Initializes a new instance of the <see cref="FastReflection"/> class. /// </summary> /// <param name="assemblySandbox">The assembly sandbox.</param> public FastReflection(AssemblySandbox assemblySandbox) { Requires.NotNull(assemblySandbox, nameof(assemblySandbox)); _assemblySandbox = assemblySandbox; }
/// <summary> /// Initializes a new instance of the <see cref="BaZicInterpreter"/> class. /// </summary> private BaZicInterpreter() { _assemblySandbox = new AssemblySandbox(); }
// Private Methods /* static IPhpStatement[] MkArray(IPhpStatement x) { return new IPhpStatement[] { x }; } */ #endregion Static Methods #region Methods // Public Methods public void Translate(AssemblySandbox sandbox) { var classes = _info.GetClasses(); var classesToTranslate = _info.ClassTranslations.Values.Where(u => u.Type.Assembly.FullName == _info.CurrentAssembly.FullName).ToArray(); // classesToTranslate = (from i in _info.ClassTranslations.Values // where i.Type.Assembly.FullName == _info.CurrentAssembly.FullName // select this.ge.ToArray(); var interfaces = _info.GetInterfaces(); // var interfacesToTranslate = info.ClassTranslations.Values.Where(u => u.Type.Assembly == info.CurrentAssembly).ToArray(); foreach (var classTranslationInfo in classesToTranslate) { if (classTranslationInfo.Skip) Debug.Write(""); PhpClassDefinition phpClass; var phpModule = GetOrMakeModuleByName(classTranslationInfo.ModuleName); // var assemblyTI = _info.GetOrMakeTranslationInfo(_info.CurrentAssembly); #region Szukanie / Tworzenie PhpClassDefinition { PhpQualifiedName phpBaseClassName; #region Szukanie nazwy klasy bazowej { var netBaseType = classTranslationInfo.Type.BaseType; if ((object)netBaseType == null || netBaseType == typeof(object)) phpBaseClassName = PhpQualifiedName.Empty; else { // _state.Principles.CurrentTyp is null so we will obtain absolute name phpBaseClassName = _state.Principles.GetPhpType(netBaseType, true, null); // absolute name var baseTypeTranslationInfo = _state.Principles.GetOrMakeTranslationInfo(netBaseType); if (baseTypeTranslationInfo.Skip) phpBaseClassName = PhpQualifiedName.Empty; } } #endregion phpClass = phpModule.FindOrCreateClass(classTranslationInfo.ScriptName, phpBaseClassName); } #endregion _state.Principles.CurrentType = classTranslationInfo.Type; _state.Principles.CurrentAssembly = _state.Principles.CurrentType.Assembly; Console.WriteLine(classTranslationInfo.ModuleName); Cs.Compiler.IClassMember[] members; if (classTranslationInfo.Type.IsInterface) { var sources = interfaces.Where(i => i.FullName == classTranslationInfo.Type.FullName).ToArray(); members = (from i in sources from j in i.ClassDeclaration.Members select j).ToArray(); { var fileNames = classTranslationInfo.Type.GetCustomAttributes<RequireOnceAttribute>().Select(i => i.Filename).Distinct().ToArray(); if (fileNames.Any()) { var b = fileNames.Select(u => new PhpConstValue(u)).ToArray(); phpModule.RequiredFiles.AddRange(b); } } } else { var sources = classes.Where(i => i.FullName == classTranslationInfo.Type.FullName).ToArray(); members = (from i in sources from j in i.ClassDeclaration.Members select j).ToArray(); { var fileNames = classTranslationInfo.Type.GetCustomAttributes<RequireOnceAttribute>().Select(i => i.Filename).Distinct().ToArray(); if (fileNames.Any()) { var b = fileNames.Select(u => new PhpConstValue(u)).ToArray(); phpModule.RequiredFiles.AddRange(b); } } } #region Constructors { var c = members.OfType<ConstructorDeclaration>().ToArray(); if (c.Length > 1) throw new Exception("PHP supports only one constructor per class"); if (c.Any()) TranslateConstructor(phpClass, c.First()); } #endregion #region Metody { foreach (var methodDeclaration in members.OfType<MethodDeclaration>()) TranslateMethod(phpClass, methodDeclaration); } #endregion #region Własności { foreach (var pDeclaration in members.OfType<CsharpPropertyDeclaration>()) TranslateProperty(phpClass, pDeclaration); } #endregion #region Pola, stałe { foreach (var constDeclaration in members.OfType<FieldDeclaration>()) TranslateField(phpModule, phpClass, constDeclaration); } #endregion _state.Principles.CurrentType = null; #region Wywołanie metody defaulttimezone oraz MAIN dla PAGE { if (classTranslationInfo.IsPage) { #region Timezone { var ati = _info.GetOrMakeTranslationInfo(_info.CurrentAssembly); if (ati.DefaultTimezone.HasValue) { // date_default_timezone_set('America/Los_Angeles'); var a = new PhpValueTranslator(_state); var aa = a.Visit(new ConstValue(ati.DefaultTimezone.Value)); var dateDefaultTimezoneSet = new PhpMethodCallExpression("date_default_timezone_set", aa); phpModule.BottomCode.Statements.Add(new PhpExpressionStatement(dateDefaultTimezoneSet)); } } #endregion #region Wywołanie main { var mti = MethodTranslationInfo.FromMethodInfo(classTranslationInfo.PageMethod, classTranslationInfo); var callMain = new PhpMethodCallExpression(mti.ScriptName); callMain.SetClassName( classTranslationInfo.ScriptName, mti ); phpModule.BottomCode.Statements.Add(new PhpExpressionStatement(callMain)); } #endregion } } #endregion #region includy { var moduleCodeRequests = new List<ModuleCodeRequest>(); var codeRequests = (phpModule as ICodeRelated).GetCodeRequests().ToArray(); { var classCodeRequests = (from request in codeRequests.OfType<ClassCodeRequest>() where request.ClassName != null select request.ClassName.FullName) .Distinct() .ToArray(); foreach (var req in classCodeRequests) { var m = _info.ClassTranslations.Values.Where(i => i.ScriptName.FullName == req).ToArray(); if (m.Length != 1) throw new NotSupportedException(); var mm = m[0]; if (mm.DontIncludeModuleForClassMembers) continue; var includeModule = mm.IncludeModule; if (includeModule == null || mm.ModuleName == phpModule.Name) continue; var h = new ModuleCodeRequest(includeModule, "class request: " + req); moduleCodeRequests.Add(h); } } { var moduleRequests = (from i in codeRequests.OfType<ModuleCodeRequest>() where i.ModuleName != null select i).Union(moduleCodeRequests).ToArray(); var moduleNames = (from mReq in moduleRequests where mReq.ModuleName != phpModule.Name let mName = mReq.ModuleName where mName != null select mName ).Distinct().ToArray(); foreach (var i in moduleNames.Where(x => !PhpCodeModuleName.IsFrameworkName(x))) AppendCodeReq(i, phpModule); } } #endregion } { var emptyModules = _modules.Where(a => a.IsEmpty).ToArray(); foreach (var module in _modules) { // if (module.IsEmpty) } } }