public override void visit(statement_list stmtList)
        {
            var stl = new statements_list(_visitor.get_location(stmtList),
                                          _visitor.get_location_with_check(stmtList.left_logical_bracket),
                                          _visitor.get_location_with_check(stmtList.right_logical_bracket));
            _visitor.convertion_data_and_alghoritms.statement_list_stack_push(stl);

            var newTreeNode = new CapturedVariablesTreeNodeBlockScope(_currentTreeNode, stl.Scope.ScopeNum, stmtList);

            if (_rootNode == null)
            {
                _rootNode = newTreeNode;
            }
            if (_currentTreeNode != null)
            {
                _currentTreeNode.ChildNodes.Add(newTreeNode);
            }
            _currentTreeNode = newTreeNode;

            _scopesCapturedVarsNodesDictionary.Add(stl.Scope.ScopeNum, _currentTreeNode);

            if (stmtList.subnodes != null)
            {
                foreach (var stmt in stmtList.subnodes)
                {
                    ProcessNode(stmt);
                }
            }

            _visitor.convertion_data_and_alghoritms.statement_list_stack.pop();

            _currentTreeNode = _currentTreeNode.ParentNode;
        }
예제 #2
0
 public static statement_list BuildSimpleAssignList(List<ident> lnames, List<ident> rnames)
 {
     var sl = new statement_list();
     for (int i = 0; i < lnames.Count; i++)
         sl.Add( new assign(lnames[i], rnames[i]));
     return sl;
 }
 public override void visit(statement_list stmtList)
 {
     var stl = new statements_list(syntaxTreeVisitor.get_location(stmtList),
                                   syntaxTreeVisitor.get_location_with_check(stmtList.left_logical_bracket),
                                   syntaxTreeVisitor.get_location_with_check(stmtList.right_logical_bracket));
     syntaxTreeVisitor.convertion_data_and_alghoritms.statement_list_stack_push(stl);
     if (stmtList.subnodes != null)
         foreach (var stmt in stmtList.subnodes)
             ProcessNode(stmt);
     syntaxTreeVisitor.convertion_data_and_alghoritms.statement_list_stack.pop();    
 }
예제 #4
0
 public override void visit(statement_list _statement_list)
 {
     if (_statement_list == null || _statement_list.source_context == null) return;
     IBaseScope tmp = cur_scope;
     cur_scope = entry_scope.FindScopeByLocation(_statement_list.source_context.begin_position.line_num, _statement_list.source_context.begin_position.column_num);
     if (cur_scope == null)
         cur_scope = tmp;
     foreach (statement stmt in _statement_list.subnodes)
         stmt.visit(this);
     cur_scope = tmp;
 }
예제 #5
0
 public virtual statement_list GetStatements(object _object)
 {
     statement_list _statement_list;
     if (_object is statement_list)
         _statement_list = _object as statement_list;
     else
     {
         _statement_list = new statement_list();
         if (_object is statement)
             _statement_list.subnodes.Add(_object as statement);
         else
             _statement_list.subnodes.Add(new empty_statement());
     }
     return _statement_list;
 }
        public override void visit(statement_list stlist)
        {
            ++CurrentLevel;

            if (BlockNamesStack.Count <= CurrentLevel)
            {
                // Создаем отображение для имен текущего уровня вложенности мини-пространства имен
                BlockNamesStack.Add(new Dictionary<string, string>());
            }

            //base.visit(stlist);
            for (var i = 0; i < stlist.list.Count; ++i)
                ProcessNode(stlist.list[i]);

            BlockNamesStack.RemoveAt(BlockNamesStack.Count - 1);

            --CurrentLevel;
        }
		public void write_statement_list(statement_list _statement_list)
		{
			write_statement(_statement_list);
			if (_statement_list.subnodes == null)
			{
				bw.Write((byte)0);
			}
			else
			{
				bw.Write((byte)1);
				bw.Write(_statement_list.subnodes.Count);
				for(Int32 ssyy_i = 0; ssyy_i < _statement_list.subnodes.Count; ssyy_i++)
				{
					if (_statement_list.subnodes[ssyy_i] == null)
					{
						bw.Write((byte)0);
					}
					else
					{
						bw.Write((byte)1);
						_statement_list.subnodes[ssyy_i].visit(this);
					}
				}
			}
			if (_statement_list.left_logical_bracket == null)
			{
				bw.Write((byte)0);
			}
			else
			{
				bw.Write((byte)1);
				_statement_list.left_logical_bracket.visit(this);
			}
			if (_statement_list.right_logical_bracket == null)
			{
				bw.Write((byte)0);
			}
			else
			{
				bw.Write((byte)1);
				_statement_list.right_logical_bracket.visit(this);
			}
		}
        /*
         * // Scope Level 0
         * begin 
         *   var x = value; // Name in Scope Level 0
         *   // Scope Level 1
         *   begin
         *     var x = value; // Name in Scope Level 1 <-- REDEFENITION ERROR, x defined at Level 0
         *     
         *     var y = value;
         *     var y = value2; // Name in Scope Level 1 <-- REDEFINITION ERROR, y defined at Level 1
         *     
         *     // Scope Level 2
         *     begin
         *       var z = y; // Name in Scope Level 2
         *     end
         *     // Scope Level 2
         *     begin
         *       var z = value; // Name in Scope Level 2
         *     end
         *   end
         * 
         * end
        */

        public override void visit(statement_list stlist)
        {
            ++CurrentLevel;

            if (BlockNamesStack.Count <= CurrentLevel)
            {
                // Создаем множество имен для текущего уровня вложенности мини-пространства имен
                BlockNamesStack.Add(new HashSet<string>());
            }


            base.visit(stlist);
            //for (var i = 0; i < stlist.list.Count; ++i)
            //    ProcessNode(stlist.list[i]);

            BlockNamesStack.RemoveAt(BlockNamesStack.Count - 1);

            --CurrentLevel;
        }
예제 #9
0
        public override void visit(while_node wn)
        {
            ProcessNode(wn.statements);
            var gt1 = new goto_statement(newLabelName());
            var gt2 = new goto_statement(newLabelName());
            var gt3 = new goto_statement(newLabelName());

            var if0 = new if_node(wn.expr, gt1, null);
            var lb3 = new labeled_statement(gt3.label, if0);
            var lb1 = new labeled_statement(gt1.label, wn.statements);
            var lb2 = new labeled_statement(gt2.label, new empty_statement());

            var stl = new statement_list(lb3, gt2, lb1, gt3, lb2);

            Replace(wn, stl);
            // в declarations ближайшего блока добавить описание labels
            block bl = listNodes.FindLast(x => x is block) as block;

            var ld = new label_definitions(gt1.label, gt2.label, gt3.label);
            bl.defs.Add(ld);
        }
예제 #10
0
        public override void Exit(syntax_tree_node st)
        {
            var sts = st as statement;

            if (sts != null && !(sts is statement_list) && !(sts is case_variant) && !(UpperNode() is statement_list))
            {
                // Одиночный оператор
                var stl = new statement_list(sts, st.source_context);
                Replace(sts, stl);
            }

            
            var lst = st as labeled_statement;

            if (lst != null && !(lst.to_statement is statement_list) && !(lst.to_statement is case_variant))
            {
                // Одиночный оператор
                var stl = new statement_list(sts, st.source_context);
                Replace(lst.to_statement, stl);
            }
            
            base.Exit(st);
        }
예제 #11
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public program_body(uses_list _used_units,declarations _program_definitions,statement_list _program_code,using_list _using_list)
		{
			this._used_units=_used_units;
			this._program_definitions=_program_definitions;
			this._program_code=_program_code;
			this._using_list=_using_list;
		}
        /*public override void Enter(syntax_tree_node st)
        {
            base.Enter(st);
            countNodesVisited++;

            // сокращение обходимых узлов. Как сделать фильтр по тем узлам, которые необходимо обходить? Например, все операторы (без выражений и описаний), все описания (без операторов)
            if (st.GetType()==typeof(assign) || st.GetType()==typeof(var_def_statement) || st is procedure_call || st is procedure_header || st is expression)
            {
                visitNode = false; // фильтр - куда не заходить 
            }
        }*/

        /*public override void visit(class_members cm)
        {
            foreach (var decl in cm.members)
            {
                if (decl is procedure_header || decl is procedure_definition)
                    decl.visit(this);
            }
            base.visit(cm);
        }*/

        type_declarations GenClassesForYield(procedure_definition pd,
            IEnumerable<var_def_statement> fields, // локальные переменные
            IDictionary<string, string> localsMap, // отображение для захваченных имен локальных переменных
            IDictionary<string, string> formalParamsMap//, // отображение для захваченных имен формальных параметров
            //IDictionary<var_def_statement, var_def_statement> localsCloneMap // отображение для оберток локальных переменных 
            ) 
        {
            var fh = (pd.proc_header as function_header);
            if (fh == null)
                throw new SyntaxError("Only functions can contain yields", "", pd.proc_header.source_context, pd.proc_header);
            var seqt = fh.return_type as sequence_type;
            if (seqt == null)
                throw new SyntaxError("Functions with yields must return sequences", "", fh.return_type.source_context, fh.return_type);

            // Теперь на месте функции генерируем класс

            // Захваченные локальные переменные
            var cm = class_members.Public;
            var capturedFields = fields.Select(vds =>
                                    {
                                        ident_list ids = new ident_list(vds.vars.idents.Select(id => new ident(localsMap[id.name])).ToArray());
                                        if (vds.vars_type == null) //&& vds.inital_value != null)
                                        {
                                            if (vds.inital_value != null)
                                            {
                                                //return new var_def_statement(ids, new yield_unknown_expression_type(localsCloneMap[vds], varsTypeDetectorHelper), null);
                                                return new var_def_statement(ids, new yield_unknown_expression_type(vds), null); // SSM - убрал localsCloneMap[vds] - заменил на vds - не знаю, зачем вообще это отображение делалось - всё равно оно было тождественным!!!
                                            }
                                            else
                                            {
                                                throw new SyntaxVisitorError("Variable defenition without type and value!",vds.source_context); // SSM - быть такого не может - грамматика не пропустит
                                            }
                                        }
                                        else
                                        {
                                            return new var_def_statement(ids, vds.vars_type, null);
                                        }
                                        
                                        //return new var_def_statement(ids, vds.vars_type, vds.inital_value);
                                    });

            foreach (var m in capturedFields)
                cm.Add(m);

            // Параметры функции
            List<ident> lid = new List<ident>();
            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);
                    //var_def_statement vds = new var_def_statement(ps.idents, ps.vars_type);
                    ident_list ids = new ident_list(ps.idents.list.Select(id => new ident(formalParamsMap[id.name])).ToArray());
                    var_def_statement vds = new var_def_statement(ids, ps.vars_type);
                    cm.Add(vds); // все параметры функции делаем полями класса
                    //lid.AddRange(vds.vars.idents);
                    lid.AddRange(ps.idents.list);
                }

            var stels = seqt.elements_type;

            var iteratorClassName = GetClassName(pd);

            // frninja 08/18/15 - Для захвата self
            if (iteratorClassName != null)
            {
                // frninja 20/04/16 - поддержка шаблонных классов
                var iteratorClassRef = CreateClassReference(iteratorClassName);

                cm.Add(new var_def_statement(YieldConsts.Self, iteratorClassRef));
            }

            var GetEnumeratorBody = new statement_list();

            // Системные поля и методы для реализации интерфейса IEnumerable
            cm.Add(new var_def_statement(YieldConsts.State, "integer"),
                new var_def_statement(YieldConsts.Current, stels),
                procedure_definition.EmptyDefaultConstructor,
                new procedure_definition("Reset"),
                new procedure_definition("MoveNext", "boolean", pd.proc_body),
                new procedure_definition("System.Collections.IEnumerator.get_Current", "object", new assign("Result", YieldConsts.Current)),
                //new procedure_definition("System.Collections.IEnumerable.GetEnumerator", "System.Collections.IEnumerator", new assign("Result", "Self"))
                new procedure_definition("System.Collections.IEnumerable.GetEnumerator", "System.Collections.IEnumerator", GetEnumeratorBody)
                );

            // frninja 20/04/16 - поддержка шаблонных классов
            var yieldClassName = NewYieldClassName();
            var yieldClassHelperName = yieldClassName + "Helper";

            var className = this.CreateHelperClassName(yieldClassName, iteratorClassName, pd);
            var classNameHelper = this.CreateHelperClassName(yieldClassHelperName, iteratorClassName, pd);
            

            var interfaces = new named_type_reference_list("System.Collections.IEnumerator", "System.Collections.IEnumerable");

            // frninja 24/04/16 - поддержка шаблонных классов
            //var td = new type_declaration(classNameHelper, this.CreateHelperClassDefinition(classNameHelper, pd, interfaces, cm));
                //SyntaxTreeBuilder.BuildClassDefinition(interfaces, cm));

            // Изменение тела процедуры
            

            // frninja 20/04/16 - поддержка шаблонных классов
            var stl = new statement_list(new var_statement("$res", new new_expr(this.CreateClassReference(className), new expression_list())));
            

            //stl.AddMany(lid.Select(id => new assign(new dot_node("$res", id), id)));
            stl.AddMany(lid.Select(id => new assign(new dot_node("$res", new ident(formalParamsMap[id.name])), id)));

            // frninja 08/12/15 - захват self
            if (iteratorClassName != null && !pd.proc_header.class_keyword)
            {
                stl.Add(new assign(new dot_node("$res", YieldConsts.Self), new ident("self")));
            }

            stl.Add(new assign("Result", "$res"));

            // New body
            pd.proc_body = new block(stl);

            if (iteratorClassName != null)
            {
                var cd = UpperTo<class_definition>();
                if (cd != null)
                {
                    // Если метод описан в классе 
                    // frninja 10/12/15 - заменить на function_header и перенести описание тела в declarations
                    Replace(pd, fh);
                    var decls = UpperTo<declarations>();
                    if (decls != null)
                    {
                        // frninja 12/05/16 - забыли копировать return
                        function_header nfh = ObjectCopier.Clone(fh);
                        //function_header nfh = new function_header();
                        //nfh.name = new method_name(fh.name.meth_name.name);

                        // Set className
                        nfh.name.class_name = iteratorClassName;
                        //nfh.parameters = fh.parameters;
                        //nfh.proc_attributes = fh.proc_attributes;
                        //nfh.return_type = fh.return_type;

                        procedure_definition npd = new procedure_definition(nfh, new block(stl));

                        // Update header
                        //pd.proc_header.className.class_name = GetClassName(pd);
                        // Add to decls
                        decls.Add(npd);
                    }
                }
            }

            // Второй класс

            var tpl = new template_param_list(stels);

            var IEnumeratorT = new template_type_reference("System.Collections.Generic.IEnumerator", tpl);

            var cm1 = cm.Add( //class_members.Public.Add(
                //procedure_definition.EmptyDefaultConstructor,
                new procedure_definition(new function_header("get_Current", stels), new assign("Result", YieldConsts.Current)),
                new procedure_definition(new function_header("GetEnumerator", IEnumeratorT), GetEnumeratorBody),
                new procedure_definition("Dispose")
            );


            // frninja 20/04/16 - поддержка шаблонных классов
            var interfaces1 = new named_type_reference_list(/*this.CreateClassReference(classNameHelper) as named_type_reference*/);
            var IEnumerableT = new template_type_reference("System.Collections.Generic.IEnumerable", tpl);

            interfaces1.Add(IEnumerableT).Add(IEnumeratorT);

            // frninja 24/04/16 - поддержка шаблонных классов

            // frninja 05/06/16 - фикс. Поддержка where секции
            var helperClassDefinition = this.CreateHelperClassDefinition(className, pd, interfaces1, cm1);
            helperClassDefinition.where_section = this.GetMethodWhereSection(pd);

            var td1 = new type_declaration(className, helperClassDefinition);
            //SyntaxTreeBuilder.BuildClassDefinition(interfaces1, cm1));


            var stl1 = new statement_list(new var_statement("$res", new new_expr(this.CreateClassReference(className), new expression_list())));
            

            stl1.AddMany(lid.Select(id => new assign(new dot_node("$res", new ident(formalParamsMap[id.name])), new ident(formalParamsMap[id.name]))));

            // Переприсваивание self 
            if (iteratorClassName != null && !pd.proc_header.class_keyword)
            {
                stl1.Add(new assign(new dot_node("$res", YieldConsts.Self), new ident(YieldConsts.Self)));
            }

            stl1.Add(new assign("Result", "$res"));


            GetEnumeratorBody.Add(new if_node(new bin_expr(new ident(YieldConsts.State), new int32_const(0), Operators.Equal),
                new assign("Result", "Self"),
                stl1));

            var cct = new type_declarations(/*td*/);
            cct.Add(td1);

            return cct;
        }
예제 #13
0
        public static procedure_definition BuildShortProcFuncDefinitionNoSC(procedure_header header, statement st)
        {
            var stlist = new statement_list(st, st.source_context);
            var b = new block(null, stlist, st.source_context);

            return new procedure_definition(header, b, true, BuildGenSC);
        }
예제 #14
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public try_stmt(statement_list _stmt_list,try_handler _handler)
		{
			this._stmt_list=_stmt_list;
			this._handler=_handler;
		}
 public ConstructFiniteAutomata(block bl)
 {
     this.stl = bl.program_code;
     defs = bl.defs;
 }
예제 #16
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public pair_type_stlist(type_definition _tn,statement_list _exprs)
		{
			this._tn=_tn;
			this._exprs=_exprs;
		}
예제 #17
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public try_stmt(statement_list _stmt_list,try_handler _handler,SourceContext sc)
		{
			this._stmt_list=_stmt_list;
			this._handler=_handler;
			source_context = sc;
		}
        public void Process(statement st)
        {
            if (!(st is yield_node || st is labeled_statement))
            {
                curStatList.Add(st);
            }
            if (st is yield_node)
            {
                var yn = st as yield_node;
                curState += 1;
                curStatList.AddMany(
                    new assign(Consts.Current, yn.ex),
                    new assign(Consts.State, curState),
                    new assign("Result", true),
                    new procedure_call("exit")
                );

                curStatList = new statement_list();
                case_variant cv = new case_variant(new expression_list(new int32_const(curState)), curStatList);
                cas.conditions.variants.Add(cv);
            }
            if (st is labeled_statement)
            {
                var ls = st as labeled_statement;
                curStatList = StatListAfterCase;
                curStatList.Add(new labeled_statement(ls.label_name));
                Process(ls.to_statement);
            }
        }
        /*public override void visit(class_members cm)
        {
            foreach (var decl in cm.members)
            {
                if (decl is procedure_header || decl is procedure_definition)
                    decl.visit(this);
            }
            base.visit(cm);
        }*/
        type_declarations GenClassesForYield(procedure_definition pd, IEnumerable<var_def_statement> fields,
            IDictionary<string, string> localsMap,
            IDictionary<string, string> formalParamsMap)
        {
            var fh = (pd.proc_header as function_header);
            if (fh == null)
                throw new SyntaxError("Only functions can contain yields", "", pd.proc_header.source_context, pd.proc_header);
            var seqt = fh.return_type as sequence_type;
            if (seqt == null)
                throw new SyntaxError("Functions with yields must return sequences", "", fh.return_type.source_context, fh.return_type);

            // Теперь на месте функции генерируем класс

            // Захваченные переменные
            var cm = class_members.Public;
            var capturedFields = fields.Select(vds =>
                                    {
                                        ident_list ids = new ident_list(vds.vars.idents.Select(id => new ident(localsMap[id.name])).ToArray());
                                        return new var_def_statement(ids, vds.vars_type, vds.inital_value);
                                    });

            foreach (var m in capturedFields)
                cm.Add(m);

            // Параметры функции
            List<ident> lid = new List<ident>();
            var pars = fh.parameters;
            if (pars != null)
                foreach (var ps in pars.params_list)
                {
                    if (ps.param_kind != parametr_kind.none)
                        throw new SyntaxError("Parameters of functions with yields must not have 'var', 'const' or 'params' modifier", "", pars.source_context, pars);
                    if (ps.inital_value != null)
                        throw new SyntaxError("Parameters of functions with yields must not have initial values", "", pars.source_context, pars);
                    //var_def_statement vds = new var_def_statement(ps.idents, ps.vars_type);
                    ident_list ids = new ident_list(ps.idents.list.Select(id => new ident(formalParamsMap[id.name])).ToArray());
                    var_def_statement vds = new var_def_statement(ids, ps.vars_type);
                    cm.Add(vds); // все параметры функции делаем полями класса
                    //lid.AddRange(vds.vars.idents);
                    lid.AddRange(ps.idents.list);
                }

            var stels = seqt.elements_type;

            // frninja 08/18/15 - Для захвата self
            if ((object)GetClassName(pd) != null)
                cm.Add(new var_def_statement(Consts.Self, GetClassName(pd).name));

            // Системные поля и методы для реализации интерфейса IEnumerable
            cm.Add(new var_def_statement(Consts.State, "integer"),
                new var_def_statement(Consts.Current, stels),
                procedure_definition.EmptyDefaultConstructor,
                new procedure_definition("Reset"),
                new procedure_definition("MoveNext", "boolean", pd.proc_body),
                new procedure_definition("get_Current", "object", new assign("Result", Consts.Current)),
                new procedure_definition("GetEnumerator", "System.Collections.IEnumerator", new assign("Result", "Self"))
                );

            var className = newClassName();
            var classNameHelper = className + "Helper";

            var interfaces = new named_type_reference_list("System.Collections.IEnumerator", "System.Collections.IEnumerable");
            var td = new type_declaration(classNameHelper, SyntaxTreeBuilder.BuildClassDefinition(interfaces, cm));

            // Изменение тела процедуры

            var stl = new statement_list(new var_statement("res", new new_expr(className)));
            //stl.AddMany(lid.Select(id => new assign(new dot_node("res", id), id)));
            stl.AddMany(lid.Select(id => new assign(new dot_node("res", new ident(formalParamsMap[id.name])), id)));

            // frninja 08/12/15 - захват self
            if ((object)GetClassName(pd) != null)
                stl.Add(new assign(new dot_node("res", Consts.Self), new ident("self")));

            stl.Add(new assign("Result", "res"));

            // New body
            pd.proc_body = new block(stl);

            if ((object)GetClassName(pd) != null)
            {
                // frninja 10/12/15 - заменить на function_header и перенести описание тела в declarations
                Replace(pd, fh);
                var decls = UpperTo<declarations>();
                if ((object)decls != null)
                {
                    function_header nfh = new function_header();
                    nfh.name = new method_name(fh.name.meth_name.name);
                    // Set name
                    nfh.name.class_name = GetClassName(pd);
                    nfh.parameters = fh.parameters;
                    nfh.proc_attributes = fh.proc_attributes;

                    procedure_definition npd = new procedure_definition(nfh, new block(stl));

                    // Update header
                    //pd.proc_header.name.class_name = GetClassName(pd);
                    // Add to decls
                    decls.Add(npd);
                }
            }

            // Второй класс

            var tpl = new template_param_list(stels);

            var IEnumeratorT = new template_type_reference("System.Collections.Generic.IEnumerator", tpl);

            var cm1 = class_members.Public.Add(
                procedure_definition.EmptyDefaultConstructor,
                new procedure_definition(new function_header("get_Current", stels), new assign("Result", Consts.Current)),
                new procedure_definition(new function_header("GetEnumerator", IEnumeratorT), new assign("Result", "Self")),
                new procedure_definition("Dispose")
            );

            var interfaces1 = new named_type_reference_list(classNameHelper);
            var IEnumerableT = new template_type_reference("System.Collections.Generic.IEnumerable", tpl);

            interfaces1.Add(IEnumerableT).Add(IEnumeratorT);

            var td1 = new type_declaration(className, SyntaxTreeBuilder.BuildClassDefinition(interfaces1, cm1));

            var cct = new type_declarations(td);
            cct.Add(td1);

            return cct;
        }
        private statement_node visit_program_code(statement_list program_code)
        {
            context.enter_code_block_with_bind();
            statement_node sn = convert_strong(program_code);
            context.leave_code_block();

            return sn;
        }
예제 #21
0
        public statement_list NewLambdaBody(expression expr_l1, LexLocation loc)
        {
            var _statement_list = new statement_list();
			var id = new ident("result");
			var _op_type_node = new op_type_node(Operators.Assignment);
			//_op_type_node.source_context = parsertools.GetTokenSourceContext();
			var _assign = new assign((addressed_value)id, expr_l1, _op_type_node.type);
			parsertools.create_source_context(_assign, id, expr_l1);
			_statement_list.subnodes.Add((statement)_assign);
            _statement_list.source_context = loc;
			//block _block = new block(null, _statement_list);
			return _statement_list;
        }
예제 #22
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public pair_type_stlist(type_definition _tn,statement_list _exprs,SourceContext sc)
		{
			this._tn=_tn;
			this._exprs=_exprs;
			source_context = sc;
		}
        public override void visit(SyntaxTree.assign_tuple asstup)
        {
            // Проверить, что справа - Tuple
            var expr = convert_strong(asstup.expr);
            expr = convert_if_typed_expression_to_function_call(expr);
            var t = ConvertSemanticTypeNodeToNETType(expr.type);
            if (t == null)
                AddError(expr.location, "TUPLE_EXPECTED");
            //if (t != typeof(System.Tuple<>))
            if (!t.FullName.StartsWith("System.Tuple"))
                AddError(expr.location, "TUPLE_EXPECTED");

            var n = asstup.vars.variables.Count();
            if (n > t.GetGenericArguments().Count())
                AddError(get_location(asstup.vars), "TOO_MANY_ELEMENTS_ON_LEFT_SIDE_OF_TUPLE_ASSIGNMRNT");

            var tname = "#temp_var" + UniqueNumStr();

            var tt = new var_statement(new ident(tname), new semantic_addr_value(expr)); // тут semantic_addr_value хранит на самом деле expr - просто неудачное название

            var st = new statement_list(tt);
            for (var i = 0; i < n; i++)
            {
                var a = new assign(asstup.vars.variables[i], new dot_node(new ident(tname), 
                    new ident("Item" + (i + 1).ToString())), Operators.Assignment, 
                    asstup.vars.variables[i].source_context);
                st.Add(a);
            }
            visit(st);
        }
예제 #24
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public program_body(uses_list _used_units,declarations _program_definitions,statement_list _program_code,using_list _using_list,SourceContext sc)
		{
			this._used_units=_used_units;
			this._program_definitions=_program_definitions;
			this._program_code=_program_code;
			this._using_list=_using_list;
			source_context = sc;
		}
예제 #25
0
		public void visit(statement_list _statement_list)
		{
			bw.Write((Int16)3);
			write_statement_list(_statement_list);
		}
예제 #26
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public unit_module(unit_name _unit_name,interface_node _interface_part,implementation_node _implementation_part,statement_list _initialization_part,statement_list _finalization_part,attribute_list _attributes,SourceContext sc)
		{
			this._unit_name=_unit_name;
			this._interface_part=_interface_part;
			this._implementation_part=_implementation_part;
			this._initialization_part=_initialization_part;
			this._finalization_part=_finalization_part;
			this._attributes=_attributes;
			source_context = sc;
		}
 public ConstructFiniteAutomata(statement_list stl)
 {
     this.stl = stl;
 }
예제 #28
0
		///<summary>
		///Конструктор с параметрами.
		///</summary>
		public unit_module(string _file_name,List<compiler_directive> _compiler_directives,LanguageId _Language,unit_name _unit_name,interface_node _interface_part,implementation_node _implementation_part,statement_list _initialization_part,statement_list _finalization_part,attribute_list _attributes,SourceContext sc)
		{
			this._file_name=_file_name;
			this._compiler_directives=_compiler_directives;
			this._Language=_Language;
			this._unit_name=_unit_name;
			this._interface_part=_interface_part;
			this._implementation_part=_implementation_part;
			this._initialization_part=_initialization_part;
			this._finalization_part=_finalization_part;
			this._attributes=_attributes;
			source_context = sc;
		}
        public void Transform()
        {
            cas = new case_node(new ident(Consts.State));

            curStatList = new statement_list();
            case_variant cv = new case_variant(new expression_list(new int32_const(curState)), curStatList);
            cas.conditions.variants.Add(cv);

            foreach (var st in stl.subnodes)
                Process(st);

            stl.subnodes = BaseChangeVisitor.SeqStatements(cas, StatListAfterCase).ToList();
            //statement_list res = new statement_list(cas);
            res = stl;
        }
예제 #30
0
 //vremenno, potom ubrat
 private compilation_unit get_fictive_unit(string s, string FileName)
 {
     program_module prog = new program_module();
     int line = 1;
     int col = 1;
     for (int i = 0; i < s.Length; i++)
         if (s[i] == '\n')
         {
             line++;
             col = 1;
         }
         else
         {
             col++;
         }
     prog.source_context = new SourceContext(1, 1, line + 3, 3);
     prog.program_block = new block();
     prog.file_name = FileName;
     statement_list sl = new statement_list();
     prog.program_block.program_code = sl;
     prog.program_block.program_code.left_logical_bracket = new token_info("begin");
     prog.program_block.program_code.left_logical_bracket.source_context = new SourceContext(1, 1, 1, 5);
     prog.program_block.program_code.right_logical_bracket = new token_info("end");
     prog.program_block.program_code.right_logical_bracket.source_context = new SourceContext(line + 3, 1, line + 3, 3);
     sl.subnodes.Add(new empty_statement());
     return prog;
 }