示例#1
0
        public procedure_definition CreateAndAddToClassWriteProc(statement st, ident id, SourceContext sc)
        {
            var fp = SyntaxTreeBuilder.BuildFormalParameters(new List <ident>()
            {
                new ident("value")
            }, new List <type_definition>()
            {
                new no_type()
            });
            var pd = SyntaxTreeBuilder.BuildShortProcDefinition(fp, null, new method_name(id.name, sc), st, sc);

            return(pd);
        }
示例#2
0
 public override void visit(ident id)
 {
     if (MethodsStack.Count > 0 && id.name.ToLower() == "result")
     {
         IdResult = id;
         //throw new SyntaxVisitorError("FUNCTIONS_WITH_YIELDS_CANNOT_CONTAIN_RESULT", id.source_context);
     }
     //if (CurrentMethod == null || !HasYields)
     if (MethodsStack.Count == 0 || !HasYields)
     {
         return;
     }
 }
        public override void visit(ident id)
        {
            var name = id.name.ToLower();

            if (name.StartsWith("readinteger") || name.StartsWith("readreal") || name.StartsWith("readstring") ||
                name.StartsWith("readlninteger") || name.StartsWith("readlnreal") || name.StartsWith("readlnstring"))
            {
                ReadFuncCount++;
            }
            if (name.StartsWith("print"))
            {
                PrintCount++;
            }
        }
示例#4
0
        public override void visit(ident id)
        {
            int?paramNameLevel = null;

            var paramName = id.name;

            // Ищем с какого уровня имя
            for (int level = formalParametersStack.Count - 1; level >= 0; --level)
            {
                if (formalParametersStack[level].ContainsKey(paramName))
                {
                    // Нашли!
                    paramNameLevel = level;
                    break;
                }
            }

            bool isField = false;

            // Локальные параметры обрабатываются в другом визиторе

            // Параметр функции
            if ((object)paramNameLevel != null)
            {
                var upper = UpperNode();
                // Подозреваем обращение к параметру метода
                if ((object)upper == null || (object)upper != null && (upper as dot_node) == null)
                {
                    // Это не self.paramName - поле класса и не что-то другое?
                    // Нашли обращение к параметру?

                    var self = new ident("self", id.source_context);

                    // Заменяем paramName -> self.hoistedParamName: <>num__paramName

                    var hoistedParamName = new ident(formalParametersStack[(int)paramNameLevel][paramName], id.source_context);

                    var selfId = new dot_node(self, hoistedParamName);

                    Replace(id, selfId);
                }
                // Иначе проверить что это поле класса! self.paramName или какой-то другой очень извращенный вариант вроде (someMethod: self).paramName
            }

            // Поле класса

            // Параметр внешней функции (если наша - вложенная)

            // Глобальная переменная
        }
示例#5
0
            //internal RaiseRule<Expr> haltRule;
            public VarInfo(STBuilderZ3 stb, Symtab stab, iterexpr ie, Sort charsort)
            {
                this.stab     = stab;
                this.charsort = charsort;
                this.stb      = stb;
                this.binder   = ie.binder;
                binderid      = stab.Get(ie.binder).id;
                bekVarIds     = new List <int>();
                bekVarVals    = new List <Expr>();
                bekVarSorts   = new List <Sort>();

                proj = new Dictionary <int, int>();

                int regPosNr = 0;

                foreach (iterassgn ia in IterInfo.Initializers(ie, stab))
                {
                    proj[stab.Get(ia.lhs).id] = regPosNr;
                    bekVarIds.Add(stab.Get(ia.lhs).id);
                    bekVarVals.Add(MkExpr(stab.Get(ia.lhs).type, ia.rhs));
                    bekVarSorts.Add(BekTypeToSort(stab.Get(ia.lhs).type));
                    regPosNr += 1;
                }

                K = bekVarSorts.Count;

                //register sort
                regSort = (K == 0 ? stb.Solver.UnitSort : (K == 1 ? bekVarSorts[0] : stb.Solver.MkTupleSort(bekVarSorts.ToArray())));

                //initial register value
                initReg = (K == 0 ? stb.Solver.UnitConst : (K == 1 ? bekVarVals[0] : stb.Solver.MkTuple(bekVarVals.ToArray())));

                //input character variable
                c = this.stb.MkInputVariable(charsort);

                //register variable
                r = this.stb.MkRegister(regSort);

                //maps variable identifiers used in the bek program to corresponding term variables
                varMap           = new Dictionary <int, Expr>();
                varMap[binderid] = c;                              //input character variable

                for (int i = 0; i < K; i++)                        //bek pgm variables
                {
                    varMap[bekVarIds[i]] = (K == 1 ? r : stb.Solver.MkProj(i, r));
                }

                //haltRule = new RaiseRule<Expr>();
            }
示例#6
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));
     }
 }
示例#7
0
        public override void visit(ident id)
        {
            if (id.name != _oldName.name)
            {
                return;
            }

            var upperNode = UpperNode();

            if (
                (object)upperNode != null && (object)(upperNode as dot_node) == null)
            {
                Replace(id, _newName);
            }
        }
示例#8
0
        public statement_list NewLambdaBody(expression expr_l1, LexLocation loc)
        {
            var sl = new statement_list();

            sl.expr_lambda_body = true;
            var id = new ident("result");
            var op = new op_type_node(Operators.Assignment);
            //_op_type_node.source_context = parsertools.GetTokenSourceContext();
            var ass = new assign(id, expr_l1, op.type);

            parsertools.create_source_context(ass, id, expr_l1);
            sl.subnodes.Add(ass);
            sl.source_context = loc;
            return(sl);
        }
 public override void visit(ident id)
 {
     if (!InLambda) // мы ищем только в лямбдах
     {
         return;
     }
     if (HasCapturedParameter)
     {
         return;
     }
     if (idents.Select(i => i.name).Contains(id.name, StringComparer.OrdinalIgnoreCase))
     {
         HasCapturedParameter = true;
     }
 }
示例#10
0
        // Этот алгоритм маломощный и меняет всё внутри лямбды.
        // Например, если переименовывается x, то
        // в записи     t := y->begin var x := '4'; Result := x*2 end;
        // и в записи   t := x->x;
        // все x будут переименованы. Но это нестрашно, хотя неэффективно

        public override void visit(ident id)
        {
            if (id.name != _oldName)
            {
                return;
            }

            //var upperNode = UpperNode();
            //if (
            //    upperNode != null /*&& (upperNode as dot_node) == null*/) // Я не знаю, зачем вообще было второе условие. Видимо, это всё надо убрать SSM
            //{
            //Replace(id, _newName);
            // заменяются только строки, а сами идентификаторы как объекты не меняются!
            id.name = _newName;
            //}
        }
示例#11
0
 internal Expr ConvertToExpr(expr e, Dictionary <string, Expr> varInfo)
 {
     if (e is boolconst)
     {
         return(((boolconst)e).val ? smt.True : smt.False);
     }
     else if (e is charconst)
     {
         return(smt.MkNumeral(((charconst)e).val, smt.CharSort));
     }
     else if (e is ident)
     {
         ident i = (ident)e;
         if (!varInfo.ContainsKey(i.name))
         {
             throw new BekParseException(i.line, i.pos, string.Format("undefined '{0}'", i.name));
         }
         return(varInfo[i.name]);
     }
     else if (e is strconst)
     {
         return(smt.MkListFromString(((strconst)e).val, smt.CharSort));
     }
     else
     {
         functioncall f = e as functioncall; //must be != null
         if (f == null)
         {
             throw new BekException("Internal error, unexpected bek expression '{0}'");
         }
         try
         {
             Expr[] args = Array.ConvertAll(f.args.ToArray(), t => ConvertToExpr(t, varInfo));
             var    res  = smt.Library.ApplyFunction(f.id.name, args);
             return(res);
         }
         catch (BekParseException bek_error)
         {
             throw bek_error;
         }
         catch (Exception inner)
         {
             //add the line info
             throw new BekParseException(f.id.line, f.id.pos, inner);
         }
     }
 }
        public override void visit(ident id)
        {
            if (id.name != _oldName.name)
            {
                return;
            }

            var upperNode = UpperNode();

            if (
                (object)upperNode != null && (object)(upperNode as dot_node) == null)
            {
                //Replace(id, _newName);
                // заменяются только строки, а сами идентификаторы как объекты не меняются!
                id.name = _newName.name;
            }
        }
示例#13
0
        internal void PushIter(ident binder, iterinit initializer)
        {
            this.PushBlock();

            // clear names
            this.RemoveElt(binder.name);
            foreach (var assgn in initializer.assgns)
            {
                this.RemoveElt(assgn.lhs.name);
            }

            // re-assign names
            foreach (var assgn in initializer.assgns)
            {
                this.HandleLhs(assgn.lhs, iter_init_visitor.Visit(this, assgn.rhs), true);
            }
            this.HandleLhs(binder, BekTypes.CHAR, true);
        }
        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);
        }
示例#15
0
        public property_accessors NewPropertySpecifiersWrite(ident tkWrite, ident opt_identifier, property_accessors property_specifiers, LexLocation loc)
        {
            var nnpsw = property_specifiers;

            if (nnpsw == null)
            {
                nnpsw = new property_accessors();
            }
            if (opt_identifier != null)
            {
                nnpsw.write_accessor = new write_accessor_name(opt_identifier, tkWrite.source_context.Merge(opt_identifier.source_context));
            }
            else
            {
                nnpsw.write_accessor = new write_accessor_name(opt_identifier, tkWrite.source_context);
            }
            nnpsw.source_context = loc;
            return(nnpsw);
        }
        public for_node NewForStmt(bool opt_var, ident identifier, type_definition for_stmt_decl_or_assign, expression expr1, for_cycle_type fc_type, expression expr2, token_info opt_tk_do, statement stmt, LexLocation loc)
        {
            var nfs = new for_node(identifier, expr1, expr2, stmt, fc_type, null, for_stmt_decl_or_assign, opt_var != false, loc);

            if (opt_tk_do == null)
            {
                file_position    fp      = expr2.source_context.end_position;
                syntax_tree_node err_stn = stmt;
                if (err_stn == null)
                {
                    err_stn = expr2;
                }
                parsertools.errors.Add(new PABCNETUnexpectedToken(parsertools.CurrentFileName, StringResources.Get("TKDO"), new SourceContext(fp.line_num, fp.column_num + 1, fp.line_num, fp.column_num + 1, 0, 0), err_stn));
            }
            if (!opt_var && for_stmt_decl_or_assign == null)
            {
                parsertools.AddWarningFromResource("USING_UNLOCAL_FOR_VARIABLE", identifier.source_context);
            }
            return(nfs);
        }
示例#17
0
        public override void visit(ident value)
        {
            if (value == null)
            {
                return;
            }

            int pos = value.name.LastIndexOf('`');

            if (pos != -1)
            {
                value.name = value.name.Remove(pos);
            }

            SymbolInfo si = context.find_first(value.name);

            if (si == null)
            {
                return;                                               //ничего не нашли => переменная совсем локальная, никуда добавлять не нужно
            }
            if ((si.sym_info is SemanticTree.ICommonParameterNode) || //параметр или
                (si.sym_info is SemanticTree.ILocalVariableNode) ||   //локальная переменная
                (si.sym_info is SemanticTree.ICommonClassFieldNode) ||  //поле класса
                (si.sym_info is SemanticTree.ILocalBlockVariableNode) ||//локальная блочная переменная
                isLoopVariable)                                         //счетчик цикла
            {
                if (!Variables.Contains(si.sym_info as SemanticTree.IVAriableDefinitionNode))
                {
                    Variables.Add(si.sym_info as SemanticTree.IVAriableDefinitionNode);
                }
            }
            else if ((si.sym_info is SemanticTree.ICommonFunctionConstantDefinitionNode) ||//константа из функции
                     (si.sym_info is SemanticTree.IClassConstantDefinitionNode))   //константа из класса
            {
                if (!Constants.Contains(si.sym_info as SemanticTree.IConstantDefinitionNode))
                {
                    Constants.Add(si.sym_info as SemanticTree.IConstantDefinitionNode);
                }
            }
        }
示例#18
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));
                }
            }
        }
示例#19
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);
        }
        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);
            }
        }
示例#21
0
 public override void visit(ident id)
 {
     vars.Add(id.name);
 }
示例#22
0
        public override void visit(ident id)
        {
            var idName = id.name.ToLower();

            var si = _visitor.context.find(idName);

            if (si == null)
            {
                if (InLambdaContext)
                {
                    _visitor.AddError(new ThisTypeOfVariablesCannotBeCaptured(_visitor.get_location(id)));
                    return;
                }
                return;
            }

            if (si.sym_info.semantic_node_type == semantic_node_type.namespace_variable ||
                si.sym_info.semantic_node_type == semantic_node_type.common_namespace_function_node ||
                si.sym_info.semantic_node_type == semantic_node_type.namespace_constant_definition ||
                si.sym_info.semantic_node_type == semantic_node_type.compiled_function_node ||
                si.sym_info.semantic_node_type == semantic_node_type.common_method_node || // SSM bug fix  #167
                si.sym_info.semantic_node_type == semantic_node_type.compiled_namespace_node ||
                si.sym_info.semantic_node_type == semantic_node_type.compiled_variable_definition ||
                si.sym_info.semantic_node_type == semantic_node_type.common_type_node ||
                si.sym_info.semantic_node_type == semantic_node_type.compiled_type_node ||
                si.sym_info.semantic_node_type == semantic_node_type.basic_interface_node ||
                si.sym_info.semantic_node_type == semantic_node_type.common_unit_node ||
                si.sym_info.semantic_node_type == semantic_node_type.compiled_unit_node ||
                si.sym_info.semantic_node_type == semantic_node_type.template_type)
            {
                return;
            }

            var acceptableVarType = si.sym_info.semantic_node_type == semantic_node_type.local_variable ||
                                    si.sym_info.semantic_node_type == semantic_node_type.local_block_variable ||
                                    si.sym_info.semantic_node_type == semantic_node_type.common_parameter ||
                                    si.sym_info.semantic_node_type == semantic_node_type.class_field;

            if (!(acceptableVarType) && InLambdaContext)
            {
                _visitor.AddError(new ThisTypeOfVariablesCannotBeCaptured(_visitor.get_location(id)));
                return;
            }

            if (si.sym_info.semantic_node_type == semantic_node_type.class_field && InLambdaContext)
            {
                var semClassField = (class_field)si.sym_info;
                if (semClassField.polymorphic_state != polymorphic_state.ps_common)
                {
                    _visitor.AddError(new ThisTypeOfVariablesCannotBeCaptured(_visitor.get_location(id)));
                    return;
                }
            }

            if (si.scope == null)
            {
                return;
            }

            var scopeIndex      = si.scope.ScopeNum;
            var selfWordInClass = false;

            CapturedVariablesTreeNode scope;

            if (_scopesCapturedVarsNodesDictionary.TryGetValue(scopeIndex, out scope))
            {
                var prScope = scope as CapturedVariablesTreeNodeProcedureScope;
                if (prScope != null && acceptableVarType)
                {
                    if (si.sym_info.semantic_node_type == semantic_node_type.local_variable)
                    {
                        if (!(idName == compiler_string_consts.self_word && si.scope is SymbolTable.ClassMethodScope && _classScope != null) && InLambdaContext)
                        {
                            _visitor.AddError(new ThisTypeOfVariablesCannotBeCaptured(_visitor.get_location(id)));
                        }
                    }
                    if (si.sym_info.semantic_node_type == semantic_node_type.common_parameter && prScope.FunctionNode.parameters.First(v => v.name.ToLower() == idName).parameter_type != parameter_type.value && InLambdaContext)
                    {
                        _visitor.AddError(new CannotCaptureNonValueParameters(_visitor.get_location(id)));
                    }

                    if (idName == compiler_string_consts.self_word && si.scope is SymbolTable.ClassMethodScope &&
                        _classScope != null)
                    {
                        var selfField = _classScope.VariablesDefinedInScope.Find(var => var.SymbolInfo == si);

                        if (selfField == null)
                        {
                            _classScope.VariablesDefinedInScope.Add(
                                new CapturedVariablesTreeNode.CapturedSymbolInfo(null, si));
                        }

                        selfWordInClass = true;
                    }
                    else
                    {
                        var field = prScope.VariablesDefinedInScope.Find(var => var.SymbolInfo == si);

                        if (field == null)
                        {
                            prScope.VariablesDefinedInScope.Add(new CapturedVariablesTreeNode.CapturedSymbolInfo(null,
                                                                                                                 si));
                        }
                    }
                }

                var clScope = scope as CapturedVariablesTreeNodeClassScope;
                if (clScope != null && acceptableVarType)
                {
                    var field = clScope.VariablesDefinedInScope.Find(var => var.SymbolInfo == si);

                    if (field == null)
                    {
                        clScope.VariablesDefinedInScope.Add(new CapturedVariablesTreeNode.CapturedSymbolInfo(null, si));
                    }

                    if (si.access_level != access_level.al_public)
                    {
                        if (!clScope.NonPublicMembersNamesMapping.ContainsKey(idName))
                        {
                            var name          = LambdaHelper.GetNameForNonPublicMember(idName);
                            var semClassField = (class_field)si.sym_info;
                            var pn            = new common_property_node(name, _visitor.context._ctn, null, field_access_level.fal_public, semClassField.polymorphic_state);
                            pn.internal_property_type = _visitor.convert_strong(id).type;
                            clScope.NonPublicMembersNamesMapping.Add(idName, new Tuple <string, class_field, semantic_node>(name, semClassField, pn));
                        }
                    }
                }

                var idRef = (selfWordInClass ? _classScope : scope)
                            .VariablesDefinedInScope
                            .Find(var => var.SymbolInfo == si);

                if (idRef == null)                                     //TODO: Осторожнее переделать
                {
                    {
                        return;
                    }
                }

                if (_currentTreeNode.CorrespondingSyntaxTreeNode != null)
                {
                    var varName  = ((IVAriableDefinitionNode)idRef.SymbolInfo.sym_info).name;                     //TODO: случай параметров и полей класса!!!!!!!!!!!!!!!!!!
                    var substKey = new SubstitutionKey(varName, idRef.SyntaxTreeNodeWithVarDeclaration, _currentTreeNode.CorrespondingSyntaxTreeNode);

                    if (!_identsReferences.ContainsKey(substKey))
                    {
                        _identsReferences.Add(substKey, new List <ident>());
                    }

                    _identsReferences[substKey].Add(id);
                }

                if (InLambdaContext && scope is CapturedVariablesTreeNodeLambdaScope &&
                    scopeIndex < _currentLambdaScopeNodeStack.Peek().ScopeIndex) //TODO: Захват параметров лямбды в другой лямбде
                {
                    _visitor.AddError(new ThisTypeOfVariablesCannotBeCaptured(_visitor.get_location(id)));
                    return;
                }

                if (!InLambdaContext ||
                    scopeIndex >= _currentLambdaScopeNodeStack.Peek().ScopeIndex)
                {
                    return;
                }

                var stackAsList = _currentLambdaScopeNodeStack.ToList();
                stackAsList.RemoveAt(0);

                if (!_currentLambdaScopeNodeStack.Peek().CapturedVarsSymbolInfo.Contains(si))
                {
                    _currentLambdaScopeNodeStack.Peek().CapturedVarsSymbolInfo.Add(si);
                    foreach (var capturedVariablesTreeNodeLambdaScope in stackAsList)
                    {
                        if (!capturedVariablesTreeNodeLambdaScope.CapturedVarsSymbolInfo.Contains(si))
                        {
                            capturedVariablesTreeNodeLambdaScope.CapturedVarsSymbolInfo.Add(si);
                        }
                    }
                }
                if (!idRef.ReferencingLambdas.Contains(_currentLambdaScopeNodeStack.Peek()))
                {
                    idRef.ReferencingLambdas.Add(_currentLambdaScopeNodeStack.Peek());
                    foreach (var capturedVariablesTreeNodeLambdaScope in stackAsList)
                    {
                        if (!idRef.ReferencingLambdas.Contains(capturedVariablesTreeNodeLambdaScope))
                        {
                            idRef.ReferencingLambdas.Add(capturedVariablesTreeNodeLambdaScope);
                        }
                    }
                }
            }
        }
示例#23
0
 public override void visit(ident _ident)
 {
     text = "Name: " + _ident.name;
 }
        public override void visit(ident id)
        {
            // Check dot node
            var upper = UpperNode(1);
            //if (upper is dot_node)
            //    return;

            var idName          = id.name;
            var idSourceContext = id.source_context;

            // frninja 31/03/16 - фикс селфа для extensionmethod
            if (idName.ToLower() == "self" && !CollectedFormalParams.Contains(idName))
            {
                var newSelf = new dot_node(new ident("self"), new ident(YieldConsts.Self));
                Replace(id, newSelf);
                return;
            }

            // Detect where is id from
            if (CollectedLocals.Contains(idName))
            {
                Replace(id, new ident(CapturedLocalsMap[idName], idSourceContext));
            }
            else if (CollectedFormalParams.Contains(idName))
            {
                Replace(id, new ident(CapturedFormalParamsMap[idName], idSourceContext));
            }
            else if (IsInClassMethod)
            {
                // In class -> check fields
                //if (CollectedClassFields.Contains(idName))
                {
                    // Good
                    // Name in class fields -> capture as class field


                    //var capturedId = new dot_node(new dot_node(new ident("self"), new ident(YieldConsts.Self)), id);
                    //Replace(id, capturedId);
                }
                //else
                {
                    // Bad
                    // At syntax we don't know if the className is class field or not coz of e.g. base .NET classes
                    // HERE WE SHOULD REPLACE TO yield_unknown_reference -> so decision is passed to semantic
                    // Check for globals will be processed at semantic, too

                    if (!id.name.StartsWith("<")) // Check for already captured
                    {
                        Replace(id, new yield_unknown_ident(id, ClassName, this.IsStaticMethod));
                    }
                }
            }
            else
            {
                // Not in class -> check globals
                if (CollectedUnitGlobals.Contains(idName))
                {
                    // Global -> just do nothing
                }
                else
                {
                    // What about static classes - search at semantic
                    // HERE WE SHOULD REPLACE TO yield_unknown_reference -> so decision is passed to semantic
                }
            }
        }
        public ReplaceCapturedVariablesVisitor(IEnumerable <string> locals,
                                               IEnumerable <string> formalParams,
                                               IEnumerable <string> classFields,
                                               IEnumerable <string> classMethods,
                                               IEnumerable <string> classProperties,
                                               IEnumerable <string> unitGlobals,
                                               IDictionary <string, string> localsMap,
                                               IDictionary <string, string> formalParamsMap,
                                               bool isInClassMethod, bool isStaticMethod, ident className)
        {
            CollectedLocals       = new HashSet <string>(locals);
            CollectedFormalParams = new HashSet <string>(formalParams);
            CollectedClassFields  = new HashSet <string>(classFields);
            CollectedUnitGlobals  = new HashSet <string>(unitGlobals);

            CapturedLocalsMap       = new Dictionary <string, string>(localsMap);
            CapturedFormalParamsMap = new Dictionary <string, string>(formalParamsMap);

            IsInClassMethod = isInClassMethod;
            ClassName       = className;

            // Methods hack
            CollectedClassFields.UnionWith(classMethods);
            // Properties hack
            CollectedClassFields.UnionWith(classProperties);
        }
        /*public var_def_statement NewVarOrIdentifier(ident identifier, named_type_reference fptype, LexLocation loc)
         * {
         *  var n_t_r = fptype;
         *              var vds = new var_def_statement();
         *              vds.vars = new ident_list();
         *              vds.vars.idents.Add(identifier);
         *              vds.vars_type = n_t_r;
         *  vds.source_context = loc;
         *              return vds;
         * }*/

        /* Функция стала короткой и утратила необходимость
         * public statement_list NewLambdaBody(expression expr_l1, LexLocation loc)
         * {
         *  var sl = new statement_list();
         *  sl.expr_lambda_body = true;
         *  var id = new ident("result");
         *              var op = new op_type_node(Operators.Assignment);
         *              var ass = new assign(id, expr_l1, op.type);
         *              parsertools.create_source_context(ass, id, expr_l1); // дурацкая функция - если хотя бы у одного sc=null, то возвращает null
         *  if (ass.source_context == null)
         *      if (expr_l1.source_context != null)
         *          ass.source_context = expr_l1.source_context;
         *      else if (id.source_context != null)
         *          ass.source_context = id.source_context;
         *  sl.subnodes.Add(ass);
         *  sl.source_context = loc;
         *  var sl = new statement_list(new assign("result",expr_l1,loc),loc);
         *
         *  return sl;
         * }/**/

        public procedure_definition CreateAndAddToClassReadFunc(expression ex, ident id, SourceContext sc)
        {
            var fd = SyntaxTreeBuilder.BuildShortFuncDefinition(new formal_parameters(), null, new method_name(id.name, sc), new no_type(), ex, sc);

            return(fd);
        }
示例#27
0
		public virtual void post_do_visit(ident _ident)
		{
		}
示例#28
0
		public virtual void pre_do_visit(ident _ident)
		{
		}
示例#29
0
		public override void visit(ident _ident)
		{
			DefaultVisit(_ident);
			pre_do_visit(_ident);
			post_do_visit(_ident);
		}
 public NameExprPair(ident id, expression ex)
 {
     this.id = id;
     this.ex = ex;
 }
        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);
        }
示例#32
0
		public virtual void visit(ident _ident)
		{
		}
示例#33
0
		public override void visit(ident _ident)
		{
			executer.visit(_ident);
			if (_ident.attributes != null)
				this.visit((dynamic)_ident.attributes);
		}
		public virtual void visit(ident _ident)
		{
			DefaultVisit(_ident);
		}
示例#35
0
 public CollectClassMethodsVisitor(ident className)
 {
     CollectedMethods = new HashSet <ident>();
     _className       = className;
 }
示例#36
0
 public CollectClassPropertiesVisitor(ident className)
 {
     CollectedProperties = new HashSet <ident>();
     _className          = className;
 }