Esempio n. 1
0
        /// <summary>
        /// Конструктор класса.
        /// </summary>
        /// <param name="begin_line_num">Номер строки начала фрагмента кода (нумерация начинается с 1).</param>
        /// <param name="begin_column_num">Номер колонки начала фрагмента кода (нумерация начинается с 1).</param>
        /// <param name="end_line_num">Номер строки конца фрагмента кода (нумерация начинается с 1).</param>
        /// <param name="end_column_num">Номер колонки конца фрагмента кода (нумерация начинается с 1)</param>
        /// <param name="doc">Документ, в котором расположен этот фрагмент кода.</param>
		public location(int begin_line_num, int begin_column_num,int end_line_num,int end_column_num,document doc)
		{
			_begin_line_num=begin_line_num;
			_begin_column_num=begin_column_num;
			_end_line_num=end_line_num;
			_end_column_num=end_column_num;
			_doc=doc;
		}
Esempio n. 2
0
 public template_class(SyntaxTree.type_declaration type_decl, string name,common_namespace_node cnn,/*common_type_node ctn,location loc,*/document doc,using_namespace_list unl)
 {
     _cnn = cnn;
     _type_decl = type_decl;
     _name = name;
     _doc = doc;
     
     //(ssyy) using - список, по-видимому, можно только копировать, т.к. Николай его периодически чистит.
     _unl = new using_namespace_list();
     foreach (using_namespace un in unl)
     {
         _unl.AddElement(un);
     }
 }
 public location get_location_with_check(SyntaxTree.syntax_tree_node tn)
 {
     if (tn == null || tn.source_context == null)
     {
         return null;
     }
     document d = current_document;
     if (tn.source_context.FileName != null)
         d = new document(tn.source_context.FileName);
     return new location(tn.source_context.begin_position.line_num, tn.source_context.begin_position.column_num,
         tn.source_context.end_position.line_num, tn.source_context.end_position.column_num, d);
 }
 public void reset()
 {
     _system_unit = null;
     SystemLibrary.SystemLibrary.system_unit = null;
     //SystemLibrary.SystemLibrary.Reset();
     SystemUnitAssigned = false;
     _compiled_unit = null;
     _referenced_units = null;
     current_document = null;
     using_list.clear();
     //_referenced_units.clear();
     ret.reset();
     motivation_keeper.reset();
     context.reset();
     convertion_data_and_alghoritms.reset();
     //compiled_type_node.compiled_types.Clear();
     internal_reset();
     release_system_module();
     WaitedRefTypes.Clear();
     set_intls.Clear();
     NetHelper.NetHelper.reset();
     if (ErrorsList != null)
         ErrorsList.Clear();
     from_pabc_dll = false;
     in_interface_part = false;
     compiled_type_node[] ctns = new compiled_type_node[compiled_type_node.compiled_types.Values.Count];
     compiled_type_node.compiled_types.Values.CopyTo(ctns, 0);
     null_type_node.reset();
     foreach (compiled_type_node ctn in ctns)
     {
         ctn.reinit_scope();
         ctn.clear_generated_names();
         ctn.clear_generated_intersections();
     }
 }
        public common_type_node instance(template_class tc, List<type_node> template_params, location loc)
        {
            //Проверяем, что попытка инстанцирования корректна
            SyntaxTree.class_definition cl_def = tc.type_dec.type_def as SyntaxTree.class_definition;
            SyntaxTree.template_type_name ttn = tc.type_dec.type_name as SyntaxTree.template_type_name;
#if (DEBUG)
            if (!tc.is_synonym)
            {
                if (cl_def == null)
                {
                    throw new PascalABCCompiler.TreeConverter.CompilerInternalError("No body definition in template class.");
                }
                if (cl_def.template_args == null || cl_def.template_args.idents == null)
                {
                    throw new PascalABCCompiler.TreeConverter.CompilerInternalError("No template arguments in syntax tree.");
                }
            }
            else
            {
                if (ttn == null)
                {
                    throw new PascalABCCompiler.TreeConverter.CompilerInternalError("No template name.");
                }
            }
#endif
            List<SyntaxTree.ident> template_formals = (tc.is_synonym) ?
                ttn.template_args.idents : cl_def.template_args.idents;
            if (template_formals.Count != ttn.template_args.idents.Count)
            {
                AddError(loc, "TEMPLATE_ARGUMENTS_COUNT_MISMATCH");
            }

            if (!tc.is_synonym)
            {
                foreach (type_node tnode in template_params)
                {
                    if (depended_from_generic_parameter(tnode))
                    {
                        AddError(loc, "TEMPLATES_AND_GENERICS_ARE_INCOMPATIBLE");
                    }
                }
            }

            //А вдруг такая инстанция уже есть - вернём её
            string inst_name = tc.CreateTemplateInstance(template_params, loc);
            SymbolInfo si = tc.cnn.scope.FindOnlyInScope(inst_name);
            if (si != null)
            {
                return (common_type_node)si.sym_info;
            }

            //Переходим в место описания шаблона
            common_namespace_node current_namespace = context.converted_namespace;
            context.converted_namespace = tc.cnn;
            common_type_node current_type = context.converted_type;
            context.converted_type = null;
            template_class current_template = context.converted_template_type;
            context.converted_template_type = null;
            compiled_type_node current_compiled_type = context.converted_compiled_type;
            context.converted_compiled_type = null;
            common_function_node_stack current_funk_stack = context.converted_func_stack;
            context.converted_func_stack = new common_function_node_stack(); //Думаю, это будет работать

            //DarkStar
            statement_list_stack statement_list_stack = convertion_data_and_alghoritms.statement_list_stack;
            convertion_data_and_alghoritms.statement_list_stack = new statement_list_stack();

            bool current_cur_meth_not_in_class = current_converted_method_not_in_class_defined;
            current_converted_method_not_in_class_defined = false;
            SymbolInfo current_last_created_function = context.last_created_function;
            context.last_created_function = null;
            bool current_record_created = _record_created;
            _record_created = false;
            SemanticTree.field_access_level current_fal = context.get_field_access_level();
            document current_doc = current_document;
            current_document = tc.cur_document;
            bool current_body_exists = body_exists;
            body_exists = false;
            bool current_allow_inherited_ctor_call = context.allow_inherited_ctor_call;
            bool current_is_direct_type_decl = is_direct_type_decl;
            is_direct_type_decl = false;
            context.allow_inherited_ctor_call = false;
            bool current_type_section_converting = type_section_converting;
            type_section_converting = true;
            SemanticTree.field_access_level curr_fal = context.get_field_access_level();
            List<var_definition_node> current_var_defs = context.var_defs;
            context.var_defs = new List<var_definition_node>();
            Hashtable current_member_decls = context.member_decls;
            context.member_decls = new Hashtable();
            //подменяем using-список 
            using_namespace_list current_using_list = new using_namespace_list();
            foreach (using_namespace un in using_list)
            {
                current_using_list.AddElement(un);
            }
            using_list.clear();
            foreach (using_namespace un in tc.using_list)
            {
                using_list.AddElement(un);
            }
            context.converted_type = null; 
            context.enter_code_block_without_bind();

            common_type_node ctn;

            bool interface_creating = false;

            //Создаём инстанцию шаблона
            if (tc.is_synonym)
            {
                ctn = context.create_type(inst_name, get_location(ttn));
            }
            else
            {
                if (cl_def.keyword == SyntaxTree.class_keyword.Record)
                {
                    ctn = context.create_record_type(get_location(tc.type_dec.type_name), inst_name);
                }
                else
                {
                    interface_creating = (cl_def.keyword == PascalABCCompiler.SyntaxTree.class_keyword.Interface);
                    ctn = context.advanced_create_type(inst_name, get_location(tc.type_dec.type_name), interface_creating);
                }
            }
            ctn.original_template = tc;
            bool indefinite = false;
            foreach (type_node tn in template_params)
            {
                indefinite = indefinite || tn.depended_from_indefinite;
            }
            ctn.SetDependedFromIndefinite(indefinite);
            tc.instance_params.Add(ctn, template_params);

            //Ставим в соответствие формальным параметрам шаблона фактические
            for (int i = 0; i < template_params.Count; i++)
            {
                ctn.Scope.AddSymbol(template_formals[i].name, new SymbolInfo(template_params[i]));
            }

            //Разбор тела класса
            if (tc.is_synonym)
            {
                type_node synonym_value = convert_strong(tc.type_dec.type_def);
                ctn.fields.AddElement(new class_field(compiler_string_consts.synonym_value_name,
                    synonym_value, ctn, PascalABCCompiler.SemanticTree.polymorphic_state.ps_static,
                    PascalABCCompiler.SemanticTree.field_access_level.fal_public, null));
            }
            else
            {
                if (cl_def.keyword == SyntaxTree.class_keyword.Record)
                {
                    _record_created = true;
                }

                bool tmp_direct = is_direct_type_decl;
                is_direct_type_decl = true;
                hard_node_test_and_visit(cl_def);
                is_direct_type_decl = tmp_direct;

                //Разбор методов, описанных вне класса
                if (!interface_creating)
                {
                    type_section_converting = false;
                    foreach (procedure_definition_info pdi in tc.external_methods)
                    {
                        if (context.converted_namespace != pdi.nspace)
                        {
                            context.converted_namespace = pdi.nspace;
                            using_namespace_list ulist =
                                (pdi.nspace == tc.cnn) ? tc.using_list : tc.using_list2;
                            using_list.clear();
                            foreach (using_namespace un in ulist)
                            {
                                using_list.AddElement(un);
                            }
                            template_class.AddUsingListToScope(context.converted_namespace.scope, ulist);
                        }

                        //Заменяем в дереве метода имя шаблонного класса на имя инстанции
                        string tmp_name = pdi.proc.proc_header.name.class_name.name;
                        pdi.proc.proc_header.name.class_name.name = inst_name;

                        hard_node_test_and_visit(pdi.proc);

                        //Обратная замена
                        pdi.proc.proc_header.name.class_name.name = tmp_name;
                    }

                    foreach (common_method_node cmn in ctn.methods)
                    {
                        if (cmn.function_code == null)
                        {
                            AddError(cmn.loc, "FUNCTION_PREDEFINITION_WITHOUT_DEFINITION");
                        }
                    }
                }
            }

            //Прыжок обратно
            context.leave_code_block();
            context.converted_namespace = current_namespace;
            context.converted_type = current_type;
            context.converted_template_type = current_template;
            context.set_field_access_level(current_fal);
            context.converted_func_stack = current_funk_stack;
            context.converted_compiled_type = current_compiled_type;
            convertion_data_and_alghoritms.statement_list_stack = statement_list_stack;
            current_document = current_doc;
            body_exists = current_body_exists;
            _record_created = current_record_created;
            context.last_created_function = current_last_created_function;
            is_direct_type_decl = current_is_direct_type_decl;
            context.allow_inherited_ctor_call = current_allow_inherited_ctor_call;
            current_converted_method_not_in_class_defined = current_cur_meth_not_in_class;
            context.set_field_access_level(curr_fal);
            type_section_converting = current_type_section_converting;
            context.member_decls = current_member_decls;
            context.var_defs = current_var_defs;
            using_list.clear();
            foreach (using_namespace un in current_using_list)
            {
                using_list.AddElement(un);
            }

            return ctn;
        }
        private template_class CreateTemplateClass(int offset)
        {
            definition_node dn = null;
            if (members.TryGetValue(offset, out dn))
                return dn as template_class;
            template_class tc = null;

            string name = br.ReadString();

            bool is_syn = br.ReadByte() == 1;

            using_namespace_list unl = new using_namespace_list();
            int using_count = br.ReadInt32();
            for (int i = 0; i < using_count; i++)
            {
                unl.AddElement(new using_namespace(br.ReadString()));
            }
            using_namespace_list unl2 = null;
            if (CanReadObject())
            {
                unl2 = new using_namespace_list();
                int using_count2 = br.ReadInt32();
                for (int i = 0; i < using_count2; i++)
                {
                    unl2.AddElement(new using_namespace(br.ReadString()));
                }
            }
            document doc = null;
            if (br.ReadByte() == 1)
            {
                doc = new document(Path.Combine(Path.GetDirectoryName(cur_doc.file_name),br.ReadString()));
            }

            SyntaxTree.SyntaxTreeStreamReader str = new SyntaxTree.SyntaxTreeStreamReader();
            str.br = br;
            SyntaxTree.type_declaration t_d = str._read_node() as SyntaxTree.type_declaration;

            int ext_count = br.ReadInt32();
            List<procedure_definition_info> pdi_list = new List<procedure_definition_info>(ext_count);
            for (int i = 0; i < ext_count; i++)
            {
                byte num = br.ReadByte();
                common_namespace_node c_m_n = cun.namespaces[num];
                SyntaxTree.syntax_tree_node stn = str._read_node();
                SyntaxTree.procedure_definition p_d = stn as SyntaxTree.procedure_definition;
                pdi_list.Add(new procedure_definition_info(c_m_n, p_d));
            }

            //(ssyy) Далее формируем список областей видимости, которые
            //подключаются к модулю. Вообще-то шаблоны классов этим
            //заниматься не должны, но кроме них этот список
            //никому не нужен (по состоянию на 01.06.2007).
            if (cun.scope.TopScopeArray.Length == 0)
            {
                cun.scope.TopScopeArray = MakeTopScopeArray(unl, pcu_file.interface_uses_count);
            }

            if (cun.implementation_scope.TopScopeArray.Length == 0 && unl2 != null)
            {
                //формируем implementation - область
                cun.implementation_scope.TopScopeArray = MakeTopScopeArray(unl2, pcu_file.incl_modules.Length);
            }

            tc = new template_class(t_d, name, cun.namespaces[0], doc, unl);
            tc.external_methods = pdi_list;
            tc.using_list2 = unl2;
            tc.is_synonym = is_syn;

            //members[offset] = tc;
            AddMember(tc, offset);
            
            cun.namespaces[0].scope.AddSymbol(name, new SymbolInfo(tc));

            return tc;
        }
        //десериализация модуля
        //читается только шапка PCU и заполняются имена сущностей модуля в таблицу символов
		public CompilationUnit GetCompilationUnit(string FileName, bool readDebugInfo)
		{
            try
            {
                this.FileName = FileName;
                this.readDebugInfo = readDebugInfo;
                unit_name = System.IO.Path.GetFileNameWithoutExtension(FileName);
                PCUReader pr = (PCUReader)units[unit_name];
                if (pr != null) return pr.unit;
                if (!File.Exists(FileName)) return null;
                dir = System.IO.Path.GetDirectoryName(FileName);
                //fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                ms = new MemoryStream(File.ReadAllBytes(FileName));
                br = new BinaryReader(ms);
                ReadPCUHeader();
                units[unit_name] = this;
                if (NeedRecompiled())
                {
                    CloseUnit();
                    need = true;
                    return null; // return comp.RecompileUnit(unit_name);
                }
                unit = new CompilationUnit();
                cun = new common_unit_node();
                cun.compiler_directives = pcu_file.compiler_directives;
                unit.SemanticTree = cun;
                ChangeState(this, PCUReaderWriterState.BeginReadTree, unit);
                cun.scope = new WrappedUnitInterfaceScope(this);
                
                //TODO сохранить в PCU
                cun.scope.CaseSensitive = false;
                if (string.Compare(unit_name,PascalABCCompiler.TreeConverter.compiler_string_consts.system_unit_file_name)==0)
                	PascalABCCompiler.TreeConverter.syntax_tree_visitor.init_system_module(cun);
                //ssyy
                //Создаём область видимости для implementation - части
                cun.implementation_scope = new WrappedUnitImplementationScope(this, cun.scope);
                //\ssyy

                //TODO сохранить в PCU
                cun.implementation_scope.CaseSensitive = false;

                string SourceFileName = pcu_file.SourceFileName;
                if (Path.GetDirectoryName(SourceFileName) == "")
                {
                    SourceFileName = Path.Combine(Path.GetDirectoryName(FileName), SourceFileName);
                    if (!File.Exists(SourceFileName))
                        SourceFileName = Path.Combine(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(FileName)),"LibSource"), pcu_file.SourceFileName);
                }
                cur_doc = new document(SourceFileName);

                AddNamespaces();
                AddInterfaceNames();
                //ssyy
                AddImplementationNames();
                //\ssyy
                
                //AddInitFinalMethods();
                //ProcessWaitedToRestoreFields();
                unit.State = UnitState.Compiled;
				//ssyy
                AddTypeSynonyms(pcu_file.interface_synonyms_offset, cun.scope);
                AddTypeSynonyms(pcu_file.implementation_synonyms_offset, cun.implementation_scope);
                //\ssyy
                

                ChangeState(this, PCUReaderWriterState.EndReadTree, unit);
                return unit;
            }
            catch (Exception)
            {
                CloseUnit();
                throw;

            }
		}
        public override void visit(c_module _c_module)
        {
            //Assembly _as = System.Reflection.Assembly.LoadFrom(get_assembly_path("mscorlib.dll",_c_module.file_name));
            System.Reflection.Assembly _as = System.Reflection.Assembly.LoadFrom(get_assembly_path("mscorlib.dll",_c_module.file_name));
            PascalABCCompiler.NetHelper.NetHelper.init_namespaces(_as);
            //add_standart_types_simple();
            //List<Scope> netScopes = new List<Scope>();
            //PascalABCCompiler.NetHelper.NetScope ns=new PascalABCCompiler.NetHelper.NetScope(unl,_as,tcst);
            if (_c_module.compiler_directives != null)
            foreach (PascalABCCompiler.SyntaxTree.compiler_directive dir in _c_module.compiler_directives)
            {
                if (dir.Name.text == "reference")
                {
                    try
                    {
                		//System.Reflection.Assembly assm = System.Reflection.Assembly.LoadFrom(get_assembly_path(dir.Directive.text,_c_module.file_name));
                    	System.Reflection.Assembly assm = PascalABCCompiler.NetHelper.NetHelper.LoadAssembly(get_assembly_path(dir.Directive.text,_c_module.file_name));
                		PascalABCCompiler.NetHelper.NetHelper.init_namespaces(assm);
                    }
                    catch (Exception e)
                    {
                    	
                    }
                }
            }
            cur_scope = new InterfaceUnitScope(new SymInfo("", SymbolKind.Block,"module"),null);
            doc = new document(_c_module.file_name);
            cur_scope.loc = get_location(_c_module);
            entry_scope = cur_scope;
            
            add_system_unit();
            if (_c_module.used_units != null)
            {
                (cur_scope as InterfaceUnitScope).uses_source_range = get_location(_c_module.used_units);
                foreach (unit_or_namespace s in _c_module.used_units.units)
                {
                    try
                    {
                        string str = "";
                        for (int i = 0; i < s.name.idents.Count; i++)
                        {
                            str += s.name.idents[i].name;
                            NamespaceScope ns_scope = null;
                            if (i == 0)
                            {
                                if (PascalABCCompiler.NetHelper.NetHelper.IsNetNamespace(str))
                                {
                                    ns_scope = new NamespaceScope(str);
                                    cur_scope.AddName(str, ns_scope);
                                    if (s.name.idents.Count == 1) cur_scope.AddUsedUnit(ns_scope);
                                }
                                else
                                {
                                    string unit_name = CodeCompletionController.comp.FindSourceFileName(str);
                                    if (unit_name == null)
                                    {
                                        unit_name = Path.Combine(System.IO.Path.GetDirectoryName(_c_module.file_name), str) + System.IO.Path.GetExtension(_c_module.file_name);
                                        if (!System.IO.File.Exists(unit_name)) unit_name = null;
                                    }
                                    if (unit_name != null)
                                    {
                                        DomConverter dc = CodeCompletionController.comp_modules[unit_name] as DomConverter;
                                        if (dc == null /*|| CodeCompletionController.recomp_files[unit_name] != null*/)
                                        {
                                            dc = new CodeCompletionController().CompileAllIfNeed(unit_name);
                                        }
                                        if (dc.stv != null)
                                        {
                                            cur_scope.AddUsedUnit(dc.stv.entry_scope);
                                            cur_scope.AddName(str, dc.stv.entry_scope);
                                        }
                                    }
                                }
                            }
                            if (i < s.name.idents.Count - 1) str += ".";
                            if (i == s.name.idents.Count - 1 && i > 0) cur_scope.AddUsedUnit(new NamespaceScope(str));
                        }
                        unl.AddElement(new PascalABCCompiler.TreeRealization.using_namespace(str));
                    }
                    catch (Exception e)
                    {

                    }
                }
            }
           
            
			//PascalABCCompiler.TreeRealization.common_type_node ctn = new ;
			if (_c_module.defs != null)
			foreach (declaration decl in _c_module.defs.defs)
            {
				decl.visit(this);
            }
			
        }
        public override void visit(program_module _program_module)
        {
            //Assembly _as = System.Reflection.Assembly.LoadFrom(get_assembly_path("mscorlib.dll",_program_module.file_name));
            string path = get_assembly_path("mscorlib.dll",_program_module.file_name);
            System.Reflection.Assembly _as = PascalABCCompiler.NetHelper.NetHelper.LoadAssembly(path);
            List<string> namespaces = new List<string>();
            PascalABCCompiler.NetHelper.NetHelper.init_namespaces(_as);
            AssemblyDocCache.Load(_as,path);
            
            namespaces.AddRange(PascalABCCompiler.NetHelper.NetHelper.GetNamespaces(_as));
            //List<Scope> netScopes = new List<Scope>();
            //PascalABCCompiler.NetHelper.NetScope ns=new PascalABCCompiler.NetHelper.NetScope(unl,_as,tcst);
            InterfaceUnitScope unit_scope = null;
            cur_scope = unit_scope = new InterfaceUnitScope(new SymInfo("", SymbolKind.Namespace,"program"),null);
//            if (XmlDoc.LookupLocalizedXmlDocForUnitWithSources(_program_module.file_name) != null)
//            {
//            	UnitDocCache.LoadWithSources(cur_scope,_program_module.file_name);
//            	this.add_doc_from_text = false;
//            }
            //add_standart_types_simple();
            CodeCompletionController.comp_modules[_program_module.file_name] = this.converter;
            Stack<Position> regions_stack = new Stack<Position>();
            if (CodeCompletionController.comp.CompilerOptions.CurrentProject != null && CodeCompletionController.comp.CompilerOptions.CurrentProject.ContainsSourceFile(_program_module.file_name))
            {
            	IReferenceInfo[] refs = CodeCompletionController.comp.CompilerOptions.CurrentProject.References;
            	if (_program_module.compiler_directives == null)
            		_program_module.compiler_directives = new List<PascalABCCompiler.SyntaxTree.compiler_directive>();
            	foreach (IReferenceInfo ri in refs)
            	{
            		_program_module.compiler_directives.Add
            			(new PascalABCCompiler.SyntaxTree.compiler_directive(new token_info("reference"),new token_info(ri.FullAssemblyName)));
            	}
            }
            if (_program_module.compiler_directives != null)
            foreach (PascalABCCompiler.SyntaxTree.compiler_directive dir in _program_module.compiler_directives)
            {
            	if (dir.Name.text.ToLower() == "reference")
                {
                    try
                    {
                		//System.Reflection.Assembly assm = System.Reflection.Assembly.LoadFrom(get_assembly_path(dir.Directive.text,_program_module.file_name));
                    	path = get_assembly_path(dir.Directive.text,_program_module.file_name);
                		System.Reflection.Assembly assm = PascalABCCompiler.NetHelper.NetHelper.LoadAssembly(path);
                        if (assm != null)
                        {
                            PascalABCCompiler.NetHelper.NetHelper.init_namespaces(assm);
                            AssemblyDocCache.Load(assm, path);
                            namespaces.AddRange(PascalABCCompiler.NetHelper.NetHelper.GetNamespaces(assm));
                            unit_scope.AddReferencedAssembly(assm);
                        }
                    }
                    catch (Exception e)
                    {
                    	
                    }
                }
                else
                if (dir.Name.text.ToLower() == "region")
                {
                	if (cur_scope.regions == null)
                		cur_scope.regions = new List<Position>();
                	regions_stack.Push(new Position(dir.source_context.begin_position.line_num,dir.source_context.begin_position.column_num,dir.source_context.end_position.line_num,dir.source_context.end_position.column_num,dir.source_context.FileName));	                   
                }
                else if (dir.Name.text.ToLower() == "endregion")
                {
                	if (regions_stack.Count > 0)
                	{
                		Position pos = regions_stack.Pop();
                		if (cur_scope.regions != null)
                		{
                			cur_scope.regions.Add(new Position(pos.end_line,pos.end_column,dir.source_context.end_position.line_num,dir.source_context.end_position.column_num,pos.file_name));
                		}
                	}
                }
            }
            
            doc = new document(_program_module.file_name);
            cur_scope.loc = get_location(_program_module);
            entry_scope = cur_scope;
            if (_program_module.program_name != null)
            	cur_scope.head_loc = get_location(_program_module.program_name);
            
            Hashtable ns_cache = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
            bool has_system_unit = false;
            if (_program_module.used_units != null)
            {
                unit_scope.uses_source_range = get_location(_program_module.used_units);

                //foreach (unit_or_namespace s in _program_module.used_units.units)
                for (int j = _program_module.used_units.units.Count - 1; j >= 0; j--)
                {
                    unit_or_namespace s = _program_module.used_units.units[j];

                    try
                    {
                        string str = "";
                        for (int i = 0; i < s.name.idents.Count; i++)
                        {
                            str += s.name.idents[i].name;
                            NamespaceScope ns_scope = null;
                            if (i == 0)
                            {
                                if (PascalABCCompiler.NetHelper.NetHelper.IsNetNamespace(str))
                                {
                                    ns_scope = new NamespaceScope(str);
                                    ns_cache[str] = str;
                                    cur_scope.AddName(str, ns_scope);
                                    if (s.name.idents.Count == 1)
                                        cur_scope.AddUsedUnit(ns_scope);
                                }
                                else if (PascalABCCompiler.NetHelper.NetHelper.IsType(str) && semantic_options.allow_import_types)
                                {
                                    Type t = PascalABCCompiler.NetHelper.NetHelper.FindType(str);
                                    cur_scope.AddUsedUnit(new NamespaceTypeScope(TypeTable.get_compiled_type(new SymInfo(t.Name, SymbolKind.Class, t.FullName), t)));
                                }
                                else
                                {
                                    string unit_name = null;
                                    string pcu_unit_name = FindPCUFileName(str);
                                    if (s is uses_unit_in) unit_name = (s as uses_unit_in).in_file.Value;
                                    else unit_name = CodeCompletionNameHelper.FindSourceFileName(str, System.IO.Path.GetDirectoryName(_program_module.file_name));
                                    if (pcu_unit_name != null && unit_name != null && string.Compare(System.IO.Path.GetDirectoryName(_program_module.file_name), System.IO.Path.GetDirectoryName(pcu_unit_name), true) == 0
                                        && string.Compare(System.IO.Path.GetDirectoryName(_program_module.file_name), System.IO.Path.GetDirectoryName(unit_name), true) != 0)
                                        unit_name = null;
                                    if (unit_name != null)
                                    {
                                        DomConverter dc = CodeCompletionController.comp_modules[unit_name] as DomConverter;
                                        if (dc == null /*|| CodeCompletionController.recomp_files[unit_name] != null*/)
                                        {
                                            dc = new CodeCompletionController().CompileAllIfNeed(unit_name, true);
                                        }
                                        if (dc.stv != null)
                                        {
                                            dc.stv.entry_scope.InitAssemblies();
                                            cur_scope.AddUsedUnit(dc.stv.entry_scope);
                                            cur_scope.AddName(str, dc.stv.entry_scope);
                                        }
                                    }
                                    else
                                    {
                                        //unit_name = FindPCUFileName(str);
                                        unit_name = pcu_unit_name;
                                        if (unit_name != null)
                                        {
                                            IntellisensePCUReader pcu_rdr = new IntellisensePCUReader();
                                            SymScope ss = pcu_rdr.GetUnit(unit_name);
                                            UnitDocCache.Load(ss, unit_name);
                                            cur_scope.AddUsedUnit(ss);
                                            cur_scope.AddName(str, ss);
                                        }
                                        //unit_name = System.IO.Path.GetDirectoryName(_program_module.file_name)+"\\"+str+System.IO.Path.GetExtension(_program_module.file_name);
                                    }
                                }
                            }
                            if (i == s.name.idents.Count - 1 && i > 0 /*&& PascalABCCompiler.NetHelper.NetHelper.IsNetNamespace(str)*/)
                                //possible_namespaces.Add(str);
                                cur_scope.AddUsedUnit(new NamespaceScope(str));
                            if (i < s.name.idents.Count - 1)
                                str += ".";

                        }
                        if (string.Compare(str,"PABCSystem",true) == 0)
                        {
                            has_system_unit = true;
                        }
                        unl.AddElement(new PascalABCCompiler.TreeRealization.using_namespace(str));
                    }
                    catch (Exception e)
                    {

                    }
                }

            }
            if (!has_system_unit)
            add_system_unit();
            foreach (string s in namespaces)
            {
            	if (!ns_cache.ContainsKey(s))
            	{
            		NamespaceScope ns_scope = new NamespaceScope(s);
                    cur_scope.AddName(s,ns_scope);
                    ns_cache[s] = s;
            	}
            }
            
			//PascalABCCompiler.TreeRealization.common_type_node ctn = new ;
			if (_program_module.program_block.defs != null)
			foreach (declaration decl in _program_module.program_block.defs.defs)
            {
                try
                {
					decl.visit(this);
                }
                catch(Exception e)
                {
                	
                }
            }
			if (_program_module.program_block.program_code != null)
			{
				//cur_scope.body_loc = get_location(_program_module.program_block.program_code);
				cur_scope.body_loc = new location(_program_module.program_block.program_code.left_logical_bracket.source_context.end_position.line_num,
				                                  _program_module.program_block.program_code.left_logical_bracket.source_context.end_position.column_num,
				                                  _program_module.program_block.program_code.source_context.end_position.line_num,_program_module.program_block.program_code.source_context.end_position.column_num,
				                                 doc);
				//cur_scope.head_loc = get_location(_program_module.program_block.program_code.left_logical_bracket);
				_program_module.program_block.program_code.visit(this);
			}
			/*if (_program_module.program_block.program_code != null)
			cur_scope.loc = get_location(_program_module.program_block.program_code);
			else cur_scope.loc = new location(0,0,0,0,doc);*/
        }
 public override void visit(unit_module _unit_module)
 {
     string path = get_assembly_path("mscorlib.dll",_unit_module.file_name);
 	Assembly _as = PascalABCCompiler.NetHelper.NetHelper.LoadAssembly(path);
     AssemblyDocCache.Load(_as, path);
     PascalABCCompiler.NetHelper.NetHelper.init_namespaces(_as);
     List<string> namespaces = new List<string>();
     namespaces.AddRange(PascalABCCompiler.NetHelper.NetHelper.GetNamespaces(_as));
     InterfaceUnitScope unit_scope = null;
     cur_scope = unit_scope= new InterfaceUnitScope(new SymInfo(_unit_module.unit_name.idunit_name.name, SymbolKind.Namespace,_unit_module.unit_name.idunit_name.name),null);
     this.cur_unit_file_name = _unit_module.file_name;
     //if (XmlDoc.LookupLocalizedXmlDocForUnitWithSources(_unit_module.file_name) != null)
     if (!add_doc_from_text)
     {
     	UnitDocCache.LoadWithSources(cur_scope,_unit_module.file_name);
     	//this.add_doc_from_text = false;
     }
     //add_standart_types_simple();
     Stack<Position> regions_stack = new Stack<Position>();
     if (CodeCompletionController.comp.CompilerOptions.CurrentProject != null && CodeCompletionController.comp.CompilerOptions.CurrentProject.ContainsSourceFile(_unit_module.file_name))
     {
     	IReferenceInfo[] refs = CodeCompletionController.comp.CompilerOptions.CurrentProject.References;
     	if (_unit_module.compiler_directives == null)
     		_unit_module.compiler_directives = new List<PascalABCCompiler.SyntaxTree.compiler_directive>();
     	foreach (IReferenceInfo ri in refs)
     	{
     		_unit_module.compiler_directives.Add
     			(new PascalABCCompiler.SyntaxTree.compiler_directive(new token_info("reference"),new token_info(ri.FullAssemblyName)));
     	}
     }
     if (_unit_module.compiler_directives != null)
     foreach (PascalABCCompiler.SyntaxTree.compiler_directive dir in _unit_module.compiler_directives)
     {
     	if (dir.Name.text.ToLower() == "reference")
         {
             try
             {
         		//System.Reflection.Assembly assm = System.Reflection.Assembly.LoadFrom(get_assembly_path(dir.Directive.text,_unit_module.file_name));
         		path = get_assembly_path(dir.Directive.text,_unit_module.file_name);
             	System.Reflection.Assembly assm = PascalABCCompiler.NetHelper.NetHelper.LoadAssembly(path);
         		PascalABCCompiler.NetHelper.NetHelper.init_namespaces(assm);
             	AssemblyDocCache.Load(assm, path);
             	namespaces.AddRange(PascalABCCompiler.NetHelper.NetHelper.GetNamespaces(assm));
             	unit_scope.AddReferencedAssembly(assm);
             }
             catch (Exception e)
             {
             	
             }
             //ns=new PascalABCCompiler.NetHelper.NetScope(unl,assm,tcst);
         }
         else
         if (dir.Name.text.ToLower() == "region")
         {
         	if (cur_scope.regions == null)
         		cur_scope.regions = new List<Position>();
             regions_stack.Push(new Position(dir.source_context.begin_position.line_num, dir.source_context.begin_position.column_num, dir.source_context.end_position.line_num, dir.source_context.end_position.column_num, dir.source_context.FileName, dir.Directive.text));	                   
         }
         else if (dir.Name.text.ToLower() == "endregion")
         {
         	if (regions_stack.Count > 0)
         	{
         		Position pos = regions_stack.Pop();
         		if (cur_scope.regions != null)
         		{
                     cur_scope.regions.Add(new Position(pos.line, pos.column-1, dir.source_context.end_position.line_num, dir.source_context.end_position.column_num, pos.file_name, pos.fold_text));
         		}
         	}
         }
     }
     ns_cache = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
     
     doc = new document(_unit_module.file_name);
     cur_scope.head_loc = get_location(_unit_module.unit_name); 
     cur_scope.file_name = _unit_module.file_name;
     cur_scope.loc = get_location(_unit_module);
     cur_scope.AddName(_unit_module.unit_name.idunit_name.name,cur_scope);
     if (add_doc_from_text && this.converter.controller.docs != null && this.converter.controller.docs.ContainsKey(_unit_module.unit_name))
 		cur_scope.AddDocumentation(this.converter.controller.docs[_unit_module.unit_name]);
     entry_scope = cur_scope;
     //add_standart_types();
     if (_unit_module.unit_name.idunit_name.name == this.converter.controller.Parser.LanguageInformation.SystemUnitName)
     //add_system_unit();
     {
     	is_system_unit = true;
     	add_standart_types(entry_scope);
     }
     CodeCompletionController.comp_modules[_unit_module.file_name] = this.converter;
     _unit_module.interface_part.visit(this);
     foreach (string s in namespaces)
     {
     	if (!ns_cache.ContainsKey(s))
     	{
           NamespaceScope ns_scope = new NamespaceScope(s);
           entry_scope.AddName(s,ns_scope);
           ns_cache[s] = s;
     	}
     }
     //if (parse_only_interface)
     //    return;
     if (_unit_module.implementation_part != null)
         _unit_module.implementation_part.visit(this);
     if (_unit_module.initialization_part != null)
     {
     	SymScope tmp = cur_scope;
     	SymScope stmt_scope = new BlockScope(cur_scope);
 		cur_scope.AddName("$block_scope",stmt_scope);
 		stmt_scope.loc = get_location(_unit_module.initialization_part);
 		/*if (_unit_module.implementation_part != null)
 		{
 			cur_scope.loc.end_line_num = entry_scope.loc.end_line_num;
 			cur_scope.loc.end_column_num = entry_scope.loc.end_column_num;
 		}*/
 		cur_scope = stmt_scope;
     	_unit_module.initialization_part.visit(this);
     	cur_scope = tmp;
     }
     if (_unit_module.finalization_part != null)
     {
     	SymScope tmp = cur_scope;
     	SymScope stmt_scope = new BlockScope(cur_scope);
 		cur_scope.AddName("$block_scope",stmt_scope);
 		stmt_scope.loc = get_location(_unit_module.finalization_part);
 		/*if (_unit_module.implementation_part != null)
 		{
 			cur_scope.loc.end_line_num = entry_scope.loc.end_line_num;
 			cur_scope.loc.end_column_num =entry_scope.loc.end_column_num;
 		}*/
 		cur_scope = stmt_scope;
     	_unit_module.finalization_part.visit(this);
     	cur_scope = tmp;
     }
     
 }
Esempio n. 11
0
 /// <summary>
 /// Конструктор класса.
 /// </summary>
 /// <param name="begin_line_num">Номер строки начала фрагмента кода (нумерация начинается с 1).</param>
 /// <param name="begin_column_num">Номер колонки начала фрагмента кода (нумерация начинается с 1).</param>
 /// <param name="end_line_num">Номер строки конца фрагмента кода (нумерация начинается с 1).</param>
 /// <param name="end_column_num">Номер колонки конца фрагмента кода (нумерация начинается с 1)</param>
 /// <param name="doc">Документ, в котором расположен этот фрагмент кода.</param>
 public location(int begin_line_num, int begin_column_num, int end_line_num, int end_column_num, document doc)
 {
     _begin_line_num   = begin_line_num;
     _begin_column_num = begin_column_num;
     _end_line_num     = end_line_num;
     _end_column_num   = end_column_num;
     _doc = doc;
 }
Esempio n. 12
0
        public template_class(SyntaxTree.type_declaration type_decl, string name, common_namespace_node cnn, /*common_type_node ctn,location loc,*/ document doc, using_namespace_list unl)
        {
            _cnn       = cnn;
            _type_decl = type_decl;
            _name      = name;
            _doc       = doc;

            //(ssyy) using - список, по-видимому, можно только копировать, т.к. Николай его периодически чистит.
            _unl = new using_namespace_list();
            foreach (using_namespace un in unl)
            {
                _unl.AddElement(un);
            }
        }