Exemple #1
0
 public void AddIdentList(ident_list idl)
 {
     foreach (var id in idl.idents)
     {
         Add(id);
     }
 }
Exemple #2
0
 public override void visit(ident_list _ident_list)
 {
     foreach (ident id in _ident_list.idents)
     {
         id.visit(this);
     }
 }
        public void semantic_check_assign_var_tuple(ident_list vars, expression ex)
        {
            // Проверить, что справа - Tuple
            var expr = convert_strong(ex);

            expr = convert_if_typed_expression_to_function_call(expr);

            var t = ConvertSemanticTypeNodeToNETType(expr.type);

            if (t == null)
            {
                AddError(expr.location, "TUPLE_EXPECTED");
            }

            if (!t.FullName.StartsWith("System.Tuple"))
            {
                AddError(expr.location, "TUPLE_EXPECTED");
            }

            var n = vars.idents.Count();

            if (n > t.GetGenericArguments().Count())
            {
                AddError(get_location(vars), "TOO_MANY_ELEMENTS_ON_LEFT_SIDE_OF_TUPLE_ASSIGNMRNT");
            }
        }
        public statement MyStmt(expression ex, statement st)
        {
            // Проверить, что в ex - целый тип
            // Сделать специальный узел для проверки new semantic_check("Тип проверки",params syntax_node[] ob)
            // Включать этот узел первым для "сахарных" узлов синтаксического дерева
            var sc = new semantic_check("ExprIsInteger", ex);

            var id     = new ident("#my");
            var idlist = new ident_list(id);
            var typ    = new named_type_reference("integer");
            var one    = new int32_const(1);
            var vdef   = new var_def_statement(idlist, typ, one, definition_attribute.None, false, null);
            var vstat  = new var_statement(vdef, null);

            var ass         = new assign(new ident("#my"), one, Operators.AssignmentAddition);
            var stlistwhile = new statement_list(st);

            stlistwhile.Add(ass);

            var bin = new bin_expr(id, ex, Operators.LessEqual);

            var wh = new while_node(bin, stlistwhile, WhileCycleType.While);

            var stlist = new statement_list(sc);

            stlist.Add(vstat);
            stlist.Add(wh);
            return(stlist);
        }
Exemple #5
0
        public override void visit(function_lambda_definition fld)
        {
            ProcessNode(fld.proc_body);
            if (fld.unpacked_params == null)
            {
                return;
            }

            fld.formal_parameters = new formal_parameters();
            fld.formal_parameters.source_context = fld.source_context;

            // Пусть параметр имеет вид \(x,y)
            // Тогда в начало тела лямбды надо добавить var (x,y) = #fpl1;
            //var idl = new ident_list(fld.unpacked_params.Select(p => p.id).ToList(),fld.source_context); //

            //var ass = new assign_var_tuple(idl, main_param_id, fld.source_context);

            List <statement> res = new List <statement>();

            foreach (var param in fld.unpacked_params)
            {
                if (param is unpacked_list_of_ident_or_list unpacked_param)
                {
                    var lam_inft   = new lambda_inferred_type(new lambda_any_type_node());
                    var param_id   = CreateIdent(fld.source_context);
                    var idlist     = new ident_list(param_id, unpacked_param.source_context);
                    var typed_pars = new typed_parameters(idlist, lam_inft, parametr_kind.none, null, unpacked_param.source_context);
                    fld.formal_parameters.Add(typed_pars, unpacked_param.source_context);
                    fld.ident_list.Add(param_id);
                    fld.parameters.Add(param_id);

                    CreateUnpackedListOfAssignments(unpacked_param, res, param_id, unpacked_param.source_context);
                }
                else if (param is ident id)
                {
                    var lam_inft   = new lambda_inferred_type(new lambda_any_type_node());
                    var idlist     = new ident_list(id, id.source_context);
                    var typed_pars = new typed_parameters(idlist, lam_inft);
                    fld.formal_parameters.Add(typed_pars, fld.source_context);
                    fld.ident_list.Add(id);
                    fld.parameters.Add(id);
                }
            }


            var stl = fld.proc_body as statement_list;

            res.Reverse();
            foreach (var st in res)
            {
                var ass = st as assign_var_tuple;
                ass.idents.source_context = new SourceContext(ass.idents[0].source_context, ass.idents[ass.idents.Count - 1].source_context);
                ass.expr.source_context   = ass.idents.source_context;
                stl.Insert(0, st); // возможно, в обратном порядке
            }

            //stl.Insert(0, ass);
            fld.unpacked_params = null; // на рассахаренном уровне это поле нулевое!
        }
            public static var_statement CreateVarStatementNode(string idName, type_definition varType, expression initValue)
            {
                var id     = new ident(idName);
                var idlist = new ident_list(id);
                var vdef   = new var_def_statement(idlist, varType, initValue, definition_attribute.None, false, null);

                return(new var_statement(vdef, null));
            }
Exemple #7
0
 public override void visit(ident_list _ident_list)
 {
     //for(int i=0;i<_ident_list.idents.Count;i++)
     //{
     //	ident id=_ident_list.idents[i];
     //	prepare_node(id,"idents["+i.ToString()+"]");
     //}
     prepare_collection(_ident_list.idents, "idents");
 }
        /// <summary>
        /// Создать var-выражение
        /// </summary>
        /// <param name="name">Имя переменной</param>
        /// <param name="initialValue">Начальное значение</param>
        /// <returns></returns>
        public static var_def_statement CreateVarDef(string name, expression initialValue)
        {
            ident_list list = new ident_list();

            list.idents.Add(new ident(name));
            var res = new var_def_statement();

            res.inital_value = initialValue;
            res.vars         = list;
            return(res);
        }
        private static ident_list RestrictionsToIdentList(template_param_list restrictions)
        {
            var templates = new ident_list();

            templates.source_context = restrictions.source_context;
            for (int i = 0; i < restrictions.Count; i++)
            {
                templates.Add((restrictions.params_list[i] as named_type_reference).names[0]);
            }

            return(templates);
        }
Exemple #10
0
 private void get_var_statement(statement_list sl, ICSharpCode.NRefactory.Ast.LocalVariableDeclaration var)
 {
     foreach (ICSharpCode.NRefactory.Ast.VariableDeclaration vd in var.Variables)
     {
         var_def_statement vds = new var_def_statement();
         vds.source_context = get_source_context(var);
         vds.vars_type      = get_type_reference(vd.TypeReference);
         ident_list idents = new ident_list();
         ident      name   = new ident(vd.Name);
         name.source_context = get_source_context(var);
         idents.idents.Add(name);
         vds.vars = idents;
         sl.subnodes.Add(new var_statement(vds));
     }
 }
        public unit_name NewNamespaceHeading(ident unitkeyword, ident_list nname, LexLocation loc)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < nname.idents.Count; i++)
            {
                sb.Append(nname.idents[i]);
                if (i < nname.idents.Count - 1)
                {
                    sb.Append(".");
                }
            }
            ident uname = new ident(sb.ToString(), nname.source_context);
            var   un    = new unit_name(uname, UnitHeaderKeyword.Unit, loc);

            un.HeaderKeyword = UnitHeaderKeyword.Namespace;
            return(un);
        }
Exemple #12
0
        public void semantic_check_assign_var_tuple(ident_list vars, expression ex)
        {
            // Почти полностью идентичный код в двух проверках
            var expr = convert_strong(ex);

            expr = convert_if_typed_expression_to_function_call(expr);

            var t = ConvertSemanticTypeNodeToNETType(expr.type);

            if (t == null)
            {
                AddError(expr.location, "TUPLE_OR_SEQUENCE_EXPECTED");
            }

            var IsTuple    = false;
            var IsSequence = false;

            if (t.FullName.StartsWith("System.Tuple"))
            {
                IsTuple = true;
            }
            if (!IsTuple)
            {
                if (t.Name.Equals("IEnumerable`1") || t.GetInterface("IEnumerable`1") != null)
                {
                    IsSequence = true;
                }
            }
            if (!IsTuple && !IsSequence)
            {
                AddError(expr.location, "TUPLE_OR_SEQUENCE_EXPECTED");
            }

            if (IsTuple)
            {
                var n = vars.idents.Count();
                if (n > t.GetGenericArguments().Count())
                {
                    AddError(get_location(vars), "TOO_MANY_ELEMENTS_ON_LEFT_SIDE_OF_TUPLE_ASSIGNMRNT");
                }
            }
        }
Exemple #13
0
        private List <declaration> get_field_declaration(ICSharpCode.NRefactory.Ast.FieldDeclaration vd)
        {
            List <declaration> fields = new List <declaration>();
            bool is_static            = (vd.Modifier & ICSharpCode.NRefactory.Ast.Modifiers.Static) == ICSharpCode.NRefactory.Ast.Modifiers.Static;

            foreach (ICSharpCode.NRefactory.Ast.VariableDeclaration vard in vd.Fields)
            {
                var_def_statement vds = new var_def_statement();
                vds.source_context = get_source_context(vd);
                vds.vars_type      = get_type_reference(vard.TypeReference);
                ident_list idents = new ident_list();
                ident      name   = new ident(vard.Name);
                name.source_context = vds.source_context;
                idents.idents.Add(name);
                vds.vars = idents;
                if (is_static)
                {
                    vds.var_attr = definition_attribute.Static;
                }
                fields.Add(vds);
            }
            return(fields);
        }
Exemple #14
0
        public void CreateUnpackedListOfAssignments(unpacked_list_of_ident_or_list ll, List <statement> res, ident prevname, SourceContext sc)
        {
            var idlist = new ident_list();

            foreach (var llelem in ll.lst)
            {
                if (llelem.lst != null)
                {
                    var id = CreateIdent(sc);
                    // надо у этого id установить souce_context
                    idlist.Add(id);
                    CreateUnpackedListOfAssignments(llelem.lst, res, id, sc);
                }
                else
                {
                    idlist.Add(llelem.id);
                }
            }
            idlist.source_context = sc;
            var ass = new assign_var_tuple(idlist, prevname, sc);

            res.Insert(0, ass);
        }
Exemple #15
0
        public void semantic_check_extended_foreach(ident_list vars, type_node elem_type, location inwhatloc)
        {
            var t = ConvertSemanticTypeNodeToNETType(elem_type);

            if (t == null)
            {
                AddError(inwhatloc, "TUPLE_OR_SEQUENCE_EXPECTED_FOREACH");
            }

            var IsTuple    = false;
            var IsSequence = false;

            if (t.FullName.StartsWith("System.Tuple"))
            {
                IsTuple = true;
            }
            if (!IsTuple)
            {
                if (t.Name.Equals("IEnumerable`1") || t.GetInterface("IEnumerable`1") != null)
                {
                    IsSequence = true;
                }
            }
            if (!IsTuple && !IsSequence)
            {
                AddError(inwhatloc, "TUPLE_OR_SEQUENCE_EXPECTED_FOREACH");
            }

            if (IsTuple)
            {
                var n = vars.idents.Count();
                if (n > t.GetGenericArguments().Count())
                {
                    AddError(get_location(vars), "TOO_MANY_ELEMENTS_ON_LEFT_SIDE_OF_TUPLE_ASSIGNMRNT");
                }
            }
        }
Exemple #16
0
        protected override void DoAction(int action)
        {
            switch (action)
            {
            case 2: // module -> MODULE, ident, SEMICOLUMN, Declarations, BEGIN, StatementSequence,
                    //           END, ident, COMMA
            {
                if (ValueStack[ValueStack.Depth - 8].id.name != ValueStack[ValueStack.Depth - 2].id.name)
                {
                    PT.AddError("Имя " + ValueStack[ValueStack.Depth - 2].id.name + " должно совпадать с именем модуля " + ValueStack[ValueStack.Depth - 8].id.name, LocationStack[LocationStack.Depth - 2]);
                }

                // Подключение стандартной библиотеки
                ident_list il = new ident_list();
                il.Add(new ident("Oberon00System"));
                unit_or_namespace un = new unit_or_namespace(il);
                uses_list         ul = new uses_list();
                ul.units.Insert(0, un);

                // Формирование главного модуля
                var b = new block(ValueStack[ValueStack.Depth - 6].decl, ValueStack[ValueStack.Depth - 4].sl, LocationStack[LocationStack.Depth - 6].Merge(LocationStack[LocationStack.Depth - 2]));
                var r = new program_module(null, ul, b, null, CurrentLocationSpan);
                r.Language = LanguageId.Oberon00;
                root       = r;
            }
            break;

            case 3: // module -> INVISIBLE, expr
            {       // Для Intellisense
                root = ValueStack[ValueStack.Depth - 1].ex;
            }
            break;

            case 4: // ident -> ID
            {
                CurrentSemanticValue.id = new ident(ValueStack[ValueStack.Depth - 1].sVal, CurrentLocationSpan);
            }
            break;

            case 5: // expr -> ident
            {
                CurrentSemanticValue.ex = ValueStack[ValueStack.Depth - 1].id;
            }
            break;

            case 6: // expr -> INTNUM
            {
                CurrentSemanticValue.ex = new int32_const(ValueStack[ValueStack.Depth - 1].iVal, CurrentLocationSpan);
            }
            break;

            case 7: // expr -> TRUE
            {
                CurrentSemanticValue.ex = new bool_const(true, CurrentLocationSpan);
            }
            break;

            case 8: // expr -> FALSE
            {
                CurrentSemanticValue.ex = new bool_const(false, CurrentLocationSpan);
            }
            break;

            case 9: // expr -> MINUS, expr
            {
                CurrentSemanticValue.ex = new un_expr(ValueStack[ValueStack.Depth - 1].ex, Operators.Minus, CurrentLocationSpan);
            }
            break;

            case 10: // expr -> LPAREN, expr, RPAREN
            { CurrentSemanticValue.ex = ValueStack[ValueStack.Depth - 2].ex; }
            break;

            case 11: // expr -> NOT, expr
            {
                CurrentSemanticValue.ex = new un_expr(ValueStack[ValueStack.Depth - 1].ex, Operators.LogicalNOT, CurrentLocationSpan);
            }
            break;

            case 12: // expr -> expr, PLUS, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Plus, CurrentLocationSpan);
            }
            break;

            case 13: // expr -> expr, MINUS, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Minus, CurrentLocationSpan);
            }
            break;

            case 14: // expr -> expr, MULT, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Multiplication, CurrentLocationSpan);
            }
            break;

            case 15: // expr -> expr, DIVIDE, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.IntegerDivision, CurrentLocationSpan);
            }
            break;

            case 16: // expr -> expr, AND, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.LogicalAND, CurrentLocationSpan);
            }
            break;

            case 17: // expr -> expr, OR, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.LogicalOR, CurrentLocationSpan);
            }
            break;

            case 18: // expr -> expr, EQ, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Equal, CurrentLocationSpan);
            }
            break;

            case 19: // expr -> expr, NE, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.NotEqual, CurrentLocationSpan);
            }
            break;

            case 20: // expr -> expr, LT, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Less, CurrentLocationSpan);
            }
            break;

            case 21: // expr -> expr, LE, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.LessEqual, CurrentLocationSpan);
            }
            break;

            case 22: // expr -> expr, GT, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Greater, CurrentLocationSpan);
            }
            break;

            case 23: // expr -> expr, GE, expr
            {
                CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.GreaterEqual, CurrentLocationSpan);
            }
            break;

            case 24: // Assignment -> ident, ASSIGN, expr
            {
                CurrentSemanticValue.st = new assign(ValueStack[ValueStack.Depth - 3].id, ValueStack[ValueStack.Depth - 1].ex, Operators.Assignment, CurrentLocationSpan);
            }
            break;

            case 25: // IfStatement -> IF, expr, THEN, StatementSequence, END
            {
                CurrentSemanticValue.st = new if_node(ValueStack[ValueStack.Depth - 4].ex, ValueStack[ValueStack.Depth - 2].sl, null, CurrentLocationSpan);
            }
            break;

            case 26: // IfStatement -> IF, expr, THEN, StatementSequence, ELSE, StatementSequence, END
            {
                CurrentSemanticValue.st = new if_node(ValueStack[ValueStack.Depth - 6].ex, ValueStack[ValueStack.Depth - 4].sl, ValueStack[ValueStack.Depth - 2].sl, CurrentLocationSpan);
            }
            break;

            case 27: // WhileStatement -> WHILE, expr, DO, StatementSequence, END
            {
                CurrentSemanticValue.st = new while_node(ValueStack[ValueStack.Depth - 4].ex, ValueStack[ValueStack.Depth - 2].sl, WhileCycleType.While, CurrentLocationSpan);
            }
            break;

            case 28: // WriteStatement -> EXCLAMATION, expr
            {
                expression_list el = new expression_list(ValueStack[ValueStack.Depth - 1].ex);
                method_call     mc = new method_call(el);
                mc.dereferencing_value  = new ident("print");
                CurrentSemanticValue.st = mc;
            }
            break;

            case 29: // factparams -> expr
            {
                CurrentSemanticValue.el = new expression_list(ValueStack[ValueStack.Depth - 1].ex, CurrentLocationSpan);
            }
            break;

            case 30: // factparams -> factparams, COLUMN, expr
            {
                ValueStack[ValueStack.Depth - 3].el.Add(ValueStack[ValueStack.Depth - 1].ex, CurrentLocationSpan);
                CurrentSemanticValue.el = ValueStack[ValueStack.Depth - 3].el;
            }
            break;

            case 31: // ProcCallStatement -> ident, LPAREN, factparams, RPAREN
            {
                CurrentSemanticValue.st = new method_call(ValueStack[ValueStack.Depth - 4].id, ValueStack[ValueStack.Depth - 2].el, CurrentLocationSpan);
            }
            break;

            case 32: // EmptyStatement -> /* empty */
            {
                CurrentSemanticValue.st = new empty_statement();
            }
            break;

            case 39: // StatementSequence -> Statement
            {
                CurrentSemanticValue.sl = new statement_list(ValueStack[ValueStack.Depth - 1].st, CurrentLocationSpan);
            }
            break;

            case 40: // StatementSequence -> StatementSequence, SEMICOLUMN, Statement
            {
                ValueStack[ValueStack.Depth - 3].sl.Add(ValueStack[ValueStack.Depth - 1].st, CurrentLocationSpan);
                CurrentSemanticValue.sl = ValueStack[ValueStack.Depth - 3].sl;
            }
            break;

            case 41: // type -> BOOLEAN
            {
                CurrentSemanticValue.ntr = new named_type_reference("boolean", CurrentLocationSpan);
            }
            break;

            case 42: // type -> INTEGER
            {
                CurrentSemanticValue.ntr = new named_type_reference("integer", CurrentLocationSpan);
            }
            break;

            case 43: // IDList -> ident
            {
                CurrentSemanticValue.il = new ident_list(ValueStack[ValueStack.Depth - 1].id, CurrentLocationSpan);
            }
            break;

            case 44: // IDList -> IDList, COLUMN, ident
            {
                ValueStack[ValueStack.Depth - 3].il.Add(ValueStack[ValueStack.Depth - 1].id, CurrentLocationSpan);
                CurrentSemanticValue.il = ValueStack[ValueStack.Depth - 3].il;
            }
            break;

            case 45: // VarDecl -> IDList, COLON, type, SEMICOLUMN
            {
                CurrentSemanticValue.vds = new var_def_statement(ValueStack[ValueStack.Depth - 4].il, ValueStack[ValueStack.Depth - 2].ntr, null, definition_attribute.None, false, CurrentLocationSpan);
            }
            break;

            case 46: // VarDeclarations -> VarDecl
            {
                CurrentSemanticValue.vdss = new variable_definitions(ValueStack[ValueStack.Depth - 1].vds, CurrentLocationSpan);
            }
            break;

            case 47: // VarDeclarations -> VarDeclarations, VarDecl
            {
                ValueStack[ValueStack.Depth - 2].vdss.Add(ValueStack[ValueStack.Depth - 1].vds, CurrentLocationSpan);
                CurrentSemanticValue.vdss = ValueStack[ValueStack.Depth - 2].vdss;
            }
            break;

            case 48: // ConstDecl -> ident, EQ, ConstExpr, SEMICOLUMN
            {
                CurrentSemanticValue.scd = new simple_const_definition(ValueStack[ValueStack.Depth - 4].id, ValueStack[ValueStack.Depth - 2].ex, CurrentLocationSpan);
            }
            break;

            case 50: // ConstDeclarations -> ConstDecl
            {
                CurrentSemanticValue.cdl = new consts_definitions_list(ValueStack[ValueStack.Depth - 1].scd, CurrentLocationSpan);
            }
            break;

            case 51: // ConstDeclarations -> ConstDeclarations, ConstDecl
            {
                ValueStack[ValueStack.Depth - 2].cdl.Add(ValueStack[ValueStack.Depth - 1].scd, CurrentLocationSpan);
                CurrentSemanticValue.cdl = ValueStack[ValueStack.Depth - 2].cdl;
            }
            break;

            case 52: // ConstDeclarationsSect -> CONST, ConstDeclarations
            {
                CurrentSemanticValue.cdl = ValueStack[ValueStack.Depth - 1].cdl;
                CurrentSemanticValue.cdl.source_context = CurrentLocationSpan;
            }
            break;

            case 53: // VarDeclarationsSect -> VAR, VarDeclarations
            {
                CurrentSemanticValue.vdss = ValueStack[ValueStack.Depth - 1].vdss;
                CurrentSemanticValue.vdss.source_context = CurrentLocationSpan;
            }
            break;

            case 54: // Declarations -> VarDeclarationsSect
            {
                CurrentSemanticValue.decl = new declarations(ValueStack[ValueStack.Depth - 1].vdss, CurrentLocationSpan);
            }
            break;

            case 55: // Declarations -> ConstDeclarationsSect, VarDeclarationsSect
            {
                CurrentSemanticValue.decl = new declarations(ValueStack[ValueStack.Depth - 1].vdss, CurrentLocationSpan);
                CurrentSemanticValue.decl.Add(ValueStack[ValueStack.Depth - 1].vdss);
//		$$.source_context = @$;
            }
            break;
            }
        }
		public override void visit(ident_list _ident_list)
		{
			executer.visit(_ident_list);
			if (_ident_list.idents != null)
			foreach (dynamic x in _ident_list.idents)
				if(x != null)
					this.visit(x);
		}
 public override void visit(ident_list _ident_list)
 {
     //text="Count: "+_ident_list.idents.Count.ToString();
     get_count(_ident_list.idents);
 }
 public virtual void visit(ident_list _ident_list)
 {
     DefaultVisit(_ident_list);
 }
		public override void visit(ident_list _ident_list)
		{
			DefaultVisit(_ident_list);
			pre_do_visit(_ident_list);
			for (int i = 0; i < idents.Count; i++)
				visit(ident_list.idents[i]);
			post_do_visit(_ident_list);
		}
		public virtual void visit(ident_list _ident_list)
		{
			DefaultVisit(_ident_list);
		}
Exemple #22
0
        // frninja 23/04/16 - для шаблонных классов в yield
        public static class_definition BuildClassDefinition(named_type_reference_list parents, ident_list template_args, params class_members[] cms)
        {
            var cb = new class_body_list();

            foreach (var cm in cms)
            {
                cb.Add(cm);
            }

            var cd = new class_definition(parents, cb, class_keyword.Class, template_args, null, class_attribute.None, false, null);

            return(cd);
        }
Exemple #23
0
 public virtual void visit(ident_list _ident_list)
 {
 }
        public override void visit(procedure_definition _procedure_definition)
        {
            bool isConstrainted = _procedure_definition.proc_header.where_defs != null &&
                                  _procedure_definition.proc_header.where_defs.defs.Any(x => x is where_typeclass_constraint);

            if (!isConstrainted)
            {
                DefaultVisit(_procedure_definition);
                return;
            }

            var header           = _procedure_definition.proc_header;
            var headerTranslated = header.Clone() as procedure_header;

            headerTranslated.where_defs = new where_definition_list();

            var additionalTemplateArgs = new ident_list();

            for (int i = 0; i < header.where_defs.defs.Count; i++)
            {
                var where = header.where_defs.defs[i];

                if (where is where_typeclass_constraint)
                {
                    var typeclassWhere = where as where_typeclass_constraint;
                    var newName        = TypeclassRestrctionToTemplateName(typeclassWhere.restriction.name, typeclassWhere.restriction.restriction_args);
                    AddAttribute(
                        newName, "__TypeclassGenericParameter",
                        new expression_list(new string_const(GetInstanceSingletonName(newName.name))));
                    additionalTemplateArgs.Add(newName);

                    // Create name for template that replaces typeclass(for ex. SumTC)
                    headerTranslated.where_defs.defs.Add(
                        GetWhereRestriction(
                            new template_type_reference(new named_type_reference("I" + typeclassWhere.restriction.name), typeclassWhere.restriction.restriction_args),
                            newName));
                }
                else
                {
                    headerTranslated.where_defs.defs.Add(where);
                }
            }

            // Add new templates devoted to constraints to template list
            // TODO: template_args can be empty, if there is no <T> or smth, need to check
            headerTranslated.template_args.idents.AddRange(additionalTemplateArgs.idents);

            var blockProc = (_procedure_definition.proc_body as block);

            foreach (var arg in additionalTemplateArgs.idents)
            {
                blockProc.program_code.AddFirst(GetInstanceSingletonVarStatement(arg.name));
            }

            //var list = _procedure_definition.proc_body.DescendantNodes().OfType<typeclass_param_list>();
            foreach (var tcr in _procedure_definition.proc_body.DescendantNodes().OfType <ident_with_templateparams>())
            {
                if (tcr.template_params is typeclass_param_list)
                {
                    // TODO: Check tcr.name - typeclass from where
                    // TODO: Check - that there is such typeclass with such args at where
                    // TODO: Ensure that we don't replace another constraint funciton call
                    var str = tcr.template_params.params_list
                              .Select(x => (x as named_type_reference).names[0].name)
                              .Aggregate((tcr.name as ident).name, (x, y) => x + y);
                    var id     = new ident(str + "Instance");
                    var parent = tcr.Parent;
                    parent.ReplaceDescendant((addressed_value)tcr, (addressed_value)id, Desc.All);
                }
                //var id = new ident(TypeclassRestrctionToTemplateName(tcr) + "Instance");
            }

            var procedureDefTranslated = new procedure_definition(
                headerTranslated, _procedure_definition.proc_body,
                _procedure_definition.is_short_definition, _procedure_definition.source_context);

            procedureDefTranslated.proc_header.attributes = _procedure_definition.proc_header.attributes;
            AddAttribute(procedureDefTranslated.proc_header, "__TypeclassRestrictedFunctionAttribute");
            Replace(_procedure_definition, procedureDefTranslated);
            visit(procedureDefTranslated);
        }
Exemple #25
0
 private void add_module_members(unit_module mod, ICSharpCode.NRefactory.Ast.TypeDeclaration td)
 {
     foreach (ICSharpCode.NRefactory.Ast.INode node in td.Children)
     {
         if (node is ICSharpCode.NRefactory.Ast.FieldDeclaration)
         {
             ICSharpCode.NRefactory.Ast.FieldDeclaration vd = node as ICSharpCode.NRefactory.Ast.FieldDeclaration;
             if ((vd.Modifier & ICSharpCode.NRefactory.Ast.Modifiers.Dim) == ICSharpCode.NRefactory.Ast.Modifiers.Dim)
             {
                 foreach (ICSharpCode.NRefactory.Ast.VariableDeclaration vard in vd.Fields)
                 {
                     var_def_statement vds = new var_def_statement();
                     vds.source_context = get_source_context(vd);
                     vds.vars_type      = get_type_reference(vard.TypeReference);
                     ident_list idents = new ident_list();
                     ident      name   = new ident(vard.Name);
                     name.source_context = vds.source_context;
                     idents.idents.Add(name);
                     vds.vars = idents;
                     mod.interface_part.interface_definitions.defs.Add(vds);
                 }
             }
             else if ((vd.Modifier & ICSharpCode.NRefactory.Ast.Modifiers.Const) == ICSharpCode.NRefactory.Ast.Modifiers.Const)
             {
                 foreach (ICSharpCode.NRefactory.Ast.VariableDeclaration vard in vd.Fields)
                 {
                     const_definition tcd = null;
                     if (vard.TypeReference is ICSharpCode.NRefactory.Ast.TypeReference)
                     {
                         tcd = new simple_const_definition();
                     }
                     else
                     {
                         tcd = new typed_const_definition();
                     }
                     tcd.source_context = get_source_context(vd);
                     if (tcd is typed_const_definition)
                     {
                         (tcd as typed_const_definition).const_type = get_type_reference(vard.TypeReference);
                     }
                     tcd.const_name = new ident(vard.Name);
                     tcd.const_name.source_context = tcd.source_context;
                     tcd.const_value = get_expression(vard.Initializer);
                     mod.interface_part.interface_definitions.defs.Add(tcd);
                 }
             }
         }
         else if (node is ICSharpCode.NRefactory.Ast.TypeDeclaration)
         {
             mod.interface_part.interface_definitions.defs.Add(get_type_declaration(node as ICSharpCode.NRefactory.Ast.TypeDeclaration));
         }
         else if (node is ICSharpCode.NRefactory.Ast.MethodDeclaration)
         {
             ICSharpCode.NRefactory.Ast.MethodDeclaration meth = node as ICSharpCode.NRefactory.Ast.MethodDeclaration;
             if (!meth.Body.IsNull)
             {
                 mod.interface_part.interface_definitions.defs.Add(get_method_declaration(meth));
             }
             else
             {
                 mod.interface_part.interface_definitions.defs.Add(get_method_header(meth));
             }
         }
     }
 }
        bool VisitTypeclassDeclaration(type_declaration typeclassDeclaration)
        {
            var typeclassDefinition = typeclassDeclaration.type_def as typeclass_definition;

            if (typeclassDefinition == null)
            {
                return(false);
            }

            var typeclassName = typeclassDeclaration.type_name as typeclass_restriction;

            // TODO: typeclassDefinition.additional_restrictions - translate to usual classes

            // Creating interface

            // Get members for typeclass interface
            var interfaceMembers = new List <class_members>();

            foreach (var cm in typeclassDefinition.body.class_def_blocks)
            {
                var cmNew = (class_members)cm.Clone();

                for (int i = 0; i < cmNew.members.Count; i++)
                {
                    var member = cmNew.members[i];
                    if (member is function_header || member is procedure_header)
                    {
                        cmNew.members[i] = member;
                    }
                    else if (member is procedure_definition procDef)
                    {
                        cmNew.members[i] = procDef.proc_header;
                    }
                    AddAttribute(cmNew.members[i], "__TypeclassMemberAttribute");
                    if (cmNew.members[i] is procedure_header ph)
                    {
                        ConvertOperatorNameIdent(ph);
                    }
                }

                interfaceMembers.Add(cmNew);
            }
            var interfaceInheritance = (named_type_reference_list)typeclassDefinition.additional_restrictions?.Clone();

            if (interfaceInheritance != null)
            {
                interfaceInheritance.source_context = null;
                for (int i = 0; i < interfaceInheritance.types.Count; i++)
                {
                    if (interfaceInheritance.types[i] is typeclass_reference tr)
                    {
                        interfaceInheritance.types[i] = TypeclassReferenceToInterfaceName(tr.names[0].name, tr.restriction_args);
                    }
                    else
                    {
                        throw new NotImplementedException("Syntactic Error");
                    }
                }
            }
            var typeclassInterfaceDef =
                SyntaxTreeBuilder.BuildClassDefinition(
                    interfaceInheritance,
                    null, interfaceMembers.ToArray());

            typeclassInterfaceDef.keyword = class_keyword.Interface;
            var typeclassInterfaceName = new template_type_name("I" + typeclassName.name, RestrictionsToIdentList(typeclassName.restriction_args));
            var typeclassInterfaceDecl = new type_declaration(typeclassInterfaceName, typeclassInterfaceDef);

            typeclassInterfaceDecl.attributes = typeclassDeclaration.attributes;
            AddAttribute(
                typeclassInterfaceDecl, "__TypeclassAttribute",
                new expression_list(new string_const(TypeclassRestrictionToString(typeclassName))));


            // Creating class

            var typeclassDefTranslated =
                SyntaxTreeBuilder.BuildClassDefinition(
                    new named_type_reference_list(new template_type_reference(typeclassInterfaceName.name, typeclassName.restriction_args)),
                    null, typeclassDefinition.body.class_def_blocks.ToArray());

            typeclassDefTranslated.attribute = class_attribute.Abstract;
            for (int i = 0; i < typeclassDefTranslated.body.class_def_blocks.Count; i++)
            {
                var cm = typeclassDefTranslated.body.class_def_blocks[i].members;

                for (int j = 0; j < cm.Count; j++)
                {
                    procedure_header header = null;
                    if (cm[j] is procedure_header ph)
                    {
                        header = ph;
                        header.proc_attributes.Add(new procedure_attribute("abstract", proc_attribute.attr_abstract));
                    }
                    else if (cm[j] is procedure_definition pd)
                    {
                        header = pd.proc_header;
                        header.proc_attributes.Add(new procedure_attribute("virtual", proc_attribute.attr_virtual));
                    }

                    ConvertOperatorNameIdent(header);
                }
            }

            /*
             * {
             *  // Add constructor
             *  var cm = typeclassDefTranslated.body.class_def_blocks[0];
             *  var def = new procedure_definition(
             *      new constructor(),
             *      new statement_list(new empty_statement()));
             *  def.proc_body.Parent = def;
             *  def.proc_header.proc_attributes = new procedure_attributes_list();
             *
             *  cm.Add(def);
             * }
             */
            // Add template parameters for typeclass class(derived typeclasses)
            ident_list templates = RestrictionsToIdentList(typeclassName.restriction_args);

            if (typeclassDefinition.additional_restrictions != null)
            {
                for (int i = 0; i < typeclassDefinition.additional_restrictions.types.Count; i++)
                {
                    string name;
                    string templateName;
                    if (typeclassDefinition.additional_restrictions.types[i] is typeclass_reference tr)
                    {
                        name         = tr.names[0].name;
                        templateName = TypeclassRestrctionToTemplateName(name, tr.restriction_args).name;
                    }
                    else
                    {
                        throw new NotImplementedException("SyntaxError");
                    }

                    // Add template parameter
                    templates.Add(templateName);

                    // Add where restriction
                    if (typeclassDefTranslated.where_section == null)
                    {
                        typeclassDefTranslated.where_section = new where_definition_list();
                    }
                    typeclassDefTranslated.where_section.Add(GetWhereRestriction(
                                                                 interfaceInheritance.types[i],
                                                                 templateName));

                    // Add methods from derived typeclasses
                    var body = (instancesAndRestrictedFunctions.typeclasses[name].type_def as typeclass_definition).body;
                    foreach (var cdb in body.class_def_blocks)
                    {
                        var cdbNew = new class_members(cdb.access_mod == null ? access_modifer.none : cdb.access_mod.access_level);
                        foreach (var member in cdb.members)
                        {
                            procedure_header memberHeaderNew;

                            if (member is procedure_header || member is function_header)
                            {
                                memberHeaderNew = (procedure_header)member.Clone();
                                memberHeaderNew.source_context = null;
                            }
                            else if (member is procedure_definition procDefinition)
                            {
                                memberHeaderNew                = (procedure_header)procDefinition.proc_header.Clone();
                                memberHeaderNew.Parent         = null;
                                memberHeaderNew.source_context = null;
                            }
                            else
                            {
                                continue;
                            }

                            var variableName = templateName + "Instance";
                            var parameters   = memberHeaderNew.parameters.params_list.Aggregate(new expression_list(), (x, y) => new expression_list(x.expressions.Concat(y.idents.idents).ToList()));

                            expression methodCall = null;
                            if (memberHeaderNew.name.meth_name is operator_name_ident oni)
                            {
                                ConvertOperatorNameIdent(memberHeaderNew);
                                Debug.Assert(parameters.expressions.Count == 2, "Parameters count for operation should be equal to 2");
                                //methodCall = new bin_expr(parameters.expressions[0], parameters.expressions[1], oni.operator_type);
                            }
                            var callName = new dot_node(variableName, memberHeaderNew.name.meth_name.name);
                            methodCall = new method_call(callName, parameters);
                            statement exec = null;
                            if (memberHeaderNew is function_header)
                            {
                                exec = new assign("Result", methodCall);
                            }
                            else if (memberHeaderNew is procedure_header)
                            {
                                exec = new procedure_call(methodCall as method_call);
                            }
                            var procDef = new procedure_definition(
                                memberHeaderNew,
                                new statement_list(
                                    GetInstanceSingletonVarStatement(templateName),
                                    exec));
                            cdbNew.Add(procDef);
                        }
                        typeclassDefTranslated.body.class_def_blocks.Add(cdbNew);
                    }
                }
            }

            var typeclassNameTanslated = new template_type_name(typeclassName.name, templates, typeclassName.source_context);

            var typeclassDeclTranslated = new type_declaration(typeclassNameTanslated, typeclassDefTranslated, typeclassDeclaration.source_context);

            typeclassDeclTranslated.attributes = typeclassDeclaration.attributes;
            AddAttribute(
                typeclassDeclTranslated, "__TypeclassAttribute",
                new expression_list(new string_const(TypeclassRestrictionToString(typeclassName))));

            Replace(typeclassDeclaration, typeclassDeclTranslated);
            UpperNodeAs <type_declarations>().InsertBefore(typeclassDeclTranslated, typeclassInterfaceDecl);
            visit(typeclassInterfaceDecl);
            visit(typeclassDeclTranslated);

            return(true);
        }
        public ident func_decl_lambda(object lr0, object lr2)
        {
            statement_list    _statement_list    = (statement_list)lr2;
            expression_list   _expression_list   = new expression_list();
            ident_list        _i_l               = new ident_list();
            formal_parameters _formal_parameters = new formal_parameters();

            if (lr0 != null)
            {
                List <object> ar = (List <object>)lr0;
                for (int i = 0; i < ar.Count; i++)
                {
                    if (ar[i] is ident)
                    {
                        _i_l.idents.Add((ident)ar[i]);
                    }
                    else
                    {
                        _i_l.idents.Add(((var_def_statement)ar[i]).vars.idents[0]);
                    }
                }

                for (int i = 0; i < _i_l.idents.Count; i++)
                {
                    _expression_list.expressions.Add(_i_l.idents[i]);
                }

                for (int i = 0; i < ar.Count; i++)
                {
                    ident_list _ident_list = new ident_list();
                    ident      id          = _i_l.idents[i];
                    _ident_list.idents.Add(id);
                    string           name_param        = id.name;
                    typed_parameters _typed_parameters = null;
                    int k = 0;
                    {
                        named_type_reference _named_type_reference = new named_type_reference();
                        type_definition      t_d = new type_definition();
                        if (ar[i] is ident)
                        {
                            ident idtype = new ident("object");
                            _named_type_reference.names.Add(idtype);
                            t_d = (type_definition)_named_type_reference;
                        }
                        else
                        {
                            t_d = ((var_def_statement)ar[i]).vars_type;
                        }
                        _typed_parameters = new typed_parameters(_ident_list, t_d, parametr_kind.none, null);
                        //parsertools.create_source_context(_typed_parameters, _ident_list, t_d);
                    }
                    _formal_parameters.params_list.Add(_typed_parameters);
                }
            }
            //////////////////////////
            named_type_reference _named_type_reference1 = new named_type_reference();
            ident idtype1 = new ident("object");

            _named_type_reference1.source_context = idtype1.source_context;
            _named_type_reference1.names.Add(idtype1);
            /////////////////////////////
            lambda_num++;
            function_lambda_definition _procedure_definition = new function_lambda_definition();

            _procedure_definition.formal_parameters = _formal_parameters;
            _procedure_definition.return_type       = (type_definition)_named_type_reference1;
            _procedure_definition.ident_list        = _i_l;
            _procedure_definition.proc_body         = null;
            _procedure_definition.parameters        = _expression_list;
            _procedure_definition.lambda_name       = "__lambda__" + lambda_num;
            //new function_lambda_definition(_formal_parameters, (type_definition)_named_type_reference1, _i_l, null, _expression_list, "lambda" + lambda_num);
            object rt = _i_l;

            _procedure_definition.proc_body = _statement_list;

            //////////////////////////////vnutrennie lambda
            if (_procedure_definition.defs == null)
            {
                _procedure_definition.defs = new List <declaration>();
            }
            while (pascalABC_lambda_definitions.Count > 0 && pascalABC_lambda_definitions[pascalABC_lambda_definitions.Count - 1] != null)
            {
                _procedure_definition.defs.Add(lambda((function_lambda_definition)pascalABC_lambda_definitions[pascalABC_lambda_definitions.Count - 1]));
                pascalABC_lambda_definitions.RemoveAt(pascalABC_lambda_definitions.Count - 1);
            }
            if (pascalABC_lambda_definitions.Count > 0 && pascalABC_lambda_definitions[pascalABC_lambda_definitions.Count - 1] == null)
            {
                pascalABC_lambda_definitions.RemoveAt(pascalABC_lambda_definitions.Count - 1);
            }
            pascalABC_lambda_definitions.Add(_procedure_definition);
            ///////////////////////////////////////////////
            //parsertools.create_source_context(_procedure_definition, _expression_list, rt);
            ident _name = new ident(_procedure_definition.lambda_name);

            if (lr0 != null)
            {
                _name.source_context = _i_l.idents[0].source_context;
            }
            return(_name);
        }
		public virtual void post_do_visit(ident_list _ident_list)
		{
		}
        bool VisitInstanceDeclaration(type_declaration instanceDeclaration)
        {
            var instanceDefinition = instanceDeclaration.type_def as instance_definition;

            if (instanceDefinition == null)
            {
                return(false);
            }
            var instanceName = instanceDeclaration.type_name as typeclass_restriction;

            // If it is instance of derived typelass than it should have template parameters
            var templateArgs = new ident_list();
            where_definition_list whereSection = null;
            var originalTypeclass = instancesAndRestrictedFunctions.typeclasses[instanceName.name].type_def as typeclass_definition;
            var typeclassParents  = originalTypeclass.additional_restrictions;

            if (typeclassParents != null && typeclassParents.Count > 0)
            {
                whereSection = new where_definition_list();

                for (int i = 0; i < typeclassParents.Count; i++)
                {
                    ident template_name;
                    if (typeclassParents[i] is typeclass_reference tr)
                    {
                        string name = tr.names[0].name;
                        template_name = TypeclassRestrctionToTemplateName(name, tr.restriction_args);

                        whereSection.Add(GetWhereRestriction(
                                             TypeclassReferenceToInterfaceName(name, instanceName.restriction_args),
                                             template_name));
                    }
                    else
                    {
                        throw new NotImplementedException("Should be syntactic error");
                    }
                    templateArgs.Add(template_name);
                }
            }

            List <type_definition> templateLists = instanceName.restriction_args.params_list.Concat(templateArgs.idents.Select(x => new named_type_reference(x.name)).OfType <type_definition>()).ToList();
            var parents = new named_type_reference_list(new List <named_type_reference> {
                new template_type_reference(instanceName.name, new template_param_list(templateLists)),
                new template_type_reference("I" + instanceName.name, instanceName.restriction_args)
            });
            var instanceDefTranslated =
                SyntaxTreeBuilder.BuildClassDefinition(
                    parents,
                    null, instanceDefinition.body.class_def_blocks.ToArray());

            instanceDefTranslated.template_args  = templateArgs;
            instanceDefTranslated.where_section  = whereSection;
            instanceDefTranslated.source_context = instanceDefinition.source_context;

            for (int i = 0; i < instanceDefTranslated.body.class_def_blocks.Count; i++)
            {
                var cm = instanceDefTranslated.body.class_def_blocks[i].members;

                for (int j = 0; j < cm.Count; j++)
                {
                    procedure_header header = null;
                    if (cm[j] is procedure_header ph)
                    {
                        cm[j] = ph;
                    }
                    else if (cm[j] is procedure_definition pd)
                    {
                        header = pd.proc_header;
                    }
                    header.proc_attributes.Add(new procedure_attribute("override", proc_attribute.attr_override));
                    ConvertOperatorNameIdent(header);
                }
            }

            /*
             * {
             *  // Add constructor
             *  var cm = instanceDefTranslated.body.class_def_blocks[0];
             *  var def = new procedure_definition(
             *      new constructor(),
             *      new statement_list(new empty_statement()));
             *  def.proc_body.Parent = def;
             *  def.proc_header.proc_attributes = new procedure_attributes_list();
             *
             *  cm.Add(def);
             * }
             */
            var typeName = new ident(CreateInstanceName(instanceName.restriction_args as typeclass_param_list, instanceName.name), instanceName.source_context);

            var instanceDeclTranslated = new type_declaration(typeName, instanceDefTranslated, instanceDeclaration.source_context);

            instanceDeclTranslated.attributes = instanceDeclaration.attributes;
            AddAttribute(
                instanceDeclTranslated, "__TypeclassInstanceAttribute",
                new expression_list(new string_const(TypeclassRestrictionToString(instanceName))));
            AddAttribute(instanceDeclTranslated, "__TypeclassAttribute",
                         new expression_list(new string_const(TypeclassRestrictionToString(
                                                                  (originalTypeclass.Parent as type_declaration).type_name as typeclass_restriction))));

            Replace(instanceDeclaration, instanceDeclTranslated);
            visit(instanceDeclTranslated);

            return(true);
        }
		public virtual void visit(ident_list _ident_list)
		{
		}