public void ShouldGenerateComplexClass() { var nsp = Noast.Create <INamespace>("MyProject.Complex"); var cla = Noast.Create <IClass>("Person", nsp).With(Visibility.Public); var field = Noast.Create <IField>("cellCount").With(Visibility.Private); field.Type = typeof(ulong).FullName; cla.Fields.Add(field); var meth = Noast.Create <IMethod>("get_Id").With(Visibility.Internal); meth.ReturnType = typeof(Guid).FullName; cla.Methods.Add(meth); meth = Noast.Create <IMethod>("add_IdChanged").With(Visibility.Protected); meth.AddParameter("handler", typeof(EventHandler).FullName); cla.Methods.Add(meth); meth = Noast.Create <IMethod>(".ctor").With(Visibility.ProtectedInternal); meth.AddParameter("id", typeof(Guid).FullName); meth.AddParameter("name", typeof(string).FullName); cla.Methods.Add(meth); meth = Noast.Create <IMethod>("op_Inequality").With(Visibility.Public); meth.ReturnType = typeof(bool).FullName; meth.AddParameter("first", "Person"); meth.AddParameter("second", "Person"); cla.Methods.Add(meth); meth = Noast.Create <IMethod>("get_Item").With(Visibility.Public); meth.AddParameter("index", typeof(int).FullName); meth.ReturnType = typeof(string).FullName; cla.Methods.Add(meth); Console.WriteLine(nsp); }
public void ShouldGenerateMetadata() { var myInfo = Noast.Create <IMetadata>("Super.Awesome.Lib"); myInfo.AddUsing("System"); myInfo.AddUsing("System.Diagnostics"); myInfo.AddUsing("System.Reflection"); myInfo.AddUsing("System.Runtime.CompilerServices"); myInfo.Version = new Version("4.6.1.0"); myInfo.ClsCompliant = true; myInfo.Company = "Autofac"; myInfo.Configuration = "Debug"; myInfo.Copyright = "Copyright © 2015 Autofac Contributors"; myInfo.Description = "Autofac Inversion of Control container for .NET applications."; myInfo.Alias = "Autofac"; myInfo.InternalVersion = "4.6.1-develop-00422"; myInfo.Product = "Autofac"; myInfo.Title = "Autofac"; myInfo.NeutralLocale = "en-US"; myInfo.ComVisible = false; myInfo.Trademark = ""; myInfo.Culture = "en-GB"; myInfo.Guid = Guid.NewGuid(); myInfo.Metadata["Author"] = "PhD Franz Schuster"; myInfo.Metadata["CreationDate"] = "August 23 2011"; myInfo.Metadata["Website"] = "www.google.de"; myInfo.TargetFramework = "4.5"; Console.WriteLine(myInfo); }
public void ShouldGenerateStruct() { var myStruct = Noast.Create <IStruct>("MyStruct").With(Visibility.Public); myStruct.AddAttribute(typeof(SerializableAttribute).FullName); Console.WriteLine(myStruct); }
public void ShouldGenerateAbstractClass() { var myClass = Noast.Create <IClass>("A").With(Visibility.Public).With(Modifier.Abstract); var myMeth = Noast.Create <IMethod>("DoWork").Accepts("i @ int") .With(Visibility.Public).With(Modifier.Abstract); myClass.Methods.Add(myMeth); Console.WriteLine(myClass); myClass = Noast.Create <IClass>("D").With(Visibility.Public); myMeth = Noast.Create <IMethod>("DoWork").Accepts("i @ int") .With(Visibility.Public).With(Modifier.Virtual); myClass.Methods.Add(myMeth); Console.WriteLine(myClass); myClass = Noast.Create <IClass>("E").With(Visibility.Public).With(Modifier.Abstract); myClass.BaseType = Noast.Create <IBase>("D"); myMeth = Noast.Create <IMethod>("DoWork").Accepts("i @ int") .With(Visibility.Public).With(Modifier.Abstract).With(Modifier.Override); myClass.Methods.Add(myMeth); Console.WriteLine(myClass); myClass = Noast.Create <IClass>("F").With(Visibility.Public); myClass.BaseType = Noast.Create <IBase>("E"); myMeth = Noast.Create <IMethod>("DoWork").Accepts("i @ int") .With(Visibility.Public).With(Modifier.Override); myClass.Methods.Add(myMeth); Console.WriteLine(myClass); myClass = Noast.Create <IClass>("D").With(Visibility.Public).With(Modifier.Sealed); Console.WriteLine(myClass); myClass = Noast.Create <IClass>("D").With(Visibility.Public); myClass.BaseType = Noast.Create <IBase>("C"); myMeth = Noast.Create <IMethod>("DoWork") .With(Visibility.Public).With(Modifier.Sealed).With(Modifier.Override); myClass.Methods.Add(myMeth); Console.WriteLine(myClass); }
public void ShouldGenerateInterface() { var myIntf = Noast.Create <IInterface>("MyInterface").With(Visibility.Public); myIntf.AddImplements(typeof(IDisposable).FullName); myIntf.AddImplements(typeof(ICloneable).FullName); Console.WriteLine(myIntf); }
private static IMethod CreateSwitchMethod() { var meth = Noast.Create <IMethod>("GetInstance").With(Visibility.Public).With(Modifier.Static); meth.ReturnType = "Api.IPlatform"; meth.Body = "if (Environment.OSVersion.Platform == PlatformID.Win32NT) return new Win32Platform(); return new MonoPlatform();"; return(meth); }
public void ShouldGenerateCustomIndexer() { var myIndx = Noast.Create <IIndexer>("MyIndexer").Accepts("int").With(Visibility.Public); myIndx.Getter = "return null;"; myIndx.Setter = "return;"; Console.WriteLine(myIndx); }
public void ShouldGenerateEnum() { var myEnum = Noast.Create <IEnum>("MyEnum").With(Visibility.Public); myEnum.AddValue("Test1"); myEnum.AddValue("Test2"); myEnum.AddValue("Test3"); Console.WriteLine(myEnum); }
public void ShouldGenerateClass() { var myClass = Noast.Create <IClass>("MyClass").With(Visibility.Public) .ChildOf(typeof(Delegate).FullName); myClass.AddImplements(typeof(IDisposable).FullName); myClass.AddImplements(typeof(ICloneable).FullName); Console.WriteLine(myClass); }
private static IMetadata CreateMetadata(string file, string replaces) { var name = Path.GetFileNameWithoutExtension(file); var meta = Noast.Create <IMetadata>(name); meta.AddUsing("System.Runtime.Versioning"); meta.TargetFramework = "4.5"; meta.Metadata[Defaults.Creator] = typeof(Purger).Namespace; meta.Metadata[Defaults.Replaces] = replaces; return(meta); }
private static IEnumerable <Tuple <IMethod, MethodDefinition> > CollectPInvokes(AssemblyDefinition ass) { var methodSigs = new List <string>(); foreach (var type in ass.GetAllTypes()) { foreach (var meth in type.Methods) { if (meth.HasPInvokeInfo) { var pinv = meth.PInvokeInfo; var name = meth.Name; if (!Enumerable.Range('A', 26).Contains(name[0])) { name = pinv.EntryPoint; } if (name.StartsWith("#", StringComparison.InvariantCulture)) { name = Path.GetFileNameWithoutExtension(pinv.Module.Name) + name.Substring(1); } var key = (pinv.Module.Name + "/" + pinv.EntryPoint + "/" + name).ToLowerInvariant(); if (methodSigs.Contains(key)) { continue; } var gen = Noast.Create <IMethod>(name); gen.ReturnType = meth.ReturnType.Name; var attr = Noast.Create <IAttribute>(typeof(DllImportAttribute).Name); attr.Values.Add($"\"{pinv.Module}\""); attr.Properties["CharSet"] = pinv.ToCharset(); attr.Properties["SetLastError"] = pinv.SupportsLastError; var entryPoint = pinv.EntryPoint; attr.Properties["EntryPoint"] = $"\"{entryPoint}\""; gen.Attributes.Add(attr); foreach (var parm in meth.Parameters) { AddParam(parm, gen); } methodSigs.Add(key); if (Type.GetType(meth.ReturnType.FullName) == null) { continue; } if (meth.Parameters.Any(p => Type.GetType(p.ParameterType.FullName) == null)) { continue; } yield return(Tuple.Create(gen, meth)); } } } }
public void ShouldGenerateAll() { var aNsp = Noast.Create <INamespace>("System.IO.Nasa"); aNsp.AddUsing(typeof(StringBuilder).Namespace); var aStruct = Noast.Create <IStruct>("HelloStruct", aNsp); var anEnum = Noast.Create <IEnum>("HelloEnum", aNsp); var anInterf = Noast.Create <IInterface>("HelloInterf", aNsp); var aClass = Noast.Create <IClass>("HelloClass", aNsp); var aDeleg = Noast.Create <IDelegate>("HelloDelegate", aNsp); Console.WriteLine(aNsp); }
public void ShouldGeneratePartialClass() { var myClass = Noast.Create <IClass>("MyPartClass").With(Visibility.Public) .With(Modifier.Partial); myClass.AddImplements(typeof(IDisposable).FullName); Console.WriteLine(myClass); myClass = Noast.Create <IClass>("MyPartClass").With(Visibility.Public) .With(Modifier.Partial); var myMeth = Noast.Create <IMethod>("Dispose").With(Visibility.Public); myClass.Methods.Add(myMeth); Console.WriteLine(myClass); }
public void ShouldGenerateOperator() { // Manual var myOp = Noast.Create <IOperator>("UnaryPlus").With(Modifier.Static).With(Visibility.Public); Console.WriteLine(myOp); // Automatic var myClass = Noast.Create <IClass>("Autogen"); var op = Noast.Create <IMethod>("op_UnaryPlus").With(Visibility.Public); myClass.Methods.Add(op); Console.WriteLine(myClass); // Compare Assert.AreEqual(myOp.ToString(), myClass.ToString()); }
public void ShouldGenerateInitializer() { // Manual var myCnstr = Noast.Create <IConstructor>("MyConstructor").With(Modifier.Static); Console.WriteLine(myCnstr); // Automatic var myClass = Noast.Create <IClass>("Autogen"); var cstr = Noast.Create <IMethod>(".cctor"); myClass.Methods.Add(cstr); Console.WriteLine(myClass); // Compare Assert.AreEqual(myCnstr.ToString(), myClass.ToString()); }
public void ShouldGenerateNoEvent() { var myClass = Noast.Create <IInterface>("IImageList"); var adder = Noast.Create <IMethod>("Add").With(Visibility.Public); adder.AddParameter("listener", typeof(IntPtr).FullName); myClass.Methods.Add(adder); var remover = Noast.Create <IMethod>("Remove").With(Visibility.Public); remover.AddParameter("listener", typeof(int).FullName); myClass.Methods.Add(remover); Console.WriteLine(myClass); // Check it Assert.AreEqual(0, myClass.Events.Count); Assert.AreEqual(2, myClass.Methods.Count); }
public void ShouldGenerateCustomProps() { var intf = Noast.Create <IInterface>("MyIntf"); intf.Methods.Add(Noast.Create <IMethod>("get_ReadOnly").Returns("string")); intf.Methods.Add(Noast.Create <IMethod>("set_WriteOnly").Accepts("char")); intf.Methods.Add(Noast.Create <IMethod>("get_ReadWrite").Returns("Stream")); intf.Methods.Add(Noast.Create <IMethod>("set_ReadWrite").Accepts("Stream")); intf.Methods.Add(Noast.Create <IMethod>("add_AutoEvent").Accepts("EventHandler")); intf.Methods.Add(Noast.Create <IMethod>("remove_AutoEvent").Accepts("EventHandler")); intf.Methods.Add(Noast.Create <IMethod>("get_ReadOnly").Accepts("byte").Returns("string")); intf.Methods.Add(Noast.Create <IMethod>("set_WriteOnly").Accepts("short", "string")); intf.Methods.Add(Noast.Create <IMethod>("get_ReadWrite").Accepts("int").Returns("string")); intf.Methods.Add(Noast.Create <IMethod>("set_ReadWrite").Accepts("int", "string")); Console.WriteLine(intf); }
private static void AddParam(ParameterDefinition parm, IMethod gen) { var name = parm.Name; if (!Enumerable.Range('A', 26).Contains(name.FirstOrDefault())) { name = "p" + gen.Parameters.Count; } var par = Noast.Create <IParameter>(name); par.Type = Simplify(parm.ParameterType.Name); if (parm.ParameterType.IsByReference) { par.Modifier = ParamModifier.Ref; } gen.Parameters.Add(par); }
private static IEnumerable <IMethod> DelegateInterface(IMethod externMeth) { var meth = Noast.Create <IMethod>($"{prefix}{externMeth.Name}"); // TODO: method cloning?! externMeth yield return(meth); meth = Noast.Create <IMethod>(externMeth.Name).With(Visibility.Public); meth.ReturnType = externMeth.ReturnType; var preamble = meth.ReturnType.ToLowerInvariant() == "void" ? "" : "return "; var parms = string.Join(", ", externMeth.Parameters.Select(p => (p.IsRef() ? "ref " : "") + p.Name)); meth.Body = $"{preamble}{prefix}{externMeth.Name}({parms});"; foreach (var parm in externMeth.Parameters) { meth.Parameters.Add(parm); } yield return(meth); }
public void ShouldGenerateMethod() { var myMeth = Noast.Create <IMethod>("MyMethod").With(Visibility.Public); var attr = myMeth.AddAttribute(typeof(DllImportAttribute).FullName); attr.Values.Add("cfgmgr32.dll"); attr.Values.Add(44); attr.Values.Add(true); attr.Properties["Entrypoint"] = "Calc"; attr.Properties["Count"] = 43; attr.Properties["SetLastError"] = true; myMeth.ReturnType = typeof(long).FullName; myMeth.Body = "System.Console.WriteLine(\"Hello world!\");" + "throw new System.InvalidOperationException();"; myMeth.AddParameter("a", "int"); myMeth.AddParameter("b", "int", ParamModifier.Ref); myMeth.AddParameter("c", "int", ParamModifier.Out); Console.WriteLine(myMeth); }
private static void GenerateMembers(AType holder, IType type) { var fldHolder = holder as IHasFields; if (fldHolder != null) { foreach (var fld in type.Fields.Values) { var myFld = Noast.Create <IField>(fld.Name); myFld.Type = Simplify(DerivedClassDeobfuscate(fld.Type)); fldHolder.Fields.Add(myFld); } } var methHolder = holder as IHasMethods; if (methHolder != null) { foreach (var meth in type.Methods.Values) { var myMeth = Noast.Create <IMethod>(meth.Name); var parmIndex = 0; foreach (var parm in meth.Parameters) { var parmName = parm.Name; if (string.IsNullOrWhiteSpace(parmName)) { parmName = $"parm{parmIndex++}"; } parmName = ToName(Deobfuscate(parmName)); var parmType = Simplify(DerivedClassDeobfuscate(parm.Type)); var parmMod = default(ParamModifier?); if (parm.Type.EndsWith("&")) { parmMod = ParamModifier.Ref; } myMeth.AddParameter(parmName, parmType, parmMod); } myMeth.ReturnType = Simplify(DerivedClassDeobfuscate(meth.ReturnType)); methHolder.Methods.Add(myMeth); } } }
private static IEnumerable <IMethod> ImplementInterface(IMethod externMeth) { var meth = Noast.Create <IMethod>(externMeth.Name).With(Visibility.Public); meth.ReturnType = externMeth.ReturnType; // meth.Body = $"throw new NotImplementedException(\"Sorry!\");"; if (meth.ReturnType.ToLowerInvariant() == "void") { meth.Body = "return;"; } else { meth.Body = $"return default({meth.ReturnType});"; } foreach (var parm in externMeth.Parameters) { meth.Parameters.Add(parm); } yield return(meth); }
public void ShouldGenerateEvent() { // Manual var myEvent = Noast.Create <IEvent>("MyEvent").With(Visibility.Public); Console.WriteLine(myEvent); // Automatic var myClass = Noast.Create <IClass>("Autogen"); var adder = Noast.Create <IMethod>("add_MyEvent").With(Visibility.Public); adder.AddParameter("listener", typeof(object).FullName); myClass.Methods.Add(adder); var remover = Noast.Create <IMethod>("remove_MyEvent").With(Visibility.Public); remover.AddParameter("listener", typeof(object).FullName); myClass.Methods.Add(remover); Console.WriteLine(myClass); // Compare Assert.AreEqual(myEvent.ToString(), myClass.ToString()); }
public void ShouldGenerateProperty() { // Manual var myProp = Noast.Create <IProperty>("MyProperty").With(Visibility.Public); Console.WriteLine(myProp); // Automatic var myClass = Noast.Create <IClass>("Autogen"); var getter = Noast.Create <IMethod>("get_MyProperty").With(Visibility.Public); getter.ReturnType = typeof(object).FullName; myClass.Methods.Add(getter); var setter = Noast.Create <IMethod>("set_MyProperty").With(Visibility.Public); setter.AddParameter("value", typeof(object).FullName); myClass.Methods.Add(setter); Console.WriteLine(myClass); // Compare Assert.AreEqual(myProp.ToString(), myClass.ToString()); }
public void ShouldGenerateDelegate() { var myDlgt = Noast.Create <IDelegate>("MyDelegate").With(Visibility.Public); Console.WriteLine(myDlgt); }
internal static int Clean(PurifyOptions opts) { var files = GetAssemblyFiles(opts.WorkDir).Where(f => !f.Contains(".OS.")).ToArray(); log.Info($"Found {files.Length} files!"); var resolv = new DefaultAssemblyResolver(); resolv.AddSearchDirectory(opts.WorkDir); var rparam = new ReaderParameters { AssemblyResolver = resolv }; var wparam = new WriterParameters(); var halDir = Path.Combine(opts.CodeDir); halDir = Directory.CreateDirectory(halDir).FullName; foreach (var file in files) { using (var stream = new MemoryStream(File.ReadAllBytes(file))) { var ass = AssemblyDefinition.ReadAssembly(stream, rparam); log.Info($" - '{ass.FullName}'"); var methods = CollectPInvokes(ass).ToList(); if (!methods.Any()) { continue; } var apiName = ass.Name.Name + ".OS.Api"; var apiCS = Path.Combine(halDir, apiName + ".cs"); var implName = ass.Name.Name + ".OS.Impl"; var implCS = Path.Combine(halDir, implName + ".cs"); using (var pinvoke = File.CreateText(apiCS)) { var nsp = Noast.Create <INamespace>(apiName); nsp.AddUsing("System"); nsp.AddUsing("System.Runtime.InteropServices"); nsp.AddUsing("System.Runtime.InteropServices.ComTypes"); nsp.AddUsing("System.Text"); var cla = Noast.Create <IInterface>("IPlatform", nsp); foreach (var meth in methods.Select(m => m.Item1)) { cla.Methods.Add(meth); } pinvoke.Write(nsp); } string f; var apiCSAss = Compiler.CreateAssembly(string.Empty, apiName, new[] { apiCS }); File.Copy(apiCSAss.Location, f = Path.Combine(halDir, apiName + ".dll"), true); log.Info($" --> '{Path.GetFileName(apiCS)}' ({Path.GetFileName(f)})"); var apiAssDef = AssemblyDefinition.ReadAssembly(f, rparam); using (var pinvoke = File.CreateText(implCS)) { var nsp = Noast.Create <INamespace>(implName); nsp.AddUsing("System"); nsp.AddUsing("System.Runtime.InteropServices"); nsp.AddUsing("System.Runtime.InteropServices.ComTypes"); nsp.AddUsing("System.Text"); var cla = Noast.Create <IClass>("Win32Platform", nsp).With(Visibility.Internal); cla.AddImplements(apiName + ".IPlatform"); foreach (var meth in methods.Select(m => m.Item1).SelectMany(DelegateInterface)) { cla.Methods.Add(meth); } cla = Noast.Create <IClass>("MonoPlatform", nsp).With(Visibility.Internal); cla.AddImplements(apiName + ".IPlatform"); foreach (var meth in methods.Select(m => m.Item1).SelectMany(ImplementInterface)) { cla.Methods.Add(meth); } cla = Noast.Create <IClass>("Platforms", nsp).With(Visibility.Public).With(Modifier.Static); cla.Methods.Add(CreateSwitchMethod()); pinvoke.Write(nsp); } var implCSAss = Compiler.CreateAssembly(string.Empty, implName, new[] { implCS }, new[] { f }); File.Copy(implCSAss.Location, f = Path.Combine(halDir, implName + ".dll"), true); log.Info($" --> '{Path.GetFileName(implCS)}' ({Path.GetFileName(f)})"); var implAssDef = AssemblyDefinition.ReadAssembly(f, rparam); var iplat = apiAssDef.GetAllTypes().First(t => t.Name == "IPlatform"); var platfs = implAssDef.GetAllTypes().First(t => t.Name == "Platforms"); var platGet = platfs.Methods.First(); PurifyCalls(methods.Select(m => m.Item2), platGet, iplat); log.InfoFormat(" added '{0}'!", CopyTypeRef(apiCSAss, opts.WorkDir)); log.InfoFormat(" added '{0}'!", CopyTypeRef(implCSAss, opts.WorkDir)); ass.Write(file, wparam); } } resolv.Dispose(); return(0); }
public void ShouldGenerateField() { var myField = Noast.Create <IField>("MyField").With(Visibility.Public); Console.WriteLine(myField); }
private static IEnumerable <KeyValuePair <string, INamespace> > GenerateNamespaces(IDependencyReport report) { ICodeValidator validator = new MethodDeduper(); foreach (var pair in report.Units) { var ass = pair.Value; var fileName = $"{ass.Name}.cs"; var groups = pair.Value.Types.GroupBy(u => u.Value.Namespace); foreach (var group in groups) { var nspName = Deobfuscate(group.Key); var nsp = Noast.Create <INamespace>(nspName); nsp.AddUsing("System"); nsp.AddUsing("System.Text"); foreach (var twik in group) { var type = twik.Value; var kind = type.Kind; var rawName = DerivedClassDeobfuscate(type.Name).Replace("`1", ""); var name = rawName; if (!IsAttribute(type) && (HasNativeMethod(type) || kind == TypeKind.Struct || kind == TypeKind.Class)) { kind = TypeKind.Interface; if (HasNativeMethod(type)) { name = $"I{name}"; } } var cstrs = type.Methods.Where(m => m.Value.Name.Equals(Defaults.InstConstrName)).ToArray(); if (cstrs.Any() && !IsAttribute(type)) { var factType = Noast.Create <IInterface>($"I{rawName}Factory", nsp).With(Visibility.Public); foreach (var cstr in cstrs) { var factMethod = Noast.Create <IMethod>($"Create{rawName}"); factMethod.ReturnType = name; foreach (var parm in cstr.Value.Parameters) { var fparm = Noast.Create <IParameter>(parm.Name); fparm.Type = parm.Type; factMethod.Parameters.Add(fparm); } factType.Methods.Add(factMethod); type.Methods.Remove(cstr.Key); } } switch (kind) { case TypeKind.Interface: var intf = Noast.Create <IInterface>(name, nsp).With(Visibility.Public); GenerateMembers(intf, type); validator.Validate(intf); break; case TypeKind.Struct: var stru = Noast.Create <IStruct>(name, nsp).With(Visibility.Public); GenerateMembers(stru, type); validator.Validate(stru); break; case TypeKind.Class: var clas = Noast.Create <IClass>(name, nsp).With(Visibility.Public); GenerateMembers(clas, type); validator.Validate(clas); break; case TypeKind.Delegate: var dlgt = Noast.Create <IDelegate>(name, nsp).With(Visibility.Public); var invoke = type.Methods.Single(); foreach (var parm in invoke.Value.Parameters) { dlgt.AddParameter(parm.Name, Simplify(parm.Type)); } break; case TypeKind.Enum: var enm = Noast.Create <IEnum>(name, nsp).With(Visibility.Public); foreach (var val in type.Values) { enm.AddValue(val.Value.Name); } break; } } yield return(new KeyValuePair <string, INamespace>(fileName, nsp)); } } }
public void ShouldGenerateIndexer() { var myIndx = Noast.Create <IIndexer>("MyIndexer").Accepts("int").With(Visibility.Public); Console.WriteLine(myIndx); }
public void ShouldGenerateParameter() { var myParm = Noast.Create <IParameter>("myParam"); Console.WriteLine(myParm); }