public void ChildWithOneInterface_IncludeMixinWithManyInterfaces_OnlyMissingInterfacesAdded() { var sourceCode = new SourceCode(Files.Interface); var childClass = sourceCode.Class(nameof(ChildWithInterface)); var startPos = childClass.GetLocation().SourceSpan.Start; var interfaces = new InterfaceList(new[] { new Interface(sourceCode.GetTypeByName(nameof(IFirstInterface))), new Interface(sourceCode.GetTypeByName(nameof(ISecondInterface))) }); var @class = Substitute.For<ClassWithTypeSymbol>(); @class.IsInterface.Returns(false); @class.Interfaces.Returns(interfaces); var mixin = Substitute.For<MixinReference>(); mixin.Class.Returns(@class); var addInterfaceWriter = new AddInterfacesToChildSyntaxWriter(mixin, sourceCode.Semantic, startPos); var newChildClass = (ClassDeclarationSyntax)addInterfaceWriter.Visit(childClass); var baseList = newChildClass.BaseList.Types; // assert: child class should have both interfaces Assert.AreEqual(2, baseList.Count); Assert.IsNotNull( baseList.Single(x => x.TypeName() == nameof(IFirstInterface))); Assert.IsNotNull( baseList.Single(x => x.TypeName() == nameof(ISecondInterface))); }
/// <summary> /// 获取接口列表 /// </summary> /// <returns></returns> public static async Task <List <InterfaceList> > GetInterfaceList() { var list = new List <InterfaceList>(); var sql = "select * from InterfaceList"; using (var conn = DBFactory.Create()) { try { conn.Open(); var cmd = conn.CreateCommand() as DbCommand; cmd.CommandText = sql; var reader = await cmd.ExecuteReaderAsync(); while (reader.Read()) { var model = new InterfaceList { InterfaceName = reader["InstrumentName"].ToString(), Comment = reader["ModelName"].ToString(), Active = reader["ModulesMax"].ToInt32(), }; list.Add(model); } } catch (Exception e) { } return(list); } }
private ClassDeclarationSyntax ImplementInterfaceByChild(string childClassName) { var sourceCode = new SourceCode(Files.Interface); var childClass = sourceCode.Class(childClassName); var startPos = childClass.GetLocation().SourceSpan.Start; // create a mixin class that implements an interface var mixin = Substitute.For<MixinReference>(); var @class = Substitute.For<ClassWithTypeSymbol>(); @class.IsInterface.Returns(false); @class.Interfaces.Returns( new InterfaceList( new Interface(sourceCode.GetTypeByName(nameof(IFirstInterface))))); mixin.Class.Returns(@class); var interfaces = new InterfaceList(new[] { new Interface(sourceCode.GetTypeByName(nameof(IFirstInterface))) }); var addInterfaceWriter = new AddInterfacesToChildSyntaxWriter(mixin,sourceCode.Semantic, startPos); var newChildClass = addInterfaceWriter.Visit(childClass); return (ClassDeclarationSyntax)newChildClass; }
public static void GenerateDependency(string dependencyPath, InterfaceList interList) { string dependencyClassName = interList.FileName.ToFirstUpper() + "DependencyResolver"; string dependencyContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.Lib.Core/DependencyTemplate.txt"));//读取依赖模板 dependencyContent = dependencyContent.Replace("${CoreFolderName}", interList.FileName + "Core"); StringBuilder dependencyCore = new StringBuilder(); StringBuilder serviceDictionary = new StringBuilder(); string tempVar = ""; //变量名 interList.lstInterDis.ForEach(x => //接口列表 { tempVar = x.InterfaceName.RemoveFirstLetter().ToFirstLower(); dependencyCore.AppendLine("\t\tprivate static readonly " + x.InterfaceName + " " + tempVar + " = new " + x.InterfaceName.GetDefaultExcutor() + "();"); serviceDictionary.AppendLine("\t\t\t{typeof (" + x.InterfaceName + "), () => " + tempVar + "},"); }); dependencyCore.AppendLine("\t\tprivate static readonly IDictionary<Type, Func<object>> ServiceDictionary = new Dictionary<Type, Func<object>>//服务类型字典"); dependencyCore.AppendLine("\t\t {"); dependencyCore.Append(serviceDictionary.ToString().Substring(0, serviceDictionary.ToString().LastIndexOf(","))); dependencyCore.AppendLine("\t\t };"); dependencyContent = dependencyContent.Replace("${ClassName}", dependencyClassName); dependencyContent = dependencyContent.Replace("${CoreCode}", dependencyCore.ToString()); FileHelper.WriteFile(Path.Combine(dependencyPath, "" + dependencyClassName + ".cs"), dependencyContent); }
public static void GenerateCoreConfig(InterfaceList interList, string configPath) { string ConfigContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.Lib.Core/ConfigHelperTemplate.txt")); ConfigContent = ConfigContent.Replace("${CoreFolderName}", interList.FileName + "Core"); FileHelper.WriteFile(Path.Combine(configPath, "ConfigHelper.cs"), ConfigContent); }
public void RemoveInterface(InterfaceType interfaceType) { if (InterfaceList.Remove(interfaceType)) { Modified(); } }
///// <summary> ///// 添加通用头部 ///// </summary> ///// <param name="str"></param> //private static void AddCommonHeader(ref StringBuilder str) //{ // str.AppendLine("using System"); // str.AppendLine("using System.Collections.Generic"); // str.AppendLine("using System.Linq"); // str.AppendLine("using System.ServiceModel"); // str.AppendLine("using System.Text"); // str.AppendLine("using System.Threading.Tasks"); //} //private static void AddExtraHeader(ref StringBuilder str, InterfaceDiscription interDis = null) //{ // if (interDis != null) // { // foreach (var item in interDis.InterUsings) // { // str.AppendLine(item.UsingName); // } // } //} //#region 生成ND.WebService.Service //public static void GenerateService(InterfaceList interList) //{ // string ServiceName = "";//服务文件名 // string DirectPath = "";//保存目录 // string RequestType = "";//请求类型 // string RequestName = "";//请求名称 // string InterfaceName = "";//接口名称 // interList.lstInterDis.ToList().ForEach(x => // { // InterfaceName = x.InterfaceName.Replace("Executor", ""); // StringBuilder str = new StringBuilder(); // ServiceName = InterfaceName.Substring(1) + "Controller"; // AddCommonHeader(ref str);//添加通用头部 // AddExtraHeader(ref str, x);//添加额外的引用头部 // str.AppendLine("namespace ND.WebService.Service." + x.FileName); // str.AppendLine("{"); // str.AppendLine(" public class " + ServiceName + ":" + InterfaceName + ""); // str.AppendLine("\t{"); // x.MethodDis.ToList().ForEach(k => // { // str.AppendLine("\t\t[RuleOperationInterceptor]"); // str.Append("\t\tpublic string " + k.InterfaceMethodName + "("); // int index = 0; // k.Request.ToList().ForEach(m =>//参数 // { // if (index > 0) // { // str.Append(","); // } // str.Append(m.RequestParamType + " " + m.RequestParamName); // index++; // }); // str.AppendLine(")"); // str.AppendLine("\t\t {"); // RequestType = k.Request.Count > 0 ? k.Request[0].RequestParamType : RequestType; // RequestName = k.Request.Count > 0 ? k.Request[0].RequestParamName : RequestName; // str.AppendLine("\t\t\t" + InterfaceName + " plugin = ControllerHelper.GetCurrentPlugin<" + RequestType + "," + InterfaceName + ">(" + RequestName + ");"); // str.AppendLine("\t\t\treturn plugin." + k.InterfaceMethodName + "(" + RequestName + ");"); // str.AppendLine("\t\t }"); // }); // str.AppendLine("\t}"); // str.AppendLine("}"); // DirectPath = System.Configuration.ConfigurationManager.AppSettings["ND.Web.Service"] + x.FileName; // ApiLogHelper.Save(DirectPath, ServiceName, str.ToString()); // }); //} //#endregion //#region 生成插件层代码ND.Plugin.DefaultPlugin //public static void GeneratePlugin(InterfaceList interList) //{ // string FileName = "";//插件文件名 // string DirectPath = "";//保存目录 // string RequestType = "";//请求类型 // string RequestName = "";//请求名称 // string InterfaceName = "";//接口名称 // string enter = ",";//\r\n // interList.lstInterDis.ToList().ForEach(x => // { // InterfaceName = x.InterfaceName.Replace("Executor", ""); // StringBuilder str = new StringBuilder(); // FileName = InterfaceName.Substring(1) + "Plugin"; // AddCommonHeader(ref str);//添加通用头部 // AddExtraHeader(ref str, x);//添加额外的引用头部 // str.AppendLine("using ND.Lib.Enums.common;"); // str.AppendLine("using ND.Lib.LibHelper.log;"); // str.AppendLine("using ND.Plugin.PluginProvider;"); // str.AppendLine("using ND.Lib.LibHelper.extention;"); // str.AppendLine("using ND.Lib.Core." + x.FileName + "Core.handlers;"); // str.AppendLine("namespace ND.Plugin.DefaultPlugin." + x.FileName.ToFirstUpper()); // str.AppendLine("{"); // str.AppendLine("\tpublic class " + InterfaceName.RemoveFirstLetter() + "Plugin:" + InterfaceName + ",IPlugin"); // str.AppendLine("\t{"); // x.MethodDis.ToList().ForEach(k => // { // str.Append("\t\tpublic string " + k.InterfaceMethodName + "("); // int index = 0; // k.Request.ToList().ForEach(m =>//参数 // { // if (index > 0) // { // str.Append(","); // } // str.Append(m.RequestParamType + " " + m.RequestParamName); // index++; // }); // str.AppendLine(")"); // str.AppendLine("\t\t {"); // RequestType = k.Request.Count > 0 ? k.Request[0].RequestParamType : RequestType; // RequestName = k.Request.Count > 0 ? k.Request[0].RequestParamName : RequestName; // str.AppendLine("\t\t\t try"); // str.AppendLine("\t\t\t {"); // str.AppendLine("\t\t\t\t I" + x.FileName.ToFirstUpper() + "HandlerContext handlerContext = new " + x.FileName.ToFirstUpper() + "HandlerContext();"); // str.AppendLine("\t\t\t\t I" + x.FileName.ToFirstUpper() + "Handler handler = new " + x.FileName.ToFirstUpper() + "Handler(handlerContext);"); // str.AppendLine("\t\t\t\t " + k.Response.ResponseParamType + " baseResponse = handler." + k.InterfaceMethodName + "(" + RequestName + ");//反序列化对象"); // str.AppendLine("\t\t\t\t string result = PluginHelper<" + k.Response.ResponseParamType.SubResponse() + ", I" + k.Response.ResponseParamType.SubResponse() + ">.SelectResponsePlugin(baseResponse, " + RequestName + ".ClientType);//根据客户端类型找对应的插件返回,app或者前台或者后台"); // str.AppendLine("\t\t\t\t return result;"); // str.AppendLine("\t\t\t }"); // str.AppendLine("\t\t\t catch (Exception e)"); // str.AppendLine("\t\t\t {");//e00001 // str.AppendLine("\t\t\t LogHelper.Log(typeof(" + InterfaceName.RemoveFirstLetter() + "Plugin), e.Message " + enter + " e.StackTrace " + enter + " e.InnerException);"); // str.AppendLine("\t\t\t return JsonConvert.SerializeObject(new ResponseBase<EmptyResponse> { errCode = ErrorCode.e00001.ToString(), errMsg = ErrorCode.e00001.description(), ResponseData = null });"); // str.AppendLine("\t\t\t }"); // str.AppendLine("\t\t }"); // }); // str.AppendLine("\t}"); // str.AppendLine("}"); // DirectPath = System.Configuration.ConfigurationManager.AppSettings["ND.Plugin.DefaultPlugin"] + x.FileName; // ApiLogHelper.Save(DirectPath, FileName, str.ToString()); // }); //} //#endregion #endregion #region 生成ND.Lib.Core public static void GenerateCore(InterfaceList interList) { string DirectPath = System.Configuration.ConfigurationManager.AppSettings["ND.Lib.Core"]; List <string> lstCreateDir = new List <string>(); #region 先生成各个文件夹 //1.先生成各个文件夹 string corePath = Path.Combine(DirectPath, interList.FileName + "Core"); //核心path string dependencyInjectionPath = Path.Combine(corePath, "dependencyInjection"); //依赖path string excutorImpPath = Path.Combine(corePath, "Executor/impl"); string excutorInterPath = Path.Combine(corePath, "Executor/inter"); string hanlderPath = Path.Combine(corePath, "handlers"); string configPath = Path.Combine(corePath, "config"); lstCreateDir.Add(corePath); lstCreateDir.Add(dependencyInjectionPath); lstCreateDir.Add(excutorImpPath); lstCreateDir.Add(excutorInterPath); lstCreateDir.Add(hanlderPath); lstCreateDir.Add(configPath); lstCreateDir.ForEach(k => { DirFileHelper.CreateDirectory(k); }); #endregion NDLibCoreHelper.GenerateDependency(dependencyInjectionPath, interList); //生成依赖类 NDLibCoreHelper.GenerateHandlers(interList, hanlderPath); //生成handler类 NDLibCoreHelper.GenerateHandlerContext(interList, hanlderPath); //生成handlercontext类 NDLibCoreHelper.GenerateCoreConfig(interList, configPath); //生成配置类 NDLibCoreHelper.GenerateCoreExcutorInter(interList, excutorInterPath); //生成excutorInter类 NDLibCoreHelper.GenerateCoreExuctorImpl(interList, excutorImpPath); //生成接口实现类 }
/// <summary> /// Gets IP interfaces which are up /// </summary> private void GetInterfaces() { foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces()) { if (networkInterface.OperationalStatus == OperationalStatus.Up) { foreach (UnicastIPAddressInformation ip in networkInterface.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { InterfaceList.Add(new IPNetworkInterface { InterfaceAddress = ip.Address.ToString(), InterfaceName = networkInterface.Name }); } } } } if (InterfaceList.Count > 0) { SelectedInterface = InterfaceList[0]; } else { selectedInterface = null; } RaisePropertyChanged("SelectedInterface"); }
public static void GenerateCode(InterfaceList interList, string contractPath) { string fileName = interList.FileName; string interfaceName = ""; interList.lstInterDis.ToList().ForEach(x => { interfaceName = x.InterfaceName; StringBuilder contractCore = new StringBuilder(); contractCore.AppendLine(""); x.MethodDis.ToList().ForEach(k => { contractCore.AppendLine(""); contractCore.AppendLine("\t\t [OperationContract]"); contractCore.Append("\t\t string " + k.InterfaceMethodName + "("); int index = 0; k.Request.ToList().ForEach(m =>//参数 { if (index > 0) { contractCore.Append(","); } contractCore.Append(m.RequestParamType + " " + m.RequestParamName); index++; }); contractCore.AppendLine(");"); }); string contractContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.WebService.Contract/ContractTemplate.txt")); contractContent = contractContent.Replace("${FileName}", fileName); contractContent = contractContent.Replace("${InterfaceName}", x.InterfaceName.RemoveExcutor()).Replace("${CoreCode}", contractCore.ToString()); FileHelper.WriteFile(Path.Combine(contractPath, "" + x.InterfaceName.RemoveExcutor() + ".cs"), contractContent); }); }
private void OnInterfaceListChanged(string newName, string oldName) { //validate the interface list by remove interfaces that are not listed and duplicated entries implementedInterfaces = implementedInterfaces.Where(i => InterfaceList.Contains(i.Name)).Distinct().ToList(); //also check for error string[] s = InterfaceList.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); showInterfaceError.target = IsInterfacesExist(s, ref interfaceListError) ? 0 : 1; new Thread(() => { try { //search for suggestion based on the last listed interface name if (s.HasElement()) { string suggest = s[s.Length - 1]; interfaceSuggesstion = SearchInterfaces(suggest); forceRepaint = true; } } catch (Exception e) { Debug.Log(e.ToString()); } }).Start(); }
public void RemoveInterface(InterfaceType interfaceType) { if (InterfaceList.Remove(interfaceType)) { Changed(); } }
public void RemoveInterface(InterfaceType interfaceType) { OnBeginUndoableOperation(); if (InterfaceList.Remove(interfaceType)) { Changed(); } }
private void RefreshInterfaceList() { // Retrieve the interfaces list IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; // Scan the list printing every entry for (int i = 0; i < allDevices.Count(); i++) { InterfaceList.Add(allDevices[i]); } }
public static void GenerateHandlerContext(InterfaceList interList, string handlerContextPath) { string coreFodlerName = interList.FileName + "Core"; string handlerContextDependencyClassName = interList.FileName.ToFirstUpper() + "DependencyResolver"; string handlerContextInterfaceName = "I" + interList.FileName.ToFirstUpper() + "HandlerContext"; string handlerContextContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.Lib.Core/HandlerContextTemplate.txt")); handlerContextContent = handlerContextContent.Replace("${CoreFolderName}", coreFodlerName).Replace("${InterfaceName}", handlerContextInterfaceName); handlerContextContent = handlerContextContent.Replace("${ClassName}", handlerContextInterfaceName.RemoveFirstLetter()).Replace("${HandlerContextDependencyClassName}", handlerContextDependencyClassName); FileHelper.WriteFile(Path.Combine(handlerContextPath, "" + handlerContextInterfaceName + ".cs"), handlerContextContent); }
public void PopulateLists() { InterfaceList.Add(new DerivedIFaceA()); InterfaceList.Add(new DerivedIFaceB()); AbstractTypeList.Add(new DerivedAbstractA()); AbstractTypeList.Add(new DerivedAbstractB()); BaseTypeList.Add(new BaseType()); BaseTypeList.Add(new DerivedBaseA()); BaseTypeList.Add(new DerivedBaseB()); }
/// <summary> /// This is used to see if a type and parameter are valid template arguments /// </summary> /// <param name="type">The type to check</param> /// <param name="parameter">The parameter to check</param> /// <returns>True if it is valid, false if not</returns> private static bool IsValidTemplateArgument(TypeNode type, TypeNode parameter) { if (type == null) { throw new ArgumentNullException("type"); } // Check that the parameter really is a type parameter ITypeParameter itp = parameter as ITypeParameter; if (itp == null) { throw new ArgumentException("The 'parameter' argument is null or not an 'ITypeParameter'."); } // Test constraints bool reference = ((itp.TypeParameterFlags & TypeParameterFlags.ReferenceTypeConstraint) > 0); if (reference && type.IsValueType) { return(false); } bool value = ((itp.TypeParameterFlags & TypeParameterFlags.ValueTypeConstraint) > 0); if (value && !type.IsValueType) { return(false); } InterfaceList contracts = parameter.Interfaces; if (contracts != null) { foreach (Interface contract in contracts) { if (!type.IsAssignableTo(contract)) { return(false); } } } TypeNode parent = parameter.BaseType; if (parent != null && !type.IsAssignableTo(parent)) { return(false); } // Okay, passed all tests return(true); }
public static void GenerateCode(InterfaceList interList, string hostPath) { string fileName = interList.FileName; interList.lstInterDis.ToList().ForEach(x => { string content = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.WebService.IISHost/HostTemplate.txt")); content = content.Replace("${FileName}", fileName); content = content.Replace("${ClassName}", x.InterfaceName.RemoveExcutor().RemoveFirstLetter().ToFirstUpper() + "Controller"); FileHelper.WriteFile(Path.Combine(hostPath, "" + x.InterfaceName.RemoveExcutor().RemoveFirstLetter().ToFirstUpper() + "Service" + ".svc"), content); }); }
public static void GenerateHandlers(InterfaceList interList, string handlerPath) { string coreFodlerName = interList.FileName + "Core"; string fileName = interList.FileName; string handlerInterName = "I" + interList.FileName.ToFirstUpper() + "Handler"; string handlerClassName = interList.FileName.ToFirstUpper() + "Handler"; StringBuilder handlerInterfaceList = new StringBuilder(); StringBuilder handlerCore = new StringBuilder(); StringBuilder paramList = new StringBuilder(); interList.lstInterDis.ToList().ForEach(x => { handlerInterfaceList.Append(x.InterfaceName + ","); handlerCore.AppendLine(""); x.MethodDis.ToList().ForEach(k => { paramList.Clear(); handlerCore.AppendLine(""); handlerCore.AppendLine("\t\t #region " + k.InterfaceMethodName); handlerCore.Append("\t\t public " + k.Response.ResponseParamType + " " + k.InterfaceMethodName + "("); int index = 0; k.Request.ToList().ForEach(m =>//参数 { if (index > 0) { paramList.Append(","); handlerCore.Append(","); } handlerCore.Append(m.RequestParamType + " " + m.RequestParamName); paramList.Append(m.RequestParamName); index++; }); handlerCore.AppendLine(")"); handlerCore.AppendLine("\t\t {"); handlerCore.AppendLine("\t\t\t" + x.InterfaceName + " executor = Context.dependencyResolver.GetService<" + x.InterfaceName + ">();"); handlerCore.AppendLine("\t\t\t if(executor == null)"); handlerCore.AppendLine("\t\t\t {"); handlerCore.AppendLine("\t\t\t\t throw new NullReferenceException(\"" + handlerClassName + "." + x.InterfaceName + " is null\");"); handlerCore.AppendLine("\t\t\t }"); handlerCore.AppendLine(" \t\t\treturn executor." + k.InterfaceMethodName + "(" + paramList.ToString() + ");"); handlerCore.AppendLine("\t\t }"); handlerCore.AppendLine("\t\t #endregion "); }); }); string handlerContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.Lib.Core/HandlersTemplate.txt")); handlerContent = handlerContent.Replace("${CoreFolderName}", coreFodlerName).Replace("${FileName}", fileName); handlerContent = handlerContent.Replace("${InterfaceName}", handlerInterName).Replace("${HandlerInterfaceList}", handlerInterfaceList.ToString().Substring(0, handlerInterfaceList.Length - 1)); handlerContent = handlerContent.Replace("${ClassName}", handlerClassName).Replace("${CoreCode}", handlerCore.ToString()); FileHelper.WriteFile(Path.Combine(handlerPath, "" + handlerInterName + ".cs"), handlerContent); }
private ClassParameter ConvertToClassParameter(TypeNode typeParameter, InterfaceList interfaces, Class baseClass, ClassExpression cExpr) { ClassParameter cParam = typeParameter is MethodTypeParameter ? new MethodClassParameter() : new ClassParameter(); this.typeParamToClassParamMap[typeParameter.UniqueKey] = cParam; cParam.SourceContext = typeParameter.SourceContext; cParam.TypeParameterFlags = ((ITypeParameter)typeParameter).TypeParameterFlags; if (typeParameter.IsUnmanaged) { cParam.SetIsUnmanaged(); } cParam.Name = typeParameter.Name; cParam.Namespace = StandardIds.ClassParameter; cParam.BaseClass = baseClass == null ? SystemTypes.Object : baseClass; cParam.BaseClassExpression = cExpr; cParam.DeclaringMember = ((ITypeParameter)typeParameter).DeclaringMember; cParam.DeclaringModule = typeParameter.DeclaringModule; cParam.DeclaringType = typeParameter is MethodTypeParameter ? null : typeParameter.DeclaringType; cParam.Flags = typeParameter.Flags & ~TypeFlags.Interface; cParam.ParameterListIndex = ((ITypeParameter)typeParameter).ParameterListIndex; MemberList mems = cParam.DeclaringType == null ? null : cParam.DeclaringType.Members; int n = mems == null ? 0 : mems.Count; for (int i = 0; i < n; i++) { if ((mems[i] as TypeNode) == typeParameter) { mems[i] = cParam; break; } } if (cExpr != null) { n = interfaces.Count - 1; InterfaceList actualInterfaces = new InterfaceList(n); for (int i = 0; i < n; i++) { actualInterfaces.Add(interfaces[i + 1]); } cParam.Interfaces = actualInterfaces; } else { cParam.Interfaces = interfaces; } if (cExpr != null) { cParam.BaseClass = this.VisitClassExpression(cExpr); } return(cParam); }
public EditorDialog(Repository repository, ObjectType subType) { this.Title = Mono.Unix.Catalog.GetString("Edit Interfaces"); this.Icon = Gdk.Pixbuf.LoadFromResource("Allors.R1.Development.GtkSharp.Icons.allors.ico"); this.DefaultWidth = 600; this.DefaultHeight = 400; var form = new Form(); this.VBox.PackStart(form); var scrolledWindow = new ScrolledWindow(); this.interfaceList = new InterfaceList(repository); scrolledWindow.Add(this.interfaceList); this.interfaceList.ActiveItems = subType.DirectSuperinterfaces; var buttonCancel = new Button { CanDefault = true, UseStock = true, UseUnderline = true, Label = "gtk-cancel" }; this.AddActionWidget(buttonCancel, -6); var buttonOk = new Button { CanDefault = true, Name = "buttonOk", UseStock = true, UseUnderline = true, Label = "gtk-ok" }; buttonOk.Clicked += this.OnButtonOkClicked; this.ActionArea.PackStart(buttonOk); // Layout form.Attach(scrolledWindow, 0, 1, 0, 1, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Fill | AttachOptions.Expand, 0, 0); this.ShowAll(); this.repository = repository; this.Resize(this.DefaultWidth, this.DefaultHeight); }
public AddInterfacesToChildSyntaxWriter( MixinReference mixin, SemanticModel model, // needed to reduce type names depending on namespaces int positionOfChildClassInCode) { _mixinInterfaces = new InterfaceList(); if (mixin.Class.IsInterface) _mixinInterfaces.AddInterface(mixin.Class.AsInterface()); else foreach (var @interface in mixin.Class.Interfaces) _mixinInterfaces.AddInterface(@interface); _semantic = model; _positionOfChildClassInCode = positionOfChildClassInCode; }
public static void GenerateCoreExuctorImpl(InterfaceList interList, string excutorImplPath) { string coreFodlerName = interList.FileName + "Core"; string fileName = interList.FileName; string className = ""; string interfaceName = ""; StringBuilder excutorImplCore = new StringBuilder(); StringBuilder paramList = new StringBuilder(); interList.lstInterDis.ToList().ForEach(x =>//遍历所有接口 { className = x.InterfaceName.GetDefaultExcutor(); interfaceName = x.InterfaceName; string exuctorImplContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.Lib.Core/ExcutorImplTemplate.txt")); exuctorImplContent = exuctorImplContent.Replace("${CoreFolderName}", coreFodlerName).Replace("${FileName}", fileName); exuctorImplContent = exuctorImplContent.Replace("${ClassName}", className).Replace("${InterfaceName}", interfaceName); x.MethodDis.ToList().ForEach(k => { paramList.Clear(); excutorImplCore.AppendLine(""); excutorImplCore.AppendLine("\t\t #region " + k.InterfaceMethodName); excutorImplCore.Append("\t\t public " + k.Response.ResponseParamType + " " + k.InterfaceMethodName + "("); int index = 0; k.Request.ToList().ForEach(m =>//参数 { if (index > 0) { paramList.Append(","); excutorImplCore.Append(","); } excutorImplCore.Append(m.RequestParamType + " " + m.RequestParamName); paramList.Append(m.RequestParamName); index++; }); excutorImplCore.AppendLine(")"); excutorImplCore.AppendLine("\t\t {"); excutorImplCore.AppendLine("\t\t\t " + k.Response.ResponseParamType + " rep = new " + k.Response.ResponseParamType + "();"); excutorImplCore.AppendLine(""); excutorImplCore.AppendLine("\t\t\t //to do whatever you want;"); excutorImplCore.AppendLine(""); excutorImplCore.AppendLine("\t\t\t return rep;"); excutorImplCore.AppendLine("\t\t }"); excutorImplCore.AppendLine("\t\t #endregion "); }); exuctorImplContent = exuctorImplContent.Replace("${CoreCode}", excutorImplCore.ToString()); FileHelper.WriteFile(Path.Combine(excutorImplPath, "" + className + ".cs"), exuctorImplContent); }); }
public static void GenerateNDPlugin(InterfaceList interList) { string DirectPath = System.Configuration.ConfigurationManager.AppSettings["ND.Plugin.DefaultPlugin"]; List <string> lstCreateDir = new List <string>(); #region 先生成各个文件夹 //1.先生成各个文件夹 string corePath = Path.Combine(DirectPath, interList.FileName.ToFirstUpper() + "Plugin");//核心path lstCreateDir.Add(corePath); lstCreateDir.ForEach(k => { DirFileHelper.CreateDirectory(k); }); #endregion NDPluginHelper.GeneratePluginCode(corePath, interList); }
public static void GenerateWebServiceContract(InterfaceList interList) { string DirectPath = System.Configuration.ConfigurationManager.AppSettings["ND.WebService.Contract"]; List <string> lstCreateDir = new List <string>(); #region 先生成各个文件夹 //1.先生成各个文件夹 string corePath = Path.Combine(DirectPath, interList.FileName);//核心path lstCreateDir.Add(corePath); lstCreateDir.ForEach(k => { DirFileHelper.CreateDirectory(k); }); #endregion NDContractHelper.GenerateCode(interList, corePath); }
public static void GenerateData(InterfaceList interList, string contextPath, string responsePath, string responseInterPath, string contextValidatorPath) { string fileName = interList.FileName; interList.lstInterDis.ToList().ForEach(x => { x.MethodDis.ToList().ForEach(k => //遍历所有方法 { k.Request.ToList().ForEach(m => //遍历所有参数 { GenerateContext(m.RequestParamType, contextPath, fileName); //生成上下文对象 GenerateValidator(m.RequestParamType, contextValidatorPath, fileName); //生成验证器对象 }); GenerateResponse(k.Response.ResponseParamType, responsePath, responseInterPath, fileName); //生成响应类名和接口 }); }); }
/// <exception cref="ArgumentException"> /// The language of <paramref name="interfaceType"/> does not equal.-or- /// <paramref name="interfaceType"/> is earlier implemented interface. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="interfaceType"/> is null. /// </exception> internal virtual void AddInterface(InterfaceType interfaceType) { if (interfaceType == null) { throw new ArgumentNullException("interfaceType"); } for (int i = 0; i < InterfaceList.Count; i++) { if (InterfaceList[i] == interfaceType) { throw new ArgumentException("error_cannot_add_same_interface"); } } InterfaceList.Add(interfaceType); }
public static void GenerateCode(InterfaceList interList, string servicePath) { string fileName = interList.FileName; string coreFodlerName = interList.FileName + "Core"; string pluginType = interList.FileName.ToFirstUpper() + "Plugin"; StringBuilder serviceCore = new StringBuilder(); StringBuilder paramList = new StringBuilder(); interList.lstInterDis.ToList().ForEach(x => { serviceCore.AppendLine(""); x.MethodDis.ToList().ForEach(k => { paramList.Clear(); serviceCore.AppendLine(""); serviceCore.AppendLine("\t\t #region " + k.InterfaceMethodName); serviceCore.AppendLine("\t\t [RuleOperationInterceptor] "); serviceCore.Append("\t\t public string " + k.InterfaceMethodName.RemoveExcutor() + "("); int index = 0; k.Request.ToList().ForEach(m =>//参数 { if (index > 0) { paramList.Append(","); serviceCore.Append(","); } serviceCore.Append(m.RequestParamType + " " + m.RequestParamName); paramList.Append(m.RequestParamName); index++; }); serviceCore.AppendLine(")"); serviceCore.AppendLine("\t\t {"); string requestType = k.Request.Count <= 0 ? "null" : k.Request[0].RequestParamType; serviceCore.AppendLine("\t\t\t " + x.InterfaceName.RemoveExcutor() + " plugin = ControllerHelper.GetCurrentPlugin<" + requestType + ", " + x.InterfaceName.RemoveExcutor() + ">(" + paramList + ");"); serviceCore.AppendLine("\t\t\t return plugin." + k.InterfaceMethodName + "(" + paramList + ");"); serviceCore.AppendLine("\t\t }"); serviceCore.AppendLine("\t\t #endregion "); }); string serviceContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.WebService.Service/WebServiceController.txt")); serviceContent = serviceContent.Replace("${FileName}", fileName); serviceContent = serviceContent.Replace("${ClassName}", x.InterfaceName.RemoveExcutor().RemoveFirstLetter().ToFirstUpper() + "Controller"); serviceContent = serviceContent.Replace("${InterfaceName}", x.InterfaceName.RemoveExcutor()).Replace("${CoreCode}", serviceCore.ToString()); FileHelper.WriteFile(Path.Combine(servicePath, "" + x.InterfaceName.RemoveExcutor().RemoveFirstLetter().ToFirstUpper() + "Controller" + ".cs"), serviceContent); }); }
/// <exception cref="RelationshipException"> /// The language of <paramref name="interfaceType" /> does not equal.-or- /// <paramref name="interfaceType" /> is earlier implemented interface. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="interfaceType" /> is null. /// </exception> public virtual void AddInterface(InterfaceType interfaceType) { if (interfaceType == null) { throw new ArgumentNullException("interfaceType"); } foreach (var implementedInterface in InterfaceList) { if (interfaceType == implementedInterface) { throw new RelationshipException(Strings.ErrorCannotAddSameInterface); } } InterfaceList.Add(interfaceType); Changed(); }
public static void GenerateWebServiceHost(InterfaceList interList) { string directPath = System.Configuration.ConfigurationManager.AppSettings["ND.WebService.IISHost"]; List <string> lstCreateDir = new List <string>(); #region 先生成各个文件夹 //1.先生成各个文件夹 string autoMapperPath = Path.Combine(directPath, "autoMapperConfiguration");//核心path string configPath = Path.Combine(directPath, "configFile"); lstCreateDir.Add(autoMapperPath); lstCreateDir.Add(configPath); lstCreateDir.ForEach(k => { DirFileHelper.CreateDirectory(k); }); #endregion NDHostHelper.GenerateCode(interList, directPath); }
/// <exception cref="RelationException"> /// The language of <paramref name="interfaceType"/> does not equal.-or- /// <paramref name="interfaceType"/> is earlier implemented interface. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="interfaceType"/> is null. /// </exception> public virtual void AddInterface(InterfaceType interfaceType) { if (interfaceType == null) { throw new ArgumentNullException("interfaceType"); } foreach (InterfaceType implementedInterface in InterfaceList) { if (interfaceType == implementedInterface) { throw new RelationException( Strings.GetString("error_cannot_add_same_interface")); } } InterfaceList.Add(interfaceType); Modified(); }
public static void GenerateCoreExcutorInter(InterfaceList interList, string excutorInterPath) { //foreach (KeyValuePair<string, string> item in SrcExcutorInter) //{ // FileHelper.WriteFile(Path.Combine(ExcutorInterPath, "" + item.Key + ".cs"), item.Value); //} string coreFodlerName = interList.FileName + "Core"; string fileName = interList.FileName; string interfaceName = ""; StringBuilder paramList = new StringBuilder(); interList.lstInterDis.ToList().ForEach(x =>//遍历所有接口 { StringBuilder excutorImplCore = new StringBuilder(); interfaceName = x.InterfaceName; string exuctorImplContent = FileHelper.ReadFile(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "template/ND.Lib.Core/ExcutorInterTemplate.txt")); exuctorImplContent = exuctorImplContent.Replace("${CoreFolderName}", coreFodlerName).Replace("${FileName}", fileName); exuctorImplContent = exuctorImplContent.Replace("${InterfaceName}", interfaceName); x.MethodDis.ToList().ForEach(k => { paramList.Clear(); excutorImplCore.AppendLine(""); excutorImplCore.Append("\t\t " + k.Response.ResponseParamType + " " + k.InterfaceMethodName + "("); int index = 0; k.Request.ToList().ForEach(m =>//参数 { if (index > 0) { paramList.Append(","); excutorImplCore.Append(","); } excutorImplCore.Append(m.RequestParamType + " " + m.RequestParamName); paramList.Append(m.RequestParamName); index++; }); excutorImplCore.AppendLine(");"); }); exuctorImplContent = exuctorImplContent.Replace("${CoreCode}", excutorImplCore.ToString()); FileHelper.WriteFile(Path.Combine(excutorInterPath, "" + x.InterfaceName + ".cs"), exuctorImplContent); }); }
public static void GenerateDtoModel(InterfaceList interList) { string DirectPath = System.Configuration.ConfigurationManager.AppSettings["ND.Lib.DtoModel"]; List <string> lstCreateDir = new List <string>(); #region 先生成各个文件夹 //1.先生成各个文件夹 string corePath = Path.Combine(DirectPath, interList.FileName); //核心path string autoMappernPath = Path.Combine(corePath, "autoMapper"); //依赖path string contextPath = Path.Combine(corePath, "context"); string dtoEntityContextPath = Path.Combine(corePath, "dtoEntity/context"); string dtoEntityResponsePath = Path.Combine(corePath, "dtoEntity/response"); string responsePath = Path.Combine(corePath, "response"); string responseAppPath = Path.Combine(corePath, "response/app"); string responseBackstagePath = Path.Combine(corePath, "response/backstage"); string responseBaseClassPath = Path.Combine(corePath, "response/baseClass"); string responseFrontPath = Path.Combine(corePath, "response/front"); string responseInterPath = Path.Combine(corePath, "response/inter"); string contextValidatorPath = Path.Combine(corePath, "validator/contextValidator"); string dtoEnitityValidatorPath = Path.Combine(corePath, "validator/dtoEnitityValidator"); lstCreateDir.Add(corePath); lstCreateDir.Add(autoMappernPath); lstCreateDir.Add(contextPath); lstCreateDir.Add(dtoEntityContextPath); lstCreateDir.Add(dtoEntityResponsePath); lstCreateDir.Add(responsePath); lstCreateDir.Add(contextValidatorPath); lstCreateDir.Add(dtoEnitityValidatorPath); lstCreateDir.Add(responseAppPath); lstCreateDir.Add(responseBackstagePath); lstCreateDir.Add(responseBaseClassPath); lstCreateDir.Add(responseFrontPath); lstCreateDir.Add(responseInterPath); lstCreateDir.ForEach(k => { DirFileHelper.CreateDirectory(k); }); #endregion NDLibDtoModelHelper.GenerateData(interList, contextPath, responseBaseClassPath, responseInterPath, contextValidatorPath); }
private void RefreshInterfaceListExecute() { IPNetworkInterface prevSelectedAddress = SelectedInterface; InterfaceList.Clear(); GetInterfaces(); if (InterfaceList.Contains(prevSelectedAddress)) { SelectedInterface = prevSelectedAddress; } else if (InterfaceList.Count > 0) { SelectedInterface = InterfaceList[0]; } else { SelectedInterface = null; } RaisePropertyChanged("SelectedInterface"); }
private Interface[] GetExposedInterfaces(InterfaceList contracts) { List < Interface > exposedContracts = new List < Interface >(); for (int i = 0; i < contracts.Count; i++) { Interface contract = contracts[i]; if (this.ApiFilter.IsExposedType(contract)) { // if generic, check whether specialization types are exposed exposedContracts.Add(contract); } } return (exposedContracts.ToArray()); }
public virtual void SupportedInterfaces(TypeNode t, InterfaceList ifaceList, TypeViewer typeViewer){ if (ifaceList == null) return; TypeNode unwrappedT = this.Unwrap(t); Interface iface = unwrappedT as Interface; if (iface != null){ // possibly not needed, but seems better to keep ifaceList as a set int i = 0; while (i < ifaceList.Count){ if (ifaceList[i] == iface) break; i++; } if (i == ifaceList.Count) // not found ifaceList.Add(iface); }else{ // nop } InterfaceList ifaces = TypeViewer.GetTypeView(typeViewer, unwrappedT).Interfaces; for (int i = 0, n = ifaces == null ? 0 : ifaces.Count; i < n; i++){ this.SupportedInterfaces(ifaces[i],ifaceList,typeViewer); } return; }
/// <summary> /// Computes an upper bound in the type hierarchy for the set of argument types. /// This upper bound is a type that all types in the list are assignable to. /// If the types are all classes, then *the* least-upper-bound in the class /// hierarchy is returned. /// If the types contain at least one interface, then *a* deepest upper-bound /// is found from the intersection of the upward closure of each type. /// Note that if one of the types is System.Object, then that is immediately /// returned as the unified type without further examination of the list. /// </summary> /// <param name="ts">A list containing the set of types from which to compute the unified type.</param> /// <returns>The type corresponding to the least-upper-bound.</returns> public virtual TypeNode UnifiedType(TypeNodeList ts, TypeViewer typeViewer){ if (ts == null || ts.Count == 0) return null; TypeNode unifiedType = SystemTypes.Object; // default unified type bool atLeastOneInterface = false; #region If at least one of the types is System.Object, then that is the unified type for (int i = 0, n = ts.Count; i < n; i++){ TypeNode t = this.Unwrap(ts[i]); if (t == SystemTypes.Object){ return SystemTypes.Object; } } #endregion If at least one of the types is System.Object, then that is the unified type // assert forall{TypeNode t in ts; t != SystemTypes.Object}; #region See if any of the types are interfaces for (int i = 0, n = ts.Count; i < n; i++){ TypeNode t = this.Unwrap(ts[i]); if (t.NodeType == NodeType.Interface){ atLeastOneInterface = true; break; } } #endregion See if any of the types are interfaces #region Find the LUB in the class hierarchy (if there are no interfaces) if (!atLeastOneInterface){ TrivialHashtable h = new TrivialHashtable(ts.Count); // Create the list [s, .., t] for each element t of ts where for each item // in the list, t_i, t_i = t_{i+1}.BaseType. (s.BaseType == SystemTypes.Object) // Store the list in a hashtable keyed by t. // Do this only for classes. Handle interfaces in a different way because of // multiple inheritance. for (int i = 0, n = ts.Count; i < n; i++){ TypeNodeList tl = new TypeNodeList(); TypeNode t = this.Unwrap(ts[i]); tl.Add(t); TypeNode t2 = t.BaseType; while (t2 != null && t2 != SystemTypes.Object){ // avoid including System.Object in the list for classes tl.Insert(t2,0); t2 = this.Unwrap(t2.BaseType); } h[ts[i].UniqueKey] = tl; } bool stop = false; int depth = 0; while (!stop){ TypeNode putativeUnifiedType = null; int i = 0; int n = ts.Count; putativeUnifiedType = ((TypeNodeList) h[ts[0].UniqueKey])[depth]; while (i < n){ TypeNode t = ts[i]; TypeNodeList subTypes = (TypeNodeList) h[t.UniqueKey]; if (subTypes.Count <= depth || subTypes[depth] != putativeUnifiedType){ // either reached the top of the hierarchy for t_i or it is on a different branch // than the current one. stop = true; break; } i++; } if (i == n){ // made it all the way through: all types are subtypes of the current one unifiedType = putativeUnifiedType; } depth++; } } #endregion Find the LUB in the class hierarchy (if there are no interfaces) #region Find *a* LUB in the interface hierarchy (if there is at least one interface or current LUB is object) if (unifiedType == SystemTypes.Object || atLeastOneInterface){ TrivialHashtable interfaces = new TrivialHashtable(); for (int i = 0, n = ts.Count; i < n; i++){ InterfaceList il = new InterfaceList(); interfaces[ts[i].UniqueKey] = il; this.SupportedInterfaces(ts[i],il,typeViewer); // side-effect: il gets added to } // interfaces[ts[i]] is the upward closure of all of the interfaces supported by ts[i] // compute the intersection of all of the upward closures // might as well start with the first type in the list ts InterfaceList intersection = new InterfaceList(); InterfaceList firstIfaceList = (InterfaceList)interfaces[ts[0].UniqueKey]; for (int i = 0, n = firstIfaceList.Count; i < n; i++){ Interface iface = firstIfaceList[i]; bool found = false; int j = 1; // start at second type in the list ts while (j < ts.Count){ InterfaceList cur = (InterfaceList)interfaces[ts[j].UniqueKey]; found = false; for (int k = 0, p = cur.Count; k < p; k++){ if (cur[k] == iface){ found = true; break; } } if (!found){ // then the j-th type doesn't support iface, don't bother looking in the rest break; } j++; } if (found){ intersection.Add(iface); } } // TODO: take the "deepest" interface in the intersection. // "deepest" means that if any other type in the intersection is a subtype // of it, then *don't* consider it. if (intersection.Count > 0){ InterfaceList finalIntersection = new InterfaceList(intersection.Count); Interface iface = intersection[0]; for (int i = 0, n = intersection.Count; i < n; i++){ Interface curFace = intersection [i]; int j = 0; int m = intersection.Count; while (j < m){ if (j != i){ Interface jFace = intersection[j]; if (TypeViewer.GetTypeView(typeViewer, jFace).IsAssignableTo(curFace)) break; } j++; } if (j == m){ // made it all the way through, no other iface is a subtype of curFace finalIntersection.Add(curFace); } } if (finalIntersection.Count > 0){ unifiedType = finalIntersection[0]; // heuristic: just take the first one } } } #endregion Find *a* LUB in the interface hierarchy (if there is at least one interface or current LUB is object) return unifiedType; }
private void GetInterfaces(int i, int firstInterfaceIndex, InterfaceList/*!*/ interfaces) { InterfaceImplRow[] intfaces = this.tables.InterfaceImplTable; for (int j = firstInterfaceIndex, n = intfaces.Length; j < n; j++) { if (intfaces[j].Class != i) continue; //TODO: break if sorted TypeNode ifaceT = this.DecodeAndGetTypeDefOrRefOrSpec(intfaces[j].Interface); Interface iface = ifaceT as Interface; if (iface == null) { iface = new Interface(); if (ifaceT != null) { iface.DeclaringModule = ifaceT.DeclaringModule; iface.Namespace = ifaceT.Namespace; iface.Name = ifaceT.Name; } } interfaces.Add(iface); } }
internal TypeNode(Module declaringModule, TypeNode declaringType, AttributeList attributes, TypeFlags flags, Identifier Namespace, Identifier name, InterfaceList interfaces, MemberList members, NodeType nodeType) : base(null, attributes, name, nodeType) { this.DeclaringModule = declaringModule; this.DeclaringType = declaringType; this.Flags = flags; this.Interfaces = interfaces; this.members = members; this.Namespace = Namespace; }
private void GetGenericParameterConstraints(int index, ref TypeNode/*!*/ parameter) { Debug.Assert(parameter != null); index++; GenericParamConstraintRow[] genericParameterConstraints = this.tables.GenericParamConstraintTable; TypeNodeList constraints = new TypeNodeList(); Class baseClass = null; InterfaceList interfaces = new InterfaceList(); int i = 0, n = genericParameterConstraints.Length, j = n - 1; bool sorted = (this.sortedTablesMask >> (int)TableIndices.GenericParamConstraint) % 2 == 1; if (sorted) { while (i < j) { int k = (i + j) / 2; if (genericParameterConstraints[k].Param < index) i = k + 1; else j = k; } while (i > 0 && genericParameterConstraints[i - 1].Param == index) i--; } for (; i < n; i++) { if (genericParameterConstraints[i].Param == index) { TypeNode t = this.DecodeAndGetTypeDefOrRefOrSpec(genericParameterConstraints[i].Constraint); Class c = t as Class; if (c != null) baseClass = c; else if (t is Interface) interfaces.Add((Interface)t); constraints.Add(t); } else if (sorted) break; } ClassParameter cp = parameter as ClassParameter; if (cp == null && baseClass != null) { cp = ((ITypeParameter)parameter).DeclaringMember is Method ? new MethodClassParameter() : new ClassParameter(); cp.Name = parameter.Name; cp.DeclaringMember = ((ITypeParameter)parameter).DeclaringMember; cp.ParameterListIndex = ((ITypeParameter)parameter).ParameterListIndex; cp.DeclaringModule = this.module; cp.TypeParameterFlags = ((ITypeParameter)parameter).TypeParameterFlags; parameter = cp; } if (cp != null) cp.structuralElementTypes = constraints; else ((TypeParameter)parameter).structuralElementTypes = constraints; if (baseClass != null && cp != null) cp.BaseClass = baseClass; parameter.Interfaces = interfaces; }
public virtual void VisitResolvedInterfaceReferenceList(InterfaceList resolvedInterfaceList, InterfaceList interfaceExpressionList){ if (resolvedInterfaceList == null || interfaceExpressionList == null) return; int n = resolvedInterfaceList.Count; if (n > interfaceExpressionList.Count){Debug.Assert(false); n = interfaceExpressionList.Count;} for (int i = 0; i < n; i++){ Interface resolvedInterface = resolvedInterfaceList[i]; if (resolvedInterface == null) continue; Interface reference = interfaceExpressionList[i]; if (reference == null) continue; this.VisitResolvedTypeReference(resolvedInterface, reference); } }
public Interface(InterfaceList baseInterfaces, NestedTypeProvider provideNestedTypes, TypeAttributeProvider provideAttributes, TypeMemberProvider provideMembers, object handle) : base(NodeType.Interface, provideNestedTypes, provideAttributes, provideMembers, handle) { this.Interfaces = baseInterfaces; }
public Interface(Module declaringModule, TypeNode declaringType, AttributeList attributes, TypeFlags flags, Identifier Namespace, Identifier name, InterfaceList baseInterfaces, MemberList members) : base(declaringModule, declaringType, attributes, flags, Namespace, name, baseInterfaces, members, NodeType.Interface) { this.Flags |= TypeFlags.Interface | TypeFlags.Abstract; }
public Struct(Module declaringModule, TypeNode declaringType, AttributeList attributes, TypeFlags flags, Identifier Namespace, Identifier name, InterfaceList interfaces, MemberList members) : base(declaringModule, declaringType, attributes, flags, Namespace, name, interfaces, members, NodeType.Struct) { this.Interfaces = interfaces; this.typeCode = ElementType.ValueType; this.Flags |= TypeFlags.Sealed; }
public MethodTypeParameter(InterfaceList baseInterfaces, NestedTypeProvider provideNestedTypes, TypeAttributeProvider provideAttributes, TypeMemberProvider provideMembers, object handle) : base(baseInterfaces, provideNestedTypes, provideAttributes, provideMembers, handle) { this.NodeType = NodeType.TypeParameter; this.Flags = TypeFlags.Interface | TypeFlags.NestedPublic | TypeFlags.Abstract; this.Namespace = StandardIds.TypeParameter; }
private void WriteInterfaces(InterfaceList contracts) { Interface[] implementedContracts = GetExposedInterfaces(contracts); if (implementedContracts.Length == 0) return; writer.WriteStartElement("implements"); StartElementCallbacks("implements", implementedContracts); for (int i = 0; i < implementedContracts.Length; i++) { WriteInterface(implementedContracts[i]); } writer.WriteEndElement(); EndElementCallbacks("implements", implementedContracts); }
public virtual bool IsAllowedAsImplementedType(InterfaceList declaringTypeInterfaces, Interface implementedInterface) { if (declaringTypeInterfaces == null) return false; if (declaringTypeInterfaces.SearchFor(implementedInterface) >= 0) return true; for (int i = 0, n = declaringTypeInterfaces.Count; i < n; i++) { Interface iface = declaringTypeInterfaces[i]; if (iface != null && this.GetTypeView(iface).IsAssignableTo(implementedInterface)) return true; } return false; }
public override InterfaceList VisitInterfaceReferenceList(InterfaceList interfaceReferences) { throw new ApplicationException("unimplemented"); }
public virtual Differences VisitInterfaceReferenceList(InterfaceList list1, InterfaceList list2, out InterfaceList changes, out InterfaceList deletions, out InterfaceList insertions){ changes = list1 == null ? null : list1.Clone(); deletions = list1 == null ? null : list1.Clone(); insertions = list1 == null ? new InterfaceList() : list1.Clone(); //^ assert insertions != null; Differences differences = new Differences(); //Compare definitions that have matching key attributes TrivialHashtable matchingPosFor = new TrivialHashtable(); TrivialHashtable matchedNodes = new TrivialHashtable(); for (int j = 0, n = list2 == null ? 0 : list2.Count; j < n; j++){ //^ assert list2 != null; Interface nd2 = list2[j]; if (nd2 == null || nd2.Name == null) continue; matchingPosFor[nd2.Name.UniqueIdKey] = j; insertions.Add(null); } for (int i = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){ //^ assert list1 != null && changes != null && deletions != null; Interface nd1 = list1[i]; if (nd1 == null || nd1.Name == null) continue; object pos = matchingPosFor[nd1.Name.UniqueIdKey]; if (!(pos is int)) continue; //^ assert pos != null; //^ assume list2 != null; //since there was entry int matchingPosFor int j = (int)pos; Interface nd2 = list2[j]; //nd1 and nd2 have the same key attributes and are therefore treated as the same entity matchedNodes[nd1.UniqueKey] = nd1; //^ assume nd2 != null; matchedNodes[nd2.UniqueKey] = nd2; //nd1 and nd2 may still be different, though, so find out how different Differences diff = this.VisitInterface(nd1, nd2); if (diff == null){Debug.Assert(false); continue;} if (diff.NumberOfDifferences != 0){ changes[i] = diff.Changes as Interface; deletions[i] = diff.Deletions as Interface; insertions[i] = diff.Insertions as Interface; insertions[n+j] = nd1; //Records the position of nd2 in list2 in case the change involved a permutation //Debug.Assert(diff.Changes == changes[i] && diff.Deletions == deletions[i] && diff.Insertions == insertions[i]); differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; continue; } changes[i] = null; deletions[i] = null; insertions[i] = null; insertions[n+j] = nd1; //Records the position of nd2 in list2 in case the change involved a permutation } //Find deletions for (int i = 0, n = list1 == null ? 0 : list1.Count; i < n; i++){ //^ assert list1 != null && changes != null && deletions != null; Interface nd1 = list1[i]; if (nd1 == null) continue; if (matchedNodes[nd1.UniqueKey] != null) continue; changes[i] = null; deletions[i] = nd1; insertions[i] = null; differences.NumberOfDifferences += 1; } //Find insertions for (int j = 0, n = list1 == null ? 0 : list1.Count, m = list2 == null ? 0 : list2.Count; j < m; j++){ //^ assert list2 != null; Interface nd2 = list2[j]; if (nd2 == null) continue; if (matchedNodes[nd2.UniqueKey] != null) continue; insertions[n+j] = nd2; //Records nd2 as an insertion into list1, along with its position in list2 differences.NumberOfDifferences += 1; //REVIEW: put the size of the tree here? } if (differences.NumberOfDifferences == 0){ changes = null; deletions = null; insertions = null; } return differences; }
private TypeNode/*!*/ ConstructCorrectTypeNodeSubclass(int i, Identifier/*!*/ namesp, int firstInterfaceIndex, int lastInterfaceIndex, TypeFlags flags, InterfaceList interfaces, int baseTypeCodedIndex, bool isSystemEnum) { TypeNode result; TypeNode.TypeAttributeProvider attributeProvider = new TypeNode.TypeAttributeProvider(this.GetTypeAttributes); TypeNode.NestedTypeProvider nestedTypeProvider = new TypeNode.NestedTypeProvider(this.GetNestedTypes); TypeNode.TypeMemberProvider memberProvider = new TypeNode.TypeMemberProvider(this.GetTypeMembers); bool isTemplateParameter = false; if ((flags & TypeFlags.Interface) != 0) { if (isTemplateParameter) result = new TypeParameter(interfaces, nestedTypeProvider, attributeProvider, memberProvider, i); else result = new Interface(interfaces, nestedTypeProvider, attributeProvider, memberProvider, i); } else if (isTemplateParameter) { result = new ClassParameter(nestedTypeProvider, attributeProvider, memberProvider, i); } else { result = null; TypeNode baseClass = this.GetTypeIfNotGenericInstance(baseTypeCodedIndex); if (baseClass != null) { if (baseClass == CoreSystemTypes.MulticastDelegate) //TODO: handle single cast delegates result = new DelegateNode(nestedTypeProvider, attributeProvider, memberProvider, i); else if (baseClass == CoreSystemTypes.Enum) result = new EnumNode(nestedTypeProvider, attributeProvider, memberProvider, i); else if (baseClass == CoreSystemTypes.ValueType && !(isSystemEnum && (flags & TypeFlags.Sealed) == 0)) { result = new Struct(nestedTypeProvider, attributeProvider, memberProvider, i); } } if(result == null) result = new Class(nestedTypeProvider, attributeProvider, memberProvider, i); } result.Flags = flags; result.Interfaces = interfaces; return result; }
public virtual InterfaceList VisitInterfaceReferenceList(InterfaceList interfaces, InterfaceList changes, InterfaceList deletions, InterfaceList insertions){ if (interfaces == null) return changes; if (changes != null){ if (deletions == null || insertions == null) Debug.Assert(false); else{ } }else if (deletions != null) return null; return interfaces; }
public Interface(InterfaceList baseInterfaces) : base(NodeType.Interface) { this.Interfaces = baseInterfaces; this.Flags = TypeFlags.Interface | TypeFlags.Abstract; }
private InterfaceList ParseInterfaceList(TokenSet followers, bool expectLeftBrace){ InterfaceList ilist = new InterfaceList(); TokenSet followersOrComma = followers|Token.Comma; for(;;){ Expression id = this.scanner.GetIdentifier(); switch(this.currentToken){ case Token.Bool: case Token.Decimal: case Token.Sbyte: case Token.Byte: case Token.Short: case Token.Ushort: case Token.Int: case Token.Uint: case Token.Long: case Token.Ulong: case Token.Char: case Token.Float: case Token.Double: case Token.Object: case Token.String: case Token.Void: TypeExpression texpr = this.TypeExpressionFor(this.currentToken); this.GetNextToken(); ilist.Add(new InterfaceExpression(texpr.Expression, texpr.SourceContext)); goto lookForComma; default: bool idOK = Parser.IdentifierOrNonReservedKeyword[this.currentToken]; if (idOK){ this.GetNextToken(); if (this.currentToken == Token.DoubleColon){ this.GetNextToken(); Identifier id2 = this.scanner.GetIdentifier(); id2.Prefix = (Identifier)id; id2.SourceContext.StartPos = id.SourceContext.StartPos; this.SkipIdentifierOrNonReservedKeyword(); id = id2; } if (this.currentToken == Token.Dot) id = this.ParseQualifiedIdentifier(id, followersOrComma|Token.LessThan); }else{ int col = this.scanner.endPos; this.SkipIdentifierOrNonReservedKeyword(Error.TypeExpected); if (col == this.scanner.endPos && this.currentToken != Token.EndOfFile){ //Did not consume a token, but just gave an error if (!followersOrComma[this.currentToken]) this.GetNextToken(); if (followers[this.currentToken]) return ilist; if (this.currentToken != Token.Comma){ if (Parser.IdentifierOrNonReservedKeyword[this.currentToken]) continue; break; } this.GetNextToken(); continue; } if (this.currentToken == Token.Dot) id = this.ParseQualifiedIdentifier(id, followersOrComma|Token.LessThan); if (!idOK) goto lookForComma; } break; } //I really want an Identifier here for StartName if (this.sink != null) { Identifier name = id as Identifier; if (id is QualifiedIdentifier) { name = ((QualifiedIdentifier)id).Identifier; } if (name != null) { this.sink.StartName(name); } } InterfaceExpression ifaceExpr = new InterfaceExpression(id, id.SourceContext); if (this.currentToken == Token.LessThan){ yetAnotherTypeArgumentList: this.GetNextToken(); TypeNodeList arguments = new TypeNodeList(); for(;;){ TypeNode t = this.ParseTypeExpression(null, followers|Token.Comma|Token.GreaterThan); arguments.Add(t); if (this.currentToken != Token.Comma) break; this.GetNextToken(); } ifaceExpr.TemplateArguments = arguments; ifaceExpr.TemplateArgumentExpressions = arguments.Clone(); ifaceExpr.SourceContext.EndPos = this.scanner.endPos; this.Skip(Token.GreaterThan); if (this.currentToken == Token.Dot) { TemplateInstance tempInst = new TemplateInstance(ifaceExpr.Expression, ifaceExpr.TemplateArguments); tempInst.TypeArgumentExpressions = ifaceExpr.TemplateArguments == null ? null : ifaceExpr.TemplateArguments.Clone(); tempInst.SourceContext = ifaceExpr.SourceContext; ifaceExpr.Expression = this.ParseQualifiedIdentifier(tempInst, followersOrComma|Token.LessThan); ifaceExpr.TemplateArguments = null; ifaceExpr.TemplateArgumentExpressions = null; if (ifaceExpr.Expression != null) ifaceExpr.SourceContext = ifaceExpr.Expression.SourceContext; if (this.currentToken == Token.LessThan) goto yetAnotherTypeArgumentList; } } ilist.Add(ifaceExpr); lookForComma: if (Parser.TypeOperator[this.currentToken] && !(expectLeftBrace && this.currentToken == Token.LeftBrace)){ this.HandleError(Error.BadBaseType); this.GetNextToken(); if (this.currentToken == Token.RightBracket || this.currentToken == Token.RightBrace) this.GetNextToken(); this.SkipTo(followersOrComma, Error.None); }else if (!followersOrComma[this.currentToken]) this.SkipTo(followersOrComma, Error.TypeExpected); if (this.currentToken == Token.Comma){ if (followers[Token.Comma] && followers[Token.GreaterThan]) break; //Parsing the constraint of a type parameter this.GetNextToken(); if (expectLeftBrace && (this.currentToken == Token.Class || this.currentToken == Token.Struct || this.currentToken == Token.New)) break; }else if (!Parser.TypeStart[this.currentToken] || this.currentToken == Token.Where) break; else if (Parser.ContractStart[this.currentToken]) break; } return ilist; }
public Class(Module declaringModule, TypeNode declaringType, AttributeList attributes, TypeFlags flags, Identifier Namespace, Identifier name, Class baseClass, InterfaceList interfaces, MemberList members) : base(declaringModule, declaringType, attributes, flags, Namespace, name, interfaces, members, NodeType.Class) { this.baseClass = baseClass; }
public override InterfaceList VisitInterfaceReferenceList(InterfaceList interfaceReferences) { if(interfaceReferences == null) return null; return base.VisitInterfaceReferenceList(new InterfaceList(interfaceReferences)); }
public virtual InterfaceList VisitInterfaceReferenceList(InterfaceList interfaceReferences) { if (interfaceReferences == null) return null; for (int i = 0, n = interfaceReferences.Count; i < n; i++) interfaceReferences[i] = this.VisitInterfaceReference(interfaceReferences[i]); return interfaceReferences; }
public virtual InterfaceList VisitInterfaceReferenceList(InterfaceList interfaceReferences1, InterfaceList interfaceReferences2) { if (interfaceReferences1 == null) return null; for (int i = 0, n = interfaceReferences1.Count, m = interfaceReferences2 == null ? 0 : interfaceReferences2.Count; i < n; i++) { //^ assert interfaceReferences2 != null; if (i >= m) interfaceReferences1[i] = this.VisitInterfaceReference(interfaceReferences1[i], null); else interfaceReferences1[i] = this.VisitInterfaceReference(interfaceReferences1[i], interfaceReferences2[i]); } return interfaceReferences1; }
private ClassParameter ConvertToClassParameter(TypeNode typeParameter, InterfaceList interfaces, Class baseClass, ClassExpression cExpr){ ClassParameter cParam = typeParameter is MethodTypeParameter ? new MethodClassParameter() : new ClassParameter(); this.typeParamToClassParamMap[typeParameter.UniqueKey] = cParam; cParam.SourceContext = typeParameter.SourceContext; cParam.TypeParameterFlags = ((ITypeParameter)typeParameter).TypeParameterFlags; if (typeParameter.IsUnmanaged) { cParam.SetIsUnmanaged(); } cParam.Name = typeParameter.Name; cParam.Namespace = StandardIds.ClassParameter; cParam.BaseClass = baseClass == null ? SystemTypes.Object : baseClass; cParam.BaseClassExpression = cExpr; cParam.DeclaringMember = ((ITypeParameter)typeParameter).DeclaringMember; cParam.DeclaringModule = typeParameter.DeclaringModule; cParam.DeclaringType = typeParameter is MethodTypeParameter ? null : typeParameter.DeclaringType; cParam.Flags = typeParameter.Flags & ~TypeFlags.Interface; cParam.ParameterListIndex = ((ITypeParameter)typeParameter).ParameterListIndex; MemberList mems = cParam.DeclaringType == null ? null : cParam.DeclaringType.Members; int n = mems == null ? 0 : mems.Count; for (int i = 0; i < n; i++){ if ((mems[i] as TypeNode) == typeParameter){ mems[i] = cParam; break; } } if (cExpr != null){ n = interfaces.Count - 1; InterfaceList actualInterfaces = new InterfaceList(n); for (int i = 0; i < n; i++) actualInterfaces.Add(interfaces[i + 1]); cParam.Interfaces = actualInterfaces; }else cParam.Interfaces = interfaces; if (cExpr != null) cParam.BaseClass = this.VisitClassExpression(cExpr); return cParam; }
public virtual void VisitBaseClassReference(Class Class){ if (Class == null) return; if (Class.Name.UniqueIdKey == StandardIds.CapitalObject.UniqueIdKey && Class.Namespace.UniqueIdKey == StandardIds.System.UniqueIdKey) { Class.BaseClass = null; Class.BaseClassExpression = null; return; } if (Class.PartiallyDefines is Class && ((Class)Class.PartiallyDefines).BaseClass == null) this.VisitBaseClassReference((Class)Class.PartiallyDefines); TypeNodeList partialTypes = Class.IsDefinedBy; if (partialTypes != null){ for (int i = 0, n = partialTypes == null ? 0 : partialTypes.Count; i < n; i++){ Class partialClass = partialTypes[i] as Class; if (partialClass == null || partialClass.BaseClass == SystemTypes.Object) continue; partialClass.PartiallyDefines = null; //Stop recursion this.VisitBaseClassReference(partialClass); partialClass.PartiallyDefines = Class; if (partialClass.BaseClass == SystemTypes.Object) continue; Class.BaseClass = partialClass.BaseClass; return; } } //Visit Class.BaseClass, but guard against doing it twice //(this routine can get called when visiting a derived class that occurs lexically before Class) if (Class.BaseClassExpression == Class) return; //Still resolving the base class. This is a recursive call due to a recursive type argument. if (Class.BaseClass != null) { ClassExpression cExpr = Class.BaseClass as ClassExpression; if (cExpr == null) return; //Been here before and found a base class this.VisitBaseClassReference(Class, true); return; } //Leaving the BaseClass null is the convention for asking that the first expression in the interface list be treated as the base class, if possible. //If not possible, the convention is to set BaseClass equal to SystemTypes.Object. InterfaceList interfaces = Class.Interfaces; InterfaceList interfaceExpressions = Class.InterfaceExpressions; if (interfaces != null && interfaces.Count > 0){ Interface iface = interfaces[0]; InterfaceExpression ifExpr = iface as InterfaceExpression; if (ifExpr != null){ ClassExpression cExpr = new ClassExpression(ifExpr.Expression, ifExpr.TemplateArguments, ifExpr.SourceContext); Class.BaseClass = Class.BaseClassExpression = cExpr; if (this.VisitBaseClassReference(Class, false)){ //The first expression is not meant as an interface, remove it from the list int n = interfaces.Count-1; InterfaceList actualInterfaces = new InterfaceList(n); InterfaceList actualInterfaceExpressions = new InterfaceList(n); for (int i = 0; i < n; i++) { actualInterfaces.Add(interfaces[i+1]); if (interfaceExpressions != null) actualInterfaceExpressions.Add(interfaceExpressions[i+1]); } Class.Interfaces = actualInterfaces; if (interfaceExpressions != null) Class.InterfaceExpressions = actualInterfaceExpressions; }else{ Class.BaseClass = SystemTypes.Object; Class.BaseClassExpression = null; } }else{ Class.BaseClass = SystemTypes.Object; Class.BaseClassExpression = null; } }else{ Class.BaseClass = SystemTypes.Object; Class.BaseClassExpression = null; } if (Class.BaseClass != null && Class.BaseClass != SystemTypes.Object) { this.VisitBaseClassReference(Class.BaseClass.Template as Class); this.VisitBaseClassReference(Class.BaseClass); } }
private static bool InterfaceListContains(InterfaceList interfaceList, TypeNode intf) { if (interfaceList == null) return false; for (int i = 0; i < interfaceList.Count; i++) { if (interfaceList[i] == intf) return true; } return false; }
internal TypeNode/*!*/ GetTypeFromDefHelper(int i) { // This is added to prevent loops. // Check the code in GetTypeFromDef which checks != null before calling this function this.tables.TypeDefTable[i - 1].Type = Class.Dummy; TypeDefRow typeDef = this.tables.TypeDefTable[i - 1]; Identifier name = this.tables.GetIdentifier(typeDef.Name); Identifier namesp = this.tables.GetIdentifier(typeDef.Namespace); int firstInterfaceIndex; int lastInterfaceIndex; this.GetInterfaceIndices(i, out firstInterfaceIndex, out lastInterfaceIndex); InterfaceList interfaces = new InterfaceList(); TypeNode result = this.ConstructCorrectTypeNodeSubclass(i, namesp, firstInterfaceIndex, lastInterfaceIndex, (TypeFlags)typeDef.Flags, interfaces, typeDef.Extends, name.UniqueIdKey == StandardIds.Enum.UniqueIdKey && namesp.UniqueIdKey == StandardIds.System.UniqueIdKey); result.DeclaringModule = this.module; result.Name = name; result.Namespace = namesp; TypeNodeList typeParameters = this.currentTypeParameters = this.GetTypeParametersFor((i << 1) | 0, result); result.TemplateParameters = typeParameters; result.IsGeneric = typeParameters != null; this.tables.TypeDefTable[i - 1].Type = result; this.currentType = result; this.RemoveTypeParametersBelongToDeclaringType(i, ref typeParameters, result); //Now that the type instance has been allocated, it is safe to get hold of things that could refer to this type. if (result is Class && result.BaseType == null) { TypeNode baseType = this.DecodeAndGetTypeDefOrRefOrSpec(typeDef.Extends); ((Class)result).BaseClass = baseType as Class; if (baseType != null && !(baseType is Class) && this.module != null) { HandleError(this.module, ExceptionStrings.InvalidBaseClass); } } if (result.IsGeneric) this.GetTypeParameterConstraints((i << 1) | 0, typeParameters); if (firstInterfaceIndex >= 0) this.GetInterfaces(i, firstInterfaceIndex, interfaces); if ((result.Flags & (TypeFlags.ExplicitLayout | TypeFlags.SequentialLayout)) != 0) this.GetClassSizeAndPackingSize(i, result); return result; }