Example #1
0
        public static DeleteRedundantBeginEnds Accept(procedure_definition pd)
        {
            var n = New;

            n.ProcessNode(pd);
            return(n);
        }
Example #2
0
        // Лучше запретить yield в вложенных функциях и в функциях со вложенными!
        // Запретить-запретить-запретить

        public override void visit(procedure_definition pd)
        {
            // var u = UpperNode(3);
            // В случае отсутствия формальных параметров
            if ((object)pd.proc_header.parameters == null)
            {
                base.visit(pd.proc_body);
                return;
            }

            formalParametersStack.Add(new Dictionary <string, string>());
            int currentLevel = formalParametersStack.Count - 1;

            foreach (var plist in pd.proc_header.parameters.params_list)
            {
                foreach (var id in plist.idents.idents)
                {
                    var paramName        = id.name;
                    var hoistedParamName = CapturedNamesHelper.MakeCapturedFormalParameterName(id.name);

                    formalParametersStack[currentLevel].Add(paramName, hoistedParamName);

                    // Захват
                    CollectedFormalParameters.Add(hoistedParamName, plist.vars_type);
                }
            }

            base.visit(pd.proc_body);

            formalParametersStack.RemoveAt(currentLevel);
        }
        public static MoveAllLocalDefsToLists Accept(procedure_definition pd)
        {
            var n = New;

            n.ProcessNode(pd);
            return(n);
        }
Example #4
0
 private void CollectFormalParams(procedure_definition pd, ISet <var_def_statement> collectedFormalParams)
 {
     if ((object)pd.proc_header.parameters != null)
     {
         collectedFormalParams.UnionWith(pd.proc_header.parameters.params_list.Select(tp => new var_def_statement(tp.idents, tp.vars_type)));
     }
 }
Example #5
0
 private void CollectFormalParamsNames(procedure_definition pd, ISet <string> collectedFormalParamsNames)
 {
     if ((object)pd.proc_header.parameters != null)
     {
         collectedFormalParamsNames.UnionWith(pd.proc_header.parameters.params_list.SelectMany(tp => tp.idents.idents).Select(id => id.name));
     }
 }
        public static procedure_definition ConvertLambdaNodeToProcDefNode(function_lambda_definition functionLambdaDef)
        {
            procedure_definition procDef = null;

            if (functionLambdaDef.return_type == null)
            {
                procDef = SyntaxTreeNodesConstructor.CreateProcedureDefinitionNode(new method_name(null, null, new ident(functionLambdaDef.lambda_name, functionLambdaDef.source_context), null),
                                                                                   functionLambdaDef.formal_parameters,
                                                                                   false,
                                                                                   false,
                                                                                   functionLambdaDef.proc_body,
                                                                                   functionLambdaDef.source_context);
            }
            else
            {
                procDef = SyntaxTreeNodesConstructor.CreateFunctionDefinitionNode(new method_name(null, null, new ident(functionLambdaDef.lambda_name), null),
                                                                                  functionLambdaDef.formal_parameters,
                                                                                  false,
                                                                                  false,
                                                                                  functionLambdaDef.proc_body,
                                                                                  functionLambdaDef.return_type,
                                                                                  functionLambdaDef.source_context);
            }
            procDef.proc_header.name.meth_name.source_context = procDef.proc_header.source_context;
            functionLambdaDef.proc_definition = procDef;
            return(procDef);
        }
        public static HashSet <string> NamesToRename(procedure_definition pd)
        {
            var v = new CollectNamesInIsVarVisitor();

            v.ProcessNode(pd);
            return(v.NamesInIsVars);
        }
Example #8
0
        public static procedure_definition BuildShortFuncDefinition(formal_parameters fp, procedure_attributes_list att, method_name name, type_definition result, expression ex, SourceContext headsc)
        {
            var ff = new function_header(fp, att, name, null, result, headsc);
            procedure_definition pd = BuildShortProcFuncDefinition(ff, new assign("Result", ex, ex.source_context));

            return(pd);
        }
            public static procedure_definition CreateFunctionDefinitionNode(method_name methName, formal_parameters formalPars, bool ofObject, bool classKeyword, statement procBody, type_definition returnType, SourceContext sc)
            {
                procedure_definition procDef = new procedure_definition();

                function_header procHeader = new function_header();

                procHeader.name           = methName;
                procHeader.source_context = sc;
                if (procHeader.name.meth_name is template_type_name)
                {
                    procHeader.template_args = (procHeader.name.meth_name as template_type_name).template_args;
                    ident id = new ident(procHeader.name.meth_name.name);
                    procHeader.name.meth_name = id;
                }
                procHeader.parameters    = formalPars;
                procHeader.of_object     = ofObject;
                procHeader.class_keyword = classKeyword;
                procHeader.return_type   = returnType;

                statement_list stmtList = new statement_list();

                stmtList.subnodes.Add(procBody);

                block bl = new block(null, null);

                bl.program_code = stmtList;

                procDef.proc_header = procHeader;
                procDef.proc_body   = (proc_block)bl;

                return(procDef);
            }
 public override void visit(procedure_definition _procedure_definition)
 {
     visit_node(_procedure_definition.proc_header);
     if (_procedure_definition.proc_body is block)
     {
         visit_node(_procedure_definition.proc_body as block);
     }
 }
        public procedure_definition lambda(function_lambda_definition _function_lambda_definition)
        {
            procedure_definition _func_def     = new procedure_definition();
            method_name          _method_name1 = new method_name(null, null, new ident(_function_lambda_definition.lambda_name), null);
            //parsertools.create_source_context(_method_name1, _method_name1.meth_name, _method_name1.meth_name);
            function_header _function_header1 = new function_header();

            object rt1 = new object();

            _function_header1.name = _method_name1;
            if (_function_header1.name.meth_name is template_type_name)
            {
                _function_header1.template_args = (_function_header1.name.meth_name as template_type_name).template_args;
                ident id = new ident(_function_header1.name.meth_name.name);
                //parsertools.create_source_context(id, _function_header1.name.meth_name, _function_header1.name.meth_name);
                _function_header1.name.meth_name = id;
            }

            formal_parameters fps = new PascalABCCompiler.SyntaxTree.formal_parameters();

            _function_header1.parameters = _function_lambda_definition.formal_parameters;//fps;

            /*SyntaxTree.named_type_reference _named_type_reference = new SyntaxTree.named_type_reference();
             * SyntaxTree.ident idtype = new SyntaxTree.ident("object");
             * _named_type_reference.source_context = idtype.source_context;
             * _named_type_reference.names.Add(idtype);
             * rt1 = _named_type_reference;
             * _function_header1.return_type = (SyntaxTree.type_definition)_named_type_reference;*/
            _function_header1.return_type = _function_lambda_definition.return_type;

            _function_header1.of_object     = false;
            _function_header1.class_keyword = false;
            token_info _token_info = new token_info("function");
            //_token_info.source_context = parsertools.GetTokenSourceContext();
            //parsertools.create_source_context(_function_header1, _token_info, _token_info);

            block          _block1 = new block(null, null);
            statement_list sl1     = new statement_list();

            sl1.subnodes.Add(_function_lambda_definition.proc_body);
            _block1.program_code  = sl1;
            _func_def.proc_header = _function_header1;
            _func_def.proc_body   = (proc_block)_block1;
            if (_function_lambda_definition.defs != null)
            {
                if (((block)_func_def.proc_body).defs == null)
                {
                    ((block)_func_def.proc_body).defs = new declarations();
                }
                for (int l = 0; l < _function_lambda_definition.defs.Count; l++)
                {
                    ((block)_func_def.proc_body).defs.defs.Add(_function_lambda_definition.defs[l] as procedure_definition);
                }
            }
            _function_lambda_definition.proc_definition = _func_def;
            //parsertools.create_source_context(_func_def, _function_header1, _function_header1);
            return(_func_def);
        }
Example #12
0
        private procedure_definition get_constructor_declaration(ICSharpCode.NRefactory.Ast.ConstructorDeclaration method)
        {
            procedure_definition proc = new procedure_definition();

            proc.proc_header    = get_constructor_header(method);
            proc.proc_body      = get_body(method.Body);
            proc.source_context = new SourceContext(method.StartLocation.Line, method.StartLocation.Column, method.Body.EndLocation.Line, method.Body.EndLocation.Column);
            return(proc);
        }
Example #13
0
        public override void visit(procedure_definition pd)
        {
            // frninja

            // Classification
            ISet <string> CollectedLocalsNames       = new HashSet <string>();
            ISet <string> CollectedFormalParamsNames = new HashSet <string>();
            ISet <string> CollectedClassFieldsNames  = new HashSet <string>();
            ISet <string> CollectedUnitGlobalsNames  = new HashSet <string>();

            ISet <var_def_statement> CollectedLocals       = new HashSet <var_def_statement>();
            ISet <var_def_statement> CollectedFormalParams = new HashSet <var_def_statement>();

            // Map from ident idName -> captured ident idName
            IDictionary <string, string> CapturedLocalsNamesMap       = new Dictionary <string, string>();
            IDictionary <string, string> CapturedFormalParamsNamesMap = new Dictionary <string, string>();

            var dld = new DeleteAllLocalDefs(); // mids.vars - все захваченные переменные

            pd.visit(dld);                      // Удалить в локальных и блочных описаниях этой процедуры все переменные и вынести их в отдельный список var_def_statement

            // frninja 08/12/15
            bool isInClassMethod;

            // Collect locals
            CollectedLocals.UnionWith(dld.LocalDeletedDefs);
            CollectedLocalsNames.UnionWith(dld.LocalDeletedDefs.SelectMany(vds => vds.vars.idents).Select(id => id.name));
            // Collect formal params
            CollectFormalParams(pd, CollectedFormalParams);
            CollectFormalParamsNames(pd, CollectedFormalParamsNames);
            // Collect class fields
            CollectClassFieldsNames(pd, CollectedClassFieldsNames, out isInClassMethod);

            // Collect unit globals
            CollectUnitGlobalsNames(pd, CollectedUnitGlobalsNames);

            // Create maps :: idName -> captureName
            CreateCapturedLocalsNamesMap(CollectedLocalsNames, CapturedLocalsNamesMap);
            CreateCapturedFormalParamsNamesMap(CollectedFormalParamsNames, CapturedFormalParamsNamesMap);

            // AHAHA test!
            ReplaceCapturedVariablesVisitor rcapVis = new ReplaceCapturedVariablesVisitor(
                CollectedLocalsNames,
                CollectedFormalParamsNames,
                CollectedClassFieldsNames,
                new HashSet <string>(),
                new HashSet <string>(),
                CollectedUnitGlobalsNames,
                CapturedLocalsNamesMap,
                CapturedFormalParamsNamesMap,
                isInClassMethod
                );

            // Replace
            (pd.proc_body as block).program_code.visit(rcapVis);
        }
Example #14
0
        private void CollectUnitGlobalsNames(procedure_definition pd, ISet <string> collectedUnitGlobalsName)
        {
            var cu = UpperTo <compilation_unit>();

            if ((object)cu != null)
            {
                var ugVis = new CollectUnitGlobalsVisitor();
                cu.visit(ugVis);
                // Collect
                collectedUnitGlobalsName.UnionWith(ugVis.CollectedGlobals.Select(id => id.name));
            }
        }
Example #15
0
        public override void visit(procedure_definition p)
        {
            if (PrintInfo)
            {
                Console.WriteLine(" " + p.proc_header.name.meth_name);
            }

            var ld = new FindLocalDefsVisitor();

            p.visit(ld);

            base.visit(p);
        }
        public override void visit(procedure_definition pd)
        {
            //this.CurrentMethod = pd;

            MethodsStack.Push(pd);

            HasYields = false;

            base.visit(pd);
            pd.has_yield = HasYields;

            if (pd.has_yield) // SSM bug fix #219
            {
                var ee = pd.proc_body as block;
                if (ee != null)
                {
                    var FirstTypeDeclaration = ee.defs.DescendantNodes().OfType <type_declarations>();
                    if (FirstTypeDeclaration.Count() > 0)
                    {
                        throw new SyntaxVisitorError("FUNCTIONS_WITH_YIELDS_CANNOT_CONTAIN_LOCAL_TYPE_DEFINITIONS", FirstTypeDeclaration.First().source_context);
                    }
                }
            }

            var innerPds = pd.DescendantNodes().OfType <procedure_definition>();

            if (pd.has_yield && innerPds.Count() > 0 ||
                innerPds.Where(npd => npd.has_yield).Count() > 0)
            {
                // Есть yield и вложенные - плохо
                // Или нет yield но есть вложенные с yield
                throw new SyntaxVisitorError("FUNCTIONS_WITH_YIELDS_CANNOT_CONTAIN_NESTED_SUBROUTINES", pd.source_context);
            }

            if (pd.has_yield && pd.DescendantNodes().OfType <try_stmt>().Count() > 0)
            {
                throw new SyntaxVisitorError("FUNCTIONS_WITH_YIELDS_CANNOT_CONTAIN_TRY_EXCEPT_FINALLY", pd.source_context);
            }

            if (pd.has_yield && pd.DescendantNodes().OfType <lock_stmt>().Count() > 0)
            {
                throw new SyntaxVisitorError("FUNCTIONS_WITH_YIELDS_CANNOT_CONTAIN_LOCK", pd.source_context);
            }

            HasYields = false;

            MethodsStack.Pop();

            //this.CurrentMethod = null;
        }
Example #17
0
        public void visit_yield_helper(syntax_tree_node yn)
        {
            procedure_definition pd = null;

            if (MethodsStack.Count > 0)
            {
                pd = MethodsStack.Peek();
            }

            if (pd == null)
            {
                throw new SyntaxVisitorError("ONLY_FUNCTIONS_CAN_CONTAIN_YIELDS", yn.source_context);
            }

            var fh = (pd.proc_header as function_header);

            if (fh == null)
            {
                throw new SyntaxVisitorError("ONLY_FUNCTIONS_CAN_CONTAIN_YIELDS", pd.proc_header.source_context);
            }
            var seqt = fh.return_type as sequence_type;

            if (seqt == null)
            {
                throw new SyntaxVisitorError("YIELD_FUNC_MUST_RETURN_SEQUENCE", fh.source_context);
            }
            if (seqt.elements_type is procedure_header || seqt.elements_type is function_header)
            {
                throw new SyntaxVisitorError("YIELD_FUNC_CANNOT_RETURN_SEQUENCE_OF_ANONYMOUS_DELEGATES", fh.source_context);
            }
            var pars = fh.parameters;

            if (pars != null)
            {
                foreach (var ps in pars.params_list)
                {
                    if (ps.param_kind != parametr_kind.none)
                    {
                        throw new SyntaxVisitorError("FUNCTIONS_WITH_YIELDS_CANNOT_CONTAIN_VAR_CONST_PARAMS_MODIFIERS", pars.source_context);
                    }
                    if (ps.inital_value != null)
                    {
                        throw new SyntaxVisitorError("FUNCTIONS_WITH_YIELDS_CANNOT_CONTAIN_DEFAULT_PARAMETERS", pars.source_context);
                    }
                }
            }

            HasYields = true;
        }
Example #18
0
        public override void visit(procedure_definition procedureDefinition)
        {
            bool isConstrainted = procedureDefinition.proc_header.where_defs != null &&
                                  procedureDefinition.proc_header.where_defs.defs.Any(x => x is where_typeclass_constraint);

            if (!isConstrainted)
            {
                return;
            }

            var usedTypeclasses = procedureDefinition.proc_header.where_defs.
                                  defs.OfType <where_typeclass_constraint>()
                                  .Select(x => x.restriction.name).ToList();

            restrictedFunctions.Add(procedureDefinition.proc_header.name.meth_name.name,
                                    usedTypeclasses);
        }
Example #19
0
        private void CollectClassFieldsNames(procedure_definition pd, ISet <string> collectedFields, out bool isInClassMethod)
        {
            isInClassMethod = false;

            ident className = null;

            if ((object)pd.proc_header.name.class_name != null)
            {
                // Объявление вне класса его метода
                className = pd.proc_header.name.class_name;
            }
            else
            {
                // Объявление функции в классе?
                var classDef = UpperNode(3) as class_definition;
                if ((object)(UpperNode(3) as class_definition) != null)
                {
                    var td = UpperNode(4) as type_declaration;
                    if ((object)td != null)
                    {
                        className = td.type_name;
                    }
                }
            }

            if ((object)className != null)
            {
                isInClassMethod = true;

                CollectClassFieldsVisitor fieldsVis = new CollectClassFieldsVisitor(className);
                var cu = UpperTo <compilation_unit>();
                if ((object)cu != null)
                {
                    cu.visit(fieldsVis);
                    // Collect
                    collectedFields.UnionWith(fieldsVis.CollectedFields.Select(id => id.name));
                }
            }
        }
        public override void visit(procedure_definition pd)               // три вида ПИ, которые надо учитывать
        {
            NamesToRename = CollectNamesInIsVarVisitor.NamesToRename(pd); // Это - акцент внимания
            if (NamesToRename.Count == 0)
            {
                return; // nothing top do
            }
            PushNamespace(pd);

            if (pd.proc_header.parameters != null)
            {
                var allnames = pd.proc_header.parameters.params_list.SelectMany(tp => tp.idents.idents);
                foreach (var name in allnames)
                {
                    AddNameNewName(name, null); // null означает, что переименовывать не надо
                }
            }

            base.visit(pd);
            PopNamespace();
            NamesToRename = null;
        }
 public void add_lambda(object lr1, procedure_definition _procedure_definition)
 {
     if (pascalABC_lambda_definitions.Count > 0)//tasha 16.04.2010
     {
         block _block = (block)lr1;
         if (_block.defs == null)
         {
             _block.defs = new declarations();
         }
         for (int i = 0; i < pascalABC_lambda_definitions.Count; i++)
         {
             _block.defs.defs.Add(lambda((function_lambda_definition)pascalABC_lambda_definitions[i]));
         }
         pascalABC_lambda_definitions.Clear();
         _procedure_definition.proc_body = (proc_block)_block;
     }
     else
     {
         //////////////////////////tasha 16.04.2010
         _procedure_definition.proc_body = (proc_block)lr1;
     }
 }
Example #22
0
        public override void visit(procedure_definition pd)
        {
            hasYields = false;
            if (pd.proc_header is function_header)
            {
                mids = new FindMainIdentsVisitor();
            }

            base.visit(pd);

            if (!hasYields) // т.е. мы разобрали функцию и уже выходим. Это значит, что пока yield будет обрабатываться только в функциях. Так это и надо.
            {
                return;
            }

            var dld = new DeleteAllLocalDefs();          // mids.vars - все захваченные переменные

            pd.visit(dld);                               // Удалить в локальных и блочных описаниях этой процедуры все переменные и вынести их в отдельный список var_def_statement

            mids.vars.Except(dld.LocalDeletedDefsNames); // параметры остались. Их тоже надо исключать - они и так будут обработаны
            // В результате работы в mids.vars что-то осталось. Это не локальные переменные и с ними непонятно что делать

            LoweringVisitor.Accept(pd);

            var cfa = new ConstructFiniteAutomata((pd.proc_body as block).program_code);

            cfa.Transform();
            (pd.proc_body as block).program_code = cfa.res;

            // Конструируем определение класса
            var cct = GenClassesForYield(pd, dld.LocalDeletedDefs); // все удаленные описания переменных делаем описанием класса

            UpperNodeAs <declarations>().InsertBefore(pd, cct);

            mids = null; // вдруг мы выйдем из процедуры, не зайдем в другую, а там - оператор! Такого конечно не может быть
        }
        public override void visit(yield_node yn)
        {
            if (yn.ex is function_lambda_definition)
            {
                syntax_tree_node sn = yn;
                do
                {
                    sn = sn.Parent;
                } while (sn != null && !(sn is procedure_definition));
                procedure_definition pd = sn as procedure_definition;

                if (sn == null)
                {
                    // этого не будет
                }
                var fh = pd.proc_header as function_header;
                if (fh == null)
                {
                    // этого тоже не будет
                }
                var sq = fh.return_type as sequence_type;
                if (sq == null)
                {
                    // и этого не будет
                }

                var lst   = new List <statement>();
                var newid = new ident(CreateNameForLambdaInYield(), yn.ex.source_context);
                var vs    = new var_statement(newid, sq.elements_type, yn.ex);
                vs.source_context = yn.ex.source_context;
                var newyn = new yield_node(newid, newid.source_context);
                lst.Add(vs);
                lst.Add(newyn);
                ReplaceStatementUsingParent(yn, lst);
            }
        }
Example #24
0
		public override void visit(procedure_definition _procedure_definition)
		{
			executer.visit(_procedure_definition);
			if (_procedure_definition.proc_header != null)
				this.visit((dynamic)_procedure_definition.proc_header);
			if (_procedure_definition.proc_body != null)
				this.visit((dynamic)_procedure_definition.proc_body);
			if (_procedure_definition.attributes != null)
				this.visit((dynamic)_procedure_definition.attributes);
		}
        public property_accessors NewPropertySpecifiersWrite(ident tkWrite, ident opt_identifier, procedure_definition pr, statement st, property_accessors property_specifiers, LexLocation loc)
        {
            var nnpsw = property_specifiers;

            if (nnpsw == null)
            {
                nnpsw = new property_accessors();
            }
            if (st != null)
            {
                nnpsw.write_accessor = new write_accessor_name(opt_identifier, pr, st, tkWrite.source_context.Merge(st.source_context));
            }
            else if (opt_identifier != null)
            {
                nnpsw.write_accessor = new write_accessor_name(opt_identifier, pr, st, tkWrite.source_context.Merge(opt_identifier.source_context));
            }
            else
            {
                nnpsw.write_accessor = new write_accessor_name(opt_identifier, pr, st, tkWrite.source_context);
            }
            nnpsw.source_context = loc;
            return(nnpsw);
        }
        public property_accessors NewPropertySpecifiersRead(ident tkRead, ident opt_identifier, procedure_definition pr, expression ex, property_accessors property_specifiers, LexLocation loc)
        {
            var nnps = property_specifiers;

            if (nnps == null)
            {
                nnps = new property_accessors();
            }
            if (opt_identifier != null && opt_identifier.name.ToLower() == "write")
            {
                nnps.read_accessor  = new read_accessor_name(null, null, null);
                nnps.write_accessor = new write_accessor_name(null, null, null);
                nnps.read_accessor.source_context  = tkRead.source_context;
                nnps.write_accessor.source_context = opt_identifier.source_context;
            }
            else
            {
                if (ex != null)
                {
                    nnps.read_accessor = new read_accessor_name(opt_identifier, pr, ex, tkRead.source_context.Merge(ex.source_context));
                }
                else if (opt_identifier != null)
                {
                    nnps.read_accessor = new read_accessor_name(opt_identifier, pr, ex, tkRead.source_context.Merge(opt_identifier.source_context));
                }
                else
                {
                    nnps.read_accessor = new read_accessor_name(opt_identifier, pr, ex, tkRead.source_context);
                }
            }
            nnps.source_context = loc;
            return(nnps);
        }
		public virtual void visit(procedure_definition _procedure_definition)
		{
			DefaultVisit(_procedure_definition);
		}
Example #28
0
		public virtual void visit(procedure_definition _procedure_definition)
		{
		}
Example #29
0
 public override void visit(procedure_definition _procedure_definition)
 {
 }
 public procedure_definition_info(common_namespace_node _nspace,
                                  procedure_definition _proc)
 {
     nspace = _nspace;
     proc   = _proc;
 }
Example #31
0
 public static void Accept(procedure_definition pd)
 {
     New.ProcessNode(pd);
 }
Example #32
0
        public static type_declaration BuildClassWithOneMethod(string class_name, List <ident> names, List <type_definition> types, procedure_definition pd)
        {
            var formnames = names.Select(x => new ident("form" + x.name)).ToList();

            var cm1 = BuildClassFieldsSection(names, types);
            var cm2 = BuildSimpleConstructorSection(names, formnames, types);
            var cm3 = BuildOneMemberSection(pd);

            return(new type_declaration(class_name, BuildClassOrRecordDefinition(true, cm1, cm2, cm3), BuildGenSC));
        }
Example #33
0
 public virtual void visit(procedure_definition _procedure_definition)
 {
     DefaultVisit(_procedure_definition);
 }
Example #34
0
		public virtual void post_do_visit(procedure_definition _procedure_definition)
		{
		}
Example #35
0
		public override void visit(procedure_definition _procedure_definition)
		{
			DefaultVisit(_procedure_definition);
			pre_do_visit(_procedure_definition);
			visit(procedure_definition.proc_header);
			visit(procedure_definition.proc_body);
			post_do_visit(_procedure_definition);
		}