private IFunctionNode find_constructor(ICommonTypeNode tn) { foreach (ICommonMethodNode cmn in tn.methods) { if (cmn.is_constructor) { return(cmn); } } return(null); }
private IFunctionNode find_constructor_with_params(ICommonTypeNode tn) { foreach (ICommonMethodNode cmn in tn.methods) { if (cmn.is_constructor && cmn.parameters.Length == 2) { return(cmn); } } return(null); }
private IFunctionNode find_method(ICommonTypeNode tn, string name) { foreach (ICommonMethodNode cmn in tn.methods) { if (string.Compare(cmn.name, name, true) == 0) { return(cmn); } } return(null); }
public List <ICommonMethodNode> GetOverloadedConstructors(ICommonTypeNode t) { List <ICommonMethodNode> lst = new List <ICommonMethodNode>(); foreach (ICommonMethodNode m in t.methods) { if (m.is_constructor) { lst.Add(m); } } return(lst); }
public ICommonClassFieldNode[] GetDefinedFields(ICommonTypeNode ctn) { List <ICommonClassFieldNode> lst = new List <ICommonClassFieldNode>(); foreach (ICommonClassFieldNode fld in ctn.fields) { if (!fld.name.Contains("$")) { lst.Add(fld); } } return(lst.ToArray()); }
public ITypeNode[] GetChildClasses(ICommonTypeNode ctn) { List <ITypeNode> lst = new List <ITypeNode>(); foreach (ITypeNode t in main_ns.types) { if (t.base_type == ctn) { lst.Add(t); } } return(lst.ToArray()); }
public IClassConstantDefinitionNode[] GetConstants(ICommonTypeNode ctn, string name) { List <IClassConstantDefinitionNode> lst = new List <IClassConstantDefinitionNode>(); foreach (IClassConstantDefinitionNode p in ctn.constants) { if (string.Compare(p.name, name, true) == 0) { lst.Add(p); } } return(lst.ToArray()); }
public ICommonMethodNode[] GetMethods(ICommonTypeNode t, string name) { List <ICommonMethodNode> lst = new List <ICommonMethodNode>(); foreach (ICommonMethodNode m in t.methods) { if (string.Compare(m.name, name, true) == 0) { lst.Add(m); } } return(lst.ToArray()); }
public ICommonMethodNode[] GetConstructors(ICommonTypeNode ctn) { List <ICommonMethodNode> lst = new List <ICommonMethodNode>(); foreach (ICommonMethodNode m in ctn.methods) { if (m.is_constructor && m.field_access_level != field_access_level.fal_private && m.polymorphic_state != polymorphic_state.ps_static && HelpUtils.can_write(m)) { lst.Add(m); } } return(lst.ToArray()); }
public ICommonPropertyNode[] GetProperties(ICommonTypeNode ctn) { List <ICommonPropertyNode> lst = new List <ICommonPropertyNode>(); while (ctn != null) { foreach (ICommonPropertyNode p in ctn.properties) { lst.Add(p); } ctn = ctn.base_type as ICommonTypeNode; } lst.Sort(new PropertyComparer()); return(lst.ToArray()); }
public bool is_overload(ICommonMethodNode meth, ICommonTypeNode ctn) { int count = 1; while (ctn != null) { foreach (ICommonMethodNode m in ctn.methods) { if (string.Compare(meth.name, m.name, true) == 0 && meth != m && meth.overrided_method != m) { count++; } } ctn = ctn.base_type as ICommonTypeNode; } return(count > 1); }
public List <ICommonMethodNode> GetOverloadsList(ICommonTypeNode t, ICommonMethodNode meth) { List <ICommonMethodNode> lst = new List <ICommonMethodNode>(); while (t != null) { foreach (ICommonMethodNode m in t.methods) { if (string.Compare(m.name, meth.name, true) == 0 && meth.overrided_method != m) { lst.Add(m); } } t = t.base_type as ICommonTypeNode; } return(lst); }
public ICommonPropertyNode[] GetNonPrivateProperties(ICommonTypeNode ctn) { List <ICommonPropertyNode> lst = new List <ICommonPropertyNode>(); while (ctn != null) { foreach (ICommonPropertyNode p in ctn.properties) { if (p.field_access_level != field_access_level.fal_private && HelpUtils.can_write(p)) { lst.Add(p); } } ctn = ctn.base_type as ICommonTypeNode; } lst.Sort(new PropertyComparer()); return(lst.ToArray()); }
public IClassConstantDefinitionNode[] GetNonPrivateClassConstants(ICommonTypeNode ctn) { List <IClassConstantDefinitionNode> lst = new List <IClassConstantDefinitionNode>(); while (ctn != null) { foreach (IClassConstantDefinitionNode p in ctn.constants) { if (p.field_access_level != field_access_level.fal_private && HelpUtils.can_write(p)) { lst.Add(p); } } ctn = ctn.base_type as ICommonTypeNode; } lst.Sort(new ConstantComparer()); return(lst.ToArray()); }
public ICommonClassFieldNode[] GetFields(ICommonTypeNode ctn, field_access_level fal) { List <ICommonClassFieldNode> lst = new List <ICommonClassFieldNode>(); while (ctn != null) { foreach (ICommonClassFieldNode p in ctn.fields) { if (p.field_access_level == fal && HelpUtils.can_write(p)) { lst.Add(p); } } ctn = ctn.base_type as ICommonTypeNode; } lst.Sort(new FieldComparer()); return(lst.ToArray()); }
public ICommonMethodNode[] GetMethods(ICommonTypeNode ctn, field_access_level fal) { List <ICommonMethodNode> lst = new List <ICommonMethodNode>(); ICommonPropertyNode[] props = GetProperties(ctn); while (ctn != null) { foreach (ICommonMethodNode m in ctn.methods) { if (!m.is_constructor && m.field_access_level == fal && m.Location != null && !is_getter_or_setter(m, props) && !is_event_special_method(m) && HelpUtils.can_write(m)) { lst.Add(m); } } ctn = ctn.base_type as ICommonTypeNode; } lst.Sort(new MethodComparer()); return(lst.ToArray()); }
private string getFieldValueFromSemanticNodeAccessModifierType(object _node) { // структуру в абстр. класс для хранения соотв. значений в Сишарпе (и других языках) string fieldValue = ""; if (_node is ICommonTypeNode) { ICommonTypeNode node = _node as ICommonTypeNode; if ((node).type_access_level == type_access_level.tal_internal) { return("internal" + Indents.BetweenWords); } if ((node).type_access_level == type_access_level.tal_public) { return("public" + Indents.BetweenWords); } } return(""); }
public int GetMethodIndex(ICommonMethodNode cmn, ICommonTypeNode ctn) { int i = 1; while (ctn != null) { ICommonMethodNode[] meths = ctn.methods; foreach (ICommonMethodNode m in meths) { if (m == cmn) { return(i); } else if (string.Compare(m.name, cmn.name, true) == 0 && cmn.overrided_method != m) { i++; } } ctn = ctn.base_type as ICommonTypeNode; } return(1); }
private IFunctionNode find_constructor_with_one_param(ICommonTypeNode tn) { foreach (ICommonMethodNode cmn in tn.methods) { if (cmn.is_constructor && cmn.parameters.Length == 1) return cmn; } return null; }
private IFunctionNode find_method(ICommonTypeNode tn, string name) { foreach (ICommonMethodNode cmn in tn.methods) { if (string.Compare(cmn.name,name,true) == 0) return cmn; } return null; }
//(ssyy) Инициализации полей типа параметр дженерика private void CreateRuntimeInitCodeWithCheck(ILGenerator il, FieldBuilder fb, ICommonTypeNode type) { if (type.runtime_initialization_marker == null) return; Type tinfo = helper.GetTypeReference(type).tp; FieldInfo finfo = helper.GetField(type.runtime_initialization_marker).fi; Label lab = il.DefineLabel(); il.Emit(OpCodes.Ldsfld, finfo); il.Emit(OpCodes.Brfalse, lab); if (!fb.IsStatic) { il.Emit(OpCodes.Ldarg_0); } il.Emit(OpCodes.Ldsfld, finfo); if (fb.IsStatic) { il.Emit(OpCodes.Ldsfld, fb); } else { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, fb); } il.Emit(OpCodes.Box, tinfo); MethodInfo rif = null; if (SystemLibrary.SystemLibInitializer.RuntimeInitializeFunction.sym_info is ICompiledMethodNode) rif = (SystemLibrary.SystemLibInitializer.RuntimeInitializeFunction.sym_info as ICompiledMethodNode).method_info; else rif = helper.GetMethod(SystemLibrary.SystemLibInitializer.RuntimeInitializeFunction.sym_info as IFunctionNode).mi; il.EmitCall(OpCodes.Call, rif, null); il.Emit(OpCodes.Unbox_Any, tinfo); if (fb.IsStatic) { il.Emit(OpCodes.Stsfld, fb); } else { il.Emit(OpCodes.Stfld, fb); } il.MarkLabel(lab); }
//Перевод заголовка типа private void ConvertTypeHeader(ICommonTypeNode value) { //(ssyy) Обрабатываем инстанции generic-типов //FillGetterMethodsTable(value); IGenericTypeInstance igtn = value as IGenericTypeInstance; if (igtn != null) { //Формируем список типов-параметров List<Type> iparams = new List<Type>(); foreach (ITypeNode itn in igtn.generic_parameters) { TypeInfo tinfo = helper.GetTypeReference(itn); if (tinfo == null) { AddTypeInstanceToFunction(GetGenericFunctionContainer(value), igtn); return; } iparams.Add(tinfo.tp); } //Запрашиваем инстанцию //ICompiledTypeNode icompiled_type = igtn.original_generic as ICompiledTypeNode; Type orig_type = helper.GetTypeReference(igtn.original_generic).tp; Type rez = orig_type.MakeGenericType(iparams.ToArray()); //Добавляем в хэш TypeInfo inst_ti = helper.AddExistingType(igtn, rez); TypeInfo generic_def_ti = helper.GetTypeReference(igtn.original_generic); if (generic_def_ti.init_meth != null) inst_ti.init_meth = TypeBuilder.GetMethod(rez, generic_def_ti.init_meth); if (generic_def_ti.clone_meth != null) inst_ti.clone_meth = TypeBuilder.GetMethod(rez, generic_def_ti.clone_meth); if (generic_def_ti.assign_meth != null) inst_ti.assign_meth = TypeBuilder.GetMethod(rez, generic_def_ti.assign_meth); return; } if (comp_opt.target == TargetType.Dll) AddPropertyAccessors(value); Type[] interfaces = new Type[value.ImplementingInterfaces.Count]; for (int i = 0; i < interfaces.Length; i++) { TypeInfo ii_ti = helper.GetTypeReference(value.ImplementingInterfaces[i]); interfaces[i] = ii_ti.tp; } //определяем тип TypeInfo ti = helper.GetTypeReference(value); bool not_exist = ti == null; TypeBuilder tb = null; GenericTypeParameterBuilder gtpb = null; if (!not_exist) { tb = ti.tp as TypeBuilder; gtpb = ti.tp as GenericTypeParameterBuilder; } TypeAttributes ta = (not_exist) ? ConvertAttributes(value) : TypeAttributes.NotPublic; if (value.base_type is ICompiledTypeNode && (value.base_type as ICompiledTypeNode).compiled_type == TypeFactory.EnumType) { ta = TypeAttributes.Public; if (value.type_access_level == type_access_level.tal_internal) ta = TypeAttributes.NotPublic; EnumBuilder emb = mb.DefineEnum(cur_unit + "." + value.name, ta, TypeFactory.Int32Type); //int num = 0; foreach (IClassConstantDefinitionNode ccfn in value.constants) { emb.DefineLiteral(ccfn.name, (ccfn.constant_value as IEnumConstNode).constant_value); } AddEnumToCloseList(emb); helper.AddEnum(value, emb); return; } else { if (not_exist) { tb = mb.DefineType(cur_unit + "." + value.name, ta, null, interfaces); } else { if (gtpb == null) { foreach (Type interf in interfaces) { tb.AddInterfaceImplementation(interf); } } else { gtpb.SetInterfaceConstraints(interfaces); GenericParameterAttributes gpa = GenericParameterAttributes.None; if (value.is_value_type) gpa |= GenericParameterAttributes.NotNullableValueTypeConstraint; if (value.is_class) gpa |= GenericParameterAttributes.ReferenceTypeConstraint; if (value.methods.Length > 0) gpa |= GenericParameterAttributes.DefaultConstructorConstraint; gtpb.SetGenericParameterAttributes(gpa); } } } //добавлям его во внутр. структуры if (not_exist) { ti = helper.AddType(value, tb); } //if (value.fields.Length == 1 && value.fields[0].type is ISimpleArrayNode) if (value.type_special_kind == type_special_kind.array_wrapper) { ti.is_arr = true; } if (value.base_type != null && !value.IsInterface) { Type base_type = helper.GetTypeReference(value.base_type).tp; if (gtpb == null) { tb.SetParent(base_type); } else { if (base_type != TypeFactory.ObjectType) gtpb.SetBaseTypeConstraint(base_type); } } if (!value.is_generic_parameter) { AddTypeToCloseList(tb);//добавляем его в список закрытия if (!value.IsInterface && value.type_special_kind != type_special_kind.array_wrapper) AddInitMembers(ti, tb, value); } //если это обертка над массивом, сразу переводим реализацию //if (value.fields.Length == 1 && value.fields[0].type is ISimpleArrayNode) ConvertArrayWrapperType(value); }
//Переводит аттрибуты типа в аттрибуты .NET private TypeAttributes ConvertAttributes(ICommonTypeNode value) { TypeAttributes ta = TypeAttributes.Public; if (value.type_access_level == type_access_level.tal_internal) ta = TypeAttributes.NotPublic; //(ssyy) 27.10.2007 Прекратить бардак! Я в третий раз устанавливаю здесь аттрибут Sealed! //Это надо, чтобы нельзя было наследовать от записей. //В следующий раз разработчику, снявшему аттрибут Sealed, указать причину, по которой это было сделано! if (value.is_value_type) ta |= TypeAttributes.SequentialLayout | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed; //TypeAttributes.Sealed нужно! if (value.IsSealed) ta |= TypeAttributes.Sealed; ICompiledTypeNode ictn = value.base_type as ICompiledTypeNode; if (ictn != null) { if (ictn.compiled_type == TypeFactory.MulticastDelegateType) { ta |= TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Sealed; } } if (value.IsInterface) { ta |= TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.AnsiClass; //if (has_com_import_attr(value)) // ta |= TypeAttributes.Import; } if (value.IsAbstract) { ta |= TypeAttributes.Abstract; } return ta; }
private void AddInitMembers(TypeInfo ti, TypeBuilder tb, ICommonTypeNode ctn) { MethodBuilder init_mb = tb.DefineMethod("$Init$", MethodAttributes.Public, TypeFactory.VoidType, Type.EmptyTypes); ti.init_meth = init_mb; //определяем метод $Init$ для выделения памяти, если метод еще не определен (в структурах он опред-ся раньше) //MethodBuilder init_mb = ti.init_meth; //if (init_mb == null) init_mb = tb.DefineMethod("$Init$", MethodAttributes.Public, typeof(void), Type.EmptyTypes); ti.init_meth = init_mb; //определяем метод Clone и Assign if (tb.IsValueType) { MethodBuilder clone_mb = null; MethodBuilder ass_mb = null; if (NeedAddCloneMethods(ctn)) { clone_mb = tb.DefineMethod("$Clone$", MethodAttributes.Public, tb, Type.EmptyTypes); LocalBuilder lb = clone_mb.GetILGenerator().DeclareLocal(tb); MarkSequencePoint(clone_mb.GetILGenerator(), 0xFFFFFF, 0, 0xFFFFFF, 0); clone_mb.GetILGenerator().Emit(OpCodes.Ldloca, lb); clone_mb.GetILGenerator().Emit(OpCodes.Call, init_mb); ti.clone_meth = clone_mb; ass_mb = tb.DefineMethod("$Assign$", MethodAttributes.Public, TypeFactory.VoidType, new Type[1] { tb }); ass_mb.DefineParameter(1, ParameterAttributes.None, "$obj$"); ti.assign_meth = ass_mb; } MethodBuilder fix_mb = tb.DefineMethod("$Fix$", MethodAttributes.Public, TypeFactory.VoidType, Type.EmptyTypes); ti.fix_meth = fix_mb; } }
//определяем заголовки членов класса private void ConvertTypeMemberHeader(ICommonTypeNode value) { //если это оболочка над массивом переводим ее особым образом if (value.type_special_kind == type_special_kind.diap_type || value.type_special_kind == type_special_kind.array_kind) return; if (value.fields.Length == 1 && value.fields[0].type is ISimpleArrayNode) { ConvertArrayWrapperType(value); return; } if (value is ISimpleArrayNode) return; //этот тип уже был переведен, поэтому находим его TypeInfo ti = helper.GetTypeReference(value); //ivan if (ti.tp.IsEnum || !(ti.tp is TypeBuilder)) return; TypeBuilder tb = (TypeBuilder)ti.tp; if (tb.IsValueType) BuildCloseTypeOrder(value, tb); //сохраняем контекст TypeInfo tmp_ti = cur_ti; cur_ti = ti; TypeBuilder tmp = cur_type; cur_type = tb; //(ssyy) Если это интерфейс, то пропускаем следующую хрень if (!value.IsInterface) { //определяем метод $Init$ для выделения памяти, если метод еще не определен (в структурах он опред-ся раньше) MethodBuilder clone_mb = null; MethodBuilder ass_mb = null; if (ti.init_meth != null && tb.IsValueType) { clone_mb = ti.clone_meth as MethodBuilder; ass_mb = ti.assign_meth as MethodBuilder; } foreach (ICommonClassFieldNode fld in value.fields) fld.visit(this); foreach (ICommonMethodNode meth in value.methods) ConvertMethodHeader(meth); foreach (ICommonPropertyNode prop in value.properties) prop.visit(this); foreach (IClassConstantDefinitionNode constant in value.constants) constant.visit(this); foreach (ICommonEventNode evnt in value.events) evnt.visit(this); //(ssyy) 21.05.2008 foreach (ICommonMethodNode meth in value.methods) { if (meth.is_generic_function) { ConvertTypeInstancesMembersInFunction(meth); } } //добавляем ритерны в специальные методы //ti.init_meth.GetILGenerator().Emit(OpCodes.Ret); //if (hndl_mb != null) hndl_mb.GetILGenerator().Emit(OpCodes.Ret); if (clone_mb != null) { clone_mb.GetILGenerator().Emit(OpCodes.Ldloc_0); clone_mb.GetILGenerator().Emit(OpCodes.Ret); } if (ass_mb != null) { ass_mb.GetILGenerator().Emit(OpCodes.Ret); } if (ti.fix_meth != null) { ti.fix_meth.GetILGenerator().Emit(OpCodes.Ret); } } else { //(ssyy) сейчас переводим интерфейс foreach (ICommonMethodNode meth in value.methods) ConvertMethodHeader(meth); foreach (ICommonPropertyNode prop in value.properties) prop.visit(this); foreach (ICommonEventNode evnt in value.events) evnt.visit(this); //(ssyy) 21.05.2008 foreach (ICommonMethodNode meth in value.methods) { if (meth.is_generic_function) { ConvertTypeInstancesMembersInFunction(meth); } } } if (value.default_property != null) { using (BinaryWriter bw = new BinaryWriter(new MemoryStream())) { bw.Write(value.default_property.name); bw.Seek(0, SeekOrigin.Begin); byte[] bytes = new byte[2 + value.default_property.name.Length + 1 + 2]; bytes[0] = 1; bytes[1] = 0; bw.BaseStream.Read(bytes, 2, value.default_property.name.Length + 1); tb.SetCustomAttribute(TypeFactory.DefaultMemberAttributeType.GetConstructor(new Type[1] { TypeFactory.StringType }), bytes); } } //восстанавливаем контекст cur_type = tmp; cur_ti = tmp_ti; }
public void SetAsProcessing(ICommonTypeNode type) { processing_types[type] = true; }
public static bool can_write(ICommonTypeNode t) { return !(string.IsNullOrEmpty(t.Documentation) && !builder.options.ShowNoCommentedElements || t.name.Contains("$") || is_pascal_type(t) || user_doc_disabled(t.Documentation)); }
private static string get_delegate(ICommonTypeNode t, bool use_tags) { ICommonMethodNode f = builder.parser.GetMethods(t,"Invoke")[0]; StringBuilder sb = new StringBuilder(); if (f.return_value_type == null) sb.Append(use_tags?get_span_for_keyword("procedure"):"procedure"); else sb.Append(use_tags?get_span_for_keyword("function"):"function"); if (f.parameters.Length > 0) { sb.Append('('); for (int i = 0; i < f.parameters.Length; i++) { IParameterNode prm = f.parameters[i]; if (prm.parameter_type == parameter_type.var) sb.Append((use_tags ? get_span_for_keyword("var") : "var") + " "); else if (prm.is_params) sb.Append((use_tags ? get_span_for_keyword("params") : "params") + " "); if (use_tags) sb.Append(get_span_for_param(prm.name)); else sb.Append(prm.name); sb.Append(" : "); if (use_tags) sb.Append(get_type_html_text(prm.type)); else sb.Append(get_type_text(prm.type)); if (i < f.parameters.Length - 1) sb.Append("; "); } sb.Append(')'); } if (f.return_value_type != null && !f.is_constructor) sb.Append(": "+(use_tags?get_type_html_text(f.return_value_type):get_type_text(f.return_value_type))); return sb.ToString(); }
public static string get_type_header(ICommonTypeNode t) { StringBuilder sb = new StringBuilder(); string hdr = HelpUtils.extract_user_defined_header(t.Documentation); if (!string.IsNullOrEmpty(hdr)) { sb.Append("<div>"+hdr+"</div>"); return sb.ToString(); } sb.Append("<div>"); sb.Append(get_span_for_keyword("type")+" "+get_span_for_identifier(HelpUtils.build_name_with_possible_generic(t,true))+" = "); if (t.type_special_kind == type_special_kind.set_type) sb.Append(get_set_type(t,true)); else if (t.type_special_kind == type_special_kind.typed_file) sb.Append(get_typed_file(t,true)); else if (t.type_special_kind == type_special_kind.binary_file) sb.Append(get_span_for_keyword("file")); else if (t.type_special_kind == type_special_kind.diap_type) sb.Append(get_diap_type(t,true)); else if (t.type_special_kind == type_special_kind.array_wrapper) sb.Append(get_static_array_type(t,true)); else if (t.IsInterface) sb.Append(get_span_for_keyword("interface")); else if (t.is_class) { sb.Append(get_span_for_keyword("class")); sb.Append(get_inherited_and_implement(t)); } else if (t.IsEnum) sb.Append(get_enum(t,true)); else if (t.IsDelegate) sb.Append(get_delegate(t,true)); else if (t.is_value_type) sb.Append(get_span_for_keyword("record")); sb.Append("</div>"); return sb.ToString(); }
public void visit(ICommonTypeNode value) { ISemanticNodeConverter.SourceTextBuilder.AddNodeInToStack(ISemanticNodeConverter.ConvertPABCNETNodeType("type", value)); }
public virtual void visit(ICommonTypeNode value) { }
public void visit(ICommonTypeNode value) { string s = value.GetType().ToString() + "."; prepare_string_node(value.name, s + "name"); prepare_up_link_node(value.comprehensive_namespace.namespace_name.ToString(), s + "comprehensive_namespace", value.comprehensive_namespace); //table_for_up_links.Add(treeView.SelectedNode.Nodes[1] as myTreeNode, treeView.SelectedNode.Parent.Parent as myTreeNode); myTreeNode from = treeView.SelectedNode.Nodes[treeView.SelectedNode.Nodes.Count - 1] as myTreeNode; myTreeNode to = table_subnodes[value.comprehensive_namespace] as myTreeNode; table_for_up_links.Add(from, to); prepare_node(value.base_type, s + "base_type"); prepare_base_node_collection(value.constants, s + "constants", "constants", value.constants.Length); prepare_node(value.default_property, s + "default_property"); prepare_node(value.element_type, s + "element_type"); prepare_base_node_collection(value.fields, s + "fields", "fields", value.fields.Length); //prepare_node(value.generic_container, s + "generic_container"); //value.generic_params; prepare_string_node(value.has_static_constructor.ToString(), s + "has_static_constructor"); prepare_base_node_collection_up_links(value.ImplementingInterfaces, s + "ImplementingInterfaces", "ImplementingInterfaces", value.ImplementingInterfaces.Count); prepare_string_node(value.is_class.ToString(), s + "is_class"); prepare_string_node(value.is_generic_parameter.ToString(), s + "is_generic_parameter"); prepare_string_node(value.is_generic_type_definition.ToString(), s + "is_generic_type_definition"); prepare_string_node(value.is_value_type.ToString(), s + "is_value_type"); prepare_string_node(value.IsInterface.ToString(), s + "IsInterface"); prepare_string_node(value.IsSealed.ToString(), s + "IsSealed"); prepare_node(value.lower_value, s + "lower_value"); prepare_base_node_collection(value.methods, s + "methods", "methods", value.methods.Length); prepare_string_node(value.node_kind.ToString(), s + "node_kind"); prepare_base_node_collection(value.properties, s + "properties", "properties", value.properties.Length); //prepare_node(value.runtime_initialization_marker, s + "runtime_initialization_marker"); prepare_string_node(value.type_access_level.ToString(), s + "type_access_level"); prepare_string_node(value.type_special_kind.ToString(), s + "type_special_kind"); prepare_node(value.upper_value, s + "upper_value"); }
private void MakeAttribute(ICommonTypeNode ctn) { Type t = helper.GetTypeReference(ctn).tp; IAttributeNode[] attrs = ctn.Attributes; for (int i = 0; i < attrs.Length; i++) { //if (attrs[i].AttributeType == SystemLibrary.SystemLibrary.comimport_type) // continue; CustomAttributeBuilder cab = new CustomAttributeBuilder ((attrs[i].AttributeConstructor is ICompiledConstructorNode) ? (attrs[i].AttributeConstructor as ICompiledConstructorNode).constructor_info : helper.GetConstructor(attrs[i].AttributeConstructor).cnstr, get_constants(attrs[i].Arguments), get_named_properties(attrs[i].PropertyNames), get_constants(attrs[i].PropertyInitializers), get_named_fields(attrs[i].FieldNames), get_constants(attrs[i].FieldInitializers)); if (t is TypeBuilder) (t as TypeBuilder).SetCustomAttribute(cab); else if (t is EnumBuilder) (t as EnumBuilder).SetCustomAttribute(cab); } }
public static bool can_show_members(ICommonTypeNode t) { switch (t.type_special_kind) { case type_special_kind.array_wrapper: case type_special_kind.set_type: case type_special_kind.typed_file: case type_special_kind.text_file: case type_special_kind.binary_file: case type_special_kind.diap_type: return false; } if (t.IsDelegate /*|| t.IsEnum*/) return false; return true; }
private bool NeedAddCloneMethods(ICommonTypeNode ctn) { foreach (ICommonClassFieldNode cfn in ctn.fields) { if (cfn.polymorphic_state != polymorphic_state.ps_static && (cfn.type.type_special_kind == type_special_kind.array_wrapper || cfn.type.type_special_kind == type_special_kind.base_set_type || cfn.type.type_special_kind == type_special_kind.short_string || cfn.type.type_special_kind == type_special_kind.text_file || cfn.type.type_special_kind == type_special_kind.typed_file || cfn.type.type_special_kind == type_special_kind.binary_file || cfn.type.type_special_kind == type_special_kind.set_type)) return true; if (cfn.type.type_special_kind == type_special_kind.record && cfn.type is ICommonTypeNode) if (NeedAddCloneMethods(cfn.type as ICommonTypeNode)) return true; } return false; }
private Type CreateTypedSetType(ICommonTypeNode t) { Type tt = helper.GetPascalTypeReference(t); if (tt != null) return tt; TypeBuilder tb = mb.DefineType(cur_unit + ".%" + t.name, TypeAttributes.Public, TypeFactory.ObjectType); types.Add(tb); helper.AddPascalTypeReference(t, tb); add_possible_type_attribute(tb, t); return tb; }
private bool has_com_import_attr(ICommonTypeNode value) { IAttributeNode[] attrs = value.Attributes; foreach (IAttributeNode attr in attrs) if (attr.AttributeType == SystemLibrary.SystemLibrary.comimport_type) return true; return false; }
//переводим заголовки типов в порядке начиная с базовых классов (т. е. у которых наследники - откомпилированные типы) private void ConvertTypeHeaderInSpecialOrder(ICommonTypeNode t) { if (t.type_special_kind == type_special_kind.diap_type) return; if (t.type_special_kind == type_special_kind.array_kind) return; if (t.depended_from_indefinite) return; if (t.type_special_kind == type_special_kind.typed_file && comp_opt.target == TargetType.Dll) { if (!t.name.Contains(" ")) { CreateTypedFileType(t); return; } } else if (t.type_special_kind == type_special_kind.set_type && comp_opt.target == TargetType.Dll) { if (!t.name.Contains(" ")) { CreateTypedSetType(t); return; } } if (helper.GetTypeReference(t) != null && !t.is_generic_parameter) return; if (t.is_generic_parameter) { //ConvertTypeHeaderInSpecialOrder(t.generic_container); AddTypeWithoutConvert(t); if (converting_generic_param != t) { return; } converting_generic_param = null; } IGenericTypeInstance gti = t as IGenericTypeInstance; if (gti != null) { if (gti.original_generic is ICommonTypeNode) { ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)gti.original_generic); } foreach (ITypeNode itn in gti.generic_parameters) { if (itn is ICommonTypeNode && !itn.is_generic_parameter) { ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)itn); } } } if (t.is_generic_type_definition) { AddTypeWithoutConvert(t); foreach (ICommonTypeNode par in t.generic_params) { converting_generic_param = par; ConvertTypeHeaderInSpecialOrder(par); } } else if ((t.type_special_kind == type_special_kind.none_kind || t.type_special_kind == type_special_kind.record) && !t.IsEnum && !t.is_generic_type_instance && !t.is_generic_parameter) { AddTypeWithoutConvert(t); } foreach (ITypeNode interf in t.ImplementingInterfaces) if (!(interf is ICompiledTypeNode)) ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)interf); if (t.base_type != null && !(t.base_type is ICompiledTypeNode)) { ConvertTypeHeaderInSpecialOrder((ICommonTypeNode)t.base_type); } ConvertTypeHeader(t); }
private void AddPropertyAccessors(ICommonTypeNode ctn) { ICommonPropertyNode[] props = ctn.properties; foreach (ICommonPropertyNode prop in props) { if (prop.get_function != null && !prop_accessors.ContainsKey(prop.get_function)) prop_accessors.Add(prop.get_function, prop.get_function); if (prop.set_function != null && !prop_accessors.ContainsKey(prop.set_function)) prop_accessors.Add(prop.set_function, prop.set_function); } ICommonMethodNode[] meths = ctn.methods; foreach (ICommonMethodNode meth in meths) { if (meth.overrided_method != null && !prop_accessors.ContainsKey(meth) && prop_accessors.ContainsKey(meth.overrided_method)) prop_accessors.Add(meth, meth); } }
private void AddTypeWithoutConvert(ICommonTypeNode t) { if (helper.GetTypeReference(t) != null) return; TypeBuilder tb = mb.DefineType(cur_unit + "." + t.name, ConvertAttributes(t), null, new Type[0]); helper.AddType(t, tb); //(ssyy) обрабатываем generics if (t.is_generic_type_definition) { int count = t.generic_params.Count; string[] par_names = new string[count]; //Создаём массив имён параметров for (int i = 0; i < count; i++) { par_names[i] = t.generic_params[i].name; } //Определяем параметры в строящемся типе GenericTypeParameterBuilder[] net_pars = tb.DefineGenericParameters(par_names); for (int i = 0; i < count; i++) { //добавляем параметр во внутр. структуры helper.AddExistingType(t.generic_params[i], net_pars[i]); } } }
//перевод заголовка функции private void ConvertFunctionHeader(ICommonFunctionNode func) { //if (is_in_unit && helper.IsUsed(func)==false) return; num_scope++; //увеличиваем глубину обл. видимости TypeBuilder tb = null, tmp_type = cur_type; Frame frm = null; bool nested = false; //func.functions_nodes.Length > 0 - имеет вложенные //funcs.Count > 0 - сама вложенная if (func.functions_nodes.Length > 0 || funcs.Count > 0) { nested = true; frm = MakeAuxType(func);//создаем запись активации tb = frm.tb; cur_type = tb; } else tb = cur_type; MethodAttributes attrs = MethodAttributes.Public | MethodAttributes.Static; //определяем саму процедуру/функцию MethodBuilder methb = null; methb = tb.DefineMethod(func.name, attrs); if (func.is_generic_function) { int count = func.generic_params.Count; string[] names = new string[count]; for (int i = 0; i < count; i++) { names[i] = func.generic_params[i].name; } methb.DefineGenericParameters(names); Type[] genargs = methb.GetGenericArguments(); for (int i = 0; i < count; i++) { helper.AddExistingType(func.generic_params[i], genargs[i]); } foreach (ICommonTypeNode par in func.generic_params) { converting_generic_param = par; ConvertTypeHeaderInSpecialOrder(par); } ConvertTypeInstancesInFunction(func); } Type ret_type = null; //получаем тип возвр. значения if (func.return_value_type == null) ret_type = TypeFactory.VoidType; else ret_type = helper.GetTypeReference(func.return_value_type).tp; //получаем типы параметров Type[] param_types = GetParamTypes(func); methb.SetParameters(param_types); methb.SetReturnType(ret_type); MethInfo mi = null; if (smi.Count != 0) //добавляем вложенную процедуру, привязывая ее к верхней процедуре mi = helper.AddMethod(func, methb, smi.Peek()); else mi = helper.AddMethod(func, methb); mi.num_scope = num_scope; mi.disp = frm;//тип - запись активации smi.Push(mi); ParameterBuilder pb = null; int num = 0; ILGenerator tmp_il = il; il = methb.GetILGenerator(); if (save_debug_info) { if (func.function_code is IStatementsListNode) MarkSequencePoint(((IStatementsListNode)func.function_code).LeftLogicalBracketLocation); else MarkSequencePoint(func.function_code.Location); } //if (ret_type != typeof(void)) mi.ret_val = il.DeclareLocal(ret_type); //если функция вложенная, то добавляем фиктивный параметр //ссылку на верхнюю запись активации if (funcs.Count > 0) { mi.nested = true;//это вложенная процедура methb.DefineParameter(1, ParameterAttributes.None, "$up$"); num = 1; } //все нелокальные параметры будем хранить в нестатических полях //записи активации. В начале функции инициализируем эти поля //параметрами IParameterNode[] parameters = func.parameters; FieldBuilder[] fba = new FieldBuilder[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { object default_value = null; if (parameters[i].default_value != null) { default_value = helper.GetConstantForExpression(parameters[i].default_value); } ParameterAttributes pa = ParameterAttributes.None; //if (func.parameters[i].parameter_type == parameter_type.var) // pa = ParameterAttributes.Retval; if (default_value != null) pa |= ParameterAttributes.Optional; pb = methb.DefineParameter(i + num + 1, pa, parameters[i].name); if (parameters[i].is_params) pb.SetCustomAttribute(TypeFactory.ParamArrayAttributeConstructor, new byte[] { 0x1, 0x0, 0x0, 0x0 }); if (default_value != null) pb.SetConstant(default_value); if (func.functions_nodes.Length > 0) { FieldBuilder fb = null; //если параметр передается по значению, то все нормально if (parameters[i].parameter_type == parameter_type.value) fb = frm.tb.DefineField(parameters[i].name, param_types[i + num], FieldAttributes.Public); else { //иначе параметр передается по ссылке //тогда вместо типа параметра тип& используем тип* //например System.Int32& - System.Int32* (unmanaged pointer) //Type pt = param_types[i + num].Module.GetType(param_types[i + num].FullName.Substring(0, param_types[i + num].FullName.IndexOf('&')) + "*"); ////это означает, что тип определен в генерируемой сборке //if (pt == null) mb.GetType(param_types[i + num].FullName.Substring(0, param_types[i + num].FullName.IndexOf('&')) + "*"); Type pt = param_types[i + num].GetElementType().MakePointerType(); //определяем поле для параметра fb = frm.tb.DefineField(parameters[i].name, pt, FieldAttributes.Public); } //добавляем как глобальный параметр helper.AddGlobalParameter(parameters[i], fb).meth = smi.Peek(); fba[i] = fb; } else { //если проца не содержит вложенных, то все хорошо helper.AddParameter(parameters[i], pb).meth = smi.Peek(); } } if (func is ICommonNamespaceFunctionNode && (func as ICommonNamespaceFunctionNode).ConnectedToType != null) { if (!marked_with_extension_attribute.ContainsKey(cur_unit_type)) { cur_unit_type.SetCustomAttribute(TypeFactory.ExtensionAttributeType.GetConstructor(new Type[0]), new byte[0]); marked_with_extension_attribute[cur_unit_type] = cur_unit_type; } methb.SetCustomAttribute(TypeFactory.ExtensionAttributeType.GetConstructor(new Type[0]), new byte[0]); } if (func.functions_nodes.Length > 0 || funcs.Count > 0) { //определяем переменную, хранящую ссылку на запись активации данной процедуры LocalBuilder frame = il.DeclareLocal(cur_type); mi.frame = frame; if (doc != null) frame.SetLocalSymInfo("$disp$"); if (funcs.Count > 0) { //если она вложенная, то конструктору зап. акт. передаем ссылку на верх. з. а. il.Emit(OpCodes.Ldarg_0); //создаем запись активации il.Emit(OpCodes.Newobj, frm.cb); il.Emit(OpCodes.Stloc, frame); } else { //в противном случае просто создаем з. а. il.Emit(OpCodes.Newobj, frm.cb); il.Emit(OpCodes.Stloc_0, frame); } if (func.functions_nodes.Length > 0) for (int j = 0; j < fba.Length; j++) { //сохраняем нелокальные параметры в полях il.Emit(OpCodes.Ldloc_0); parameters = func.parameters; if (parameters[j].parameter_type == parameter_type.value) { if (funcs.Count > 0) il.Emit(OpCodes.Ldarg_S, (byte)(j + 1)); else il.Emit(OpCodes.Ldarg_S, (byte)j); } else { if (funcs.Count > 0) il.Emit(OpCodes.Ldarga_S, (byte)(j + 1)); else il.Emit(OpCodes.Ldarg_S, (byte)j); } il.Emit(OpCodes.Stfld, fba[j]); } } funcs.Add(func); //здесь наверное дублирование MethodBuilder tmp = cur_meth; cur_meth = methb; ConvertCommonFunctionConstantDefinitions(func.constants); //если функция не содержит вложенных процедур, то //переводим переменные как локальные if (func.functions_nodes.Length > 0) ConvertNonLocalVariables(func.var_definition_nodes, frm.mb); /*if (func.functions_nodes.Length == 0) ConvertLocalVariables(func.var_definition_nodes); else //иначе как нелокальные ConvertNonLocalVariables(func.var_definition_nodes, frm.mb);*/ //переводим заголовки вложенных функций ConvertNestedFunctionHeaders(func.functions_nodes); //переводим тела вложенных функций //foreach (ICommonNestedInFunctionFunctionNode f in func.functions_nodes) // ConvertFunctionBody(f); if (frm != null) frm.mb.GetILGenerator().Emit(OpCodes.Ret); //восстанавливаем текущие значения cur_type = tmp_type; num_scope--; smi.Pop(); funcs.RemoveAt(funcs.Count - 1); }
//перевод релизаций типов private void ConvertTypeImplementations(ICommonTypeNode[] types) { foreach (ICommonTypeNode t in types) //если это не особый тип переводим реализацию наверно здесь много лишнего нужно оставить ISimpleArrayNode { if (/*!(t.fields.Length == 1 && t.fields[0].type is ISimpleArrayNode) &&*/ t.type_special_kind != type_special_kind.diap_type && !t.depended_from_indefinite) t.visit(this); } }
//перевод заголовка метода private void ConvertMethodHeader(SemanticTree.ICommonMethodNode value) { if (value.is_constructor == true) { ConvertConstructorHeader(value); return; } if (helper.GetMethod(value) != null) return; MethodBuilder methb = null; bool is_prop_acc = IsPropertyAccessor(value); MethodAttributes attrs = GetMethodAttributes(value, is_prop_acc); IRuntimeManagedMethodBody irmmb = value.function_code as IRuntimeManagedMethodBody; if (irmmb != null) { if ((irmmb.runtime_statement_type == SemanticTree.runtime_statement_type.invoke_delegate) || (irmmb.runtime_statement_type == SemanticTree.runtime_statement_type.begin_invoke_delegate) || (irmmb.runtime_statement_type == SemanticTree.runtime_statement_type.end_invoke_delegate)) { attrs = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual; } } //определяем метод string method_name = OperatorsNameConvertor.convert_name(value.name); if (method_name != null) { attrs |= MethodAttributes.SpecialName; } else { bool get_set = false; method_name = GetPossibleAccessorName(value, out get_set); if (get_set) { attrs |= MethodAttributes.SpecialName; } /*if (is_get_set) { attrs |= MethodAttributes.SpecialName; method_name = cur_prop_name; }*/ } //ssyy if (value.comperehensive_type.IsInterface) { attrs |= MethodAttributes.Virtual | MethodAttributes.Abstract | MethodAttributes.NewSlot; } if (value.is_final) { attrs |= MethodAttributes.Virtual | MethodAttributes.Final; } if (value.newslot_awaited) { attrs |= MethodAttributes.NewSlot; } //\ssyy //methb = cur_type.DefineMethod(method_name, attrs, ret_type, param_types); methb = cur_type.DefineMethod(method_name, attrs); if (value.is_generic_function) { int count = value.generic_params.Count; string[] names = new string[count]; for (int i = 0; i < count; i++) { names[i] = value.generic_params[i].name; } methb.DefineGenericParameters(names); Type[] genargs = methb.GetGenericArguments(); for (int i = 0; i < count; i++) { helper.AddExistingType(value.generic_params[i], genargs[i]); } foreach (ICommonTypeNode par in value.generic_params) { converting_generic_param = par; ConvertTypeHeaderInSpecialOrder(par); } ConvertTypeInstancesInFunction(value); } Type ret_type = null; bool is_ptr_ret_type = false; if (value.return_value_type == null) ret_type = TypeFactory.VoidType; else { ret_type = helper.GetTypeReference(value.return_value_type).tp; if (IsNeedCorrectGetType(cur_ti, ret_type)) { ret_type = ret_type.MakePointerType(); is_ptr_ret_type = true; } } Type[] param_types = GetParamTypes(value); methb.SetParameters(param_types); methb.SetReturnType(ret_type); if (irmmb != null) { //if ((irmmb.runtime_statement_type == SemanticTree.runtime_statement_type.invoke_delegate) || // (irmmb.runtime_statement_type == SemanticTree.runtime_statement_type.begin_invoke_delegate) || // (irmmb.runtime_statement_type == SemanticTree.runtime_statement_type.end_invoke_delegate)) //{ methb.SetImplementationFlags(MethodImplAttributes.Runtime); //} } if (save_debug_info) { if (value.function_code is IStatementsListNode) MarkSequencePoint(methb.GetILGenerator(), ((IStatementsListNode)value.function_code).LeftLogicalBracketLocation); //else // MarkSequencePoint(methb.GetILGenerator(),value.function_code.Location); } //TestForHandler(value, param_types, methb); MethInfo mi = null; mi = helper.AddMethod(value, methb); //binding CloneSet to set type if (value.comperehensive_type.type_special_kind == type_special_kind.base_set_type && value.name == "GetEnumerator") { helper.GetTypeReference(value.comperehensive_type).enumerator_meth = methb; //helper.GetTypeReference(value.comprehensive_type).assign_meth = methb; } mi.is_ptr_ret_type = is_ptr_ret_type; mi.num_scope = num_scope + 1; ConvertMethodParameters(value, methb); }
private void ConvertTypeMemberHeaderAndRemoveFromList(ICommonTypeNode type, List<ICommonTypeNode> types) { if (!type.depended_from_indefinite) { if (type.type_special_kind == type_special_kind.array_wrapper && type.element_type.type_special_kind == type_special_kind.array_wrapper && type.element_type is ICommonTypeNode && types.IndexOf((ICommonTypeNode)(type.element_type)) > -1) { ConvertTypeMemberHeaderAndRemoveFromList((ICommonTypeNode)(type.element_type), types); } ConvertTypeMemberHeader(type); } types.Remove(type); }
private IFunctionNode find_constructor(ICommonTypeNode tn) { foreach (ICommonMethodNode cmn in tn.methods) { if (cmn.is_constructor) return cmn; } return null; }
//перевод заголовков членов класса private void ConvertTypeMemberHeaders(ICommonTypeNode[] types) { //(ssyy) Переупорядочиваем, чтобы массивы создавались в правильном порядке List<ICommonTypeNode> ts = new List<ICommonTypeNode>(types); while (ts.Count > 0) { ConvertTypeMemberHeaderAndRemoveFromList(ts[0], ts); } //foreach (ICommonTypeNode t in types) // ConvertTypeMemberHeader(t); }
private void BuildCloseTypeOrder(ICommonTypeNode value, TypeBuilder tb) { foreach (ICommonClassFieldNode fld in value.fields) { ITypeNode ctn = fld.type; TypeInfo ti = helper.GetTypeReference(ctn); if (ctn is ICommonTypeNode && ti.tp.IsValueType && ti.tp is TypeBuilder) { BuildCloseTypeOrder((ICommonTypeNode)ctn, (TypeBuilder)ti.tp); } } if (!added_types.ContainsKey(tb)) { value_types.Add(tb); added_types[tb] = tb; } }
public bool IsProcessing(ICommonTypeNode type) { return(processing_types[type] != null); }
//перевод заголовков типов private void ConvertTypeHeaders(ICommonTypeNode[] types) { foreach (ICommonTypeNode t in types) { ConvertTypeHeaderInSpecialOrder(t); } }