Ejemplo n.º 1
0
        public unit_name NewUnitHeading(ident unitkeyword, ident uname, LexLocation loc)
        {
            var un = new unit_name(uname, UnitHeaderKeyword.Unit, loc);
            if (unitkeyword.name.ToLower().Equals("library"))
				un.HeaderKeyword = UnitHeaderKeyword.Library;
            return un;
        }
Ejemplo n.º 2
0
        public override void visit(for_node fn)
        {
            ProcessNode(fn.statements);
            var b = HasStatementVisitor<yield_node>.Has(fn);
            if (!b)
                return;

            var gt1 = goto_statement.New;
            var gt2 = goto_statement.New;

            var endtemp = new ident(newVarName());
            var ass1 = new var_statement(fn.loop_variable, fn.type_name, fn.initial_value);
            var ass2 = new var_statement(endtemp, fn.type_name, fn.finish_value);


            var if0 = new if_node(bin_expr.Greater(fn.loop_variable, fn.finish_value), gt1);
            var lb2 = new labeled_statement(gt2.label, if0);
            var lb1 = new labeled_statement(gt1.label);
            var Inc = new procedure_call(new method_call(new ident("Inc"),new expression_list(fn.loop_variable)));

            ReplaceStatement(fn, SeqStatements(ass1,ass2,lb2, fn.statements, Inc, gt2, lb1));

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

            bl.defs.Add(new label_definitions(gt1.label, gt2.label));
        }
        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(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);
            }
        }
        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 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;

            if (idName.ToLower() == "self")
            {
                var newSelf = new dot_node(new ident("self"), new ident(Consts.Self));
                Replace(id, newSelf);
            }

            // 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(Consts.Self)), id);
                    Replace(id, capturedId);
                }
                else
                {
                    // Bad
                    // At syntax we don't know if the name 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
                }
            }
            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
                }
            }
        }
 private VarNames NewVarNames(ident name)
 {
     _varnum++;
     return new VarNames()
     {
         VarName = "$" + name.name + _varnum,
         VarEndName = "<>varLV" + _varnum
     };
 }
        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);
            }
        }
        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
            }

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

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

            // Глобальная переменная
        }
Ejemplo n.º 9
0
        public method_name NewQualifiedIdentifier(method_name qualified_identifier, ident identifier, LexLocation loc)
        {
            var nqi = qualified_identifier;
			nqi.class_name = nqi.meth_name;
			nqi.meth_name = identifier;
			nqi.source_context = loc;
            return nqi;
        }
Ejemplo n.º 10
0
 public override void visit(ident id)
 {
     if (indef)
         ids.Add(id.name);
 }
Ejemplo n.º 11
0
 public override void visit(ident id)
 {
     vars.Add(id.name);
 }
Ejemplo n.º 12
0
        public statement_list NewLambdaBody(expression expr_l1, LexLocation loc)
        {
            var _statement_list = new statement_list();
			var id = new ident("result");
			var _op_type_node = new op_type_node(Operators.Assignment);
			//_op_type_node.source_context = parsertools.GetTokenSourceContext();
			var _assign = new assign((addressed_value)id, expr_l1, _op_type_node.type);
			parsertools.create_source_context(_assign, id, expr_l1);
			_statement_list.subnodes.Add((statement)_assign);
            _statement_list.source_context = loc;
			//block _block = new block(null, _statement_list);
			return _statement_list;
        }
 public ReplaceForVariableVisitor(ident oldName, ident newName)
 {
     _oldName = oldName;
     _newName = newName;
 }
Ejemplo n.º 14
0
        public function_lambda_call NewFactor(ident func_decl_lambda, expression_list expr_list, LexLocation loc)
        {
            var fld = parsertools.find_pascalABC_lambda_name(func_decl_lambda.name);
            var _expression_list = expr_list;
			var _lambda_definition = fld;
			var _lambda_call = new function_lambda_call(_lambda_definition, _expression_list, loc);
			_lambda_call.source_context = func_decl_lambda.source_context;
			return _lambda_call;
        }
Ejemplo n.º 15
0
        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;
        }
        private void CheckVariableAlreadyDefined(ident id)
        {
            string name = id.name;

            if (IsVariableAlreadyDefined(name))
            {
                throw new PascalABCCompiler.Errors.SyntaxError(string.Format("Var {0} is already defined", name), "", id.source_context, id);
            }
        }
Ejemplo n.º 17
0
 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));
     }
     return nfs;
 }
 private SyntaxTree.procedure_call ConvertOperatorToProcedureCall(SyntaxTree.assign _assign)
 {
     SyntaxTree.ident operator_name = new PascalABCCompiler.SyntaxTree.ident(name_reflector.get_name(_assign.operator_type));
     operator_name.source_context = _assign.to.source_context;
     SyntaxTree.dot_node dot = new PascalABCCompiler.SyntaxTree.dot_node(_assign.to, operator_name);
     dot.source_context = _assign.to.source_context;
     SyntaxTree.expression_list exprlist = new SyntaxTree.expression_list();
     exprlist.expressions.Add(_assign.from);
     exprlist.source_context = _assign.to.source_context;
     SyntaxTree.method_call add_methcall = new SyntaxTree.method_call(exprlist);
     add_methcall.dereferencing_value = dot;
     add_methcall.source_context = _assign.source_context;
     SyntaxTree.procedure_call add_proccall = new SyntaxTree.procedure_call(add_methcall);
     add_proccall.source_context = _assign.source_context;
     return add_proccall;
 }
Ejemplo n.º 19
0
		public void write_ident(ident _ident)
		{
			write_addressed_value_funcname(_ident);
			if (_ident.name == null)
			{
				bw.Write((byte)0);
			}
			else
			{
				bw.Write((byte)1);
				bw.Write(_ident.name);
			}
		}
        public CollectClassFieldsVisitor(ident className)
        {
            CollectedFields = new HashSet<ident>();

            _className = className;
        }
Ejemplo n.º 21
0
 public static simple_property BuildSimpleReadWriteProperty(ident name, ident field, type_definition type)
 {
     return new simple_property(name, type, new property_accessors(new read_accessor_name(field), new write_accessor_name(field)));
 }
 private class_definition CreateHelperClassDefinition(ident className, procedure_definition pd, named_type_reference_list parents, params class_members[] cms)
 {
     if (className is template_type_name)
     {
         return SyntaxTreeBuilder.BuildClassDefinition(parents, (className as template_type_name).template_args , cms);
     }
     else if (pd.proc_header.template_args != null)
     {
         return SyntaxTreeBuilder.BuildClassDefinition(parents, pd.proc_header.template_args, cms);
     }
     return SyntaxTreeBuilder.BuildClassDefinition(parents, cms);
 }
 /// <summary>
 /// Создает имя вспомогательного класса
 /// </summary>
 /// <param name="helperName">Имя вспомогательного класса</param>
 /// <param name="className">Имя класса</param>
 /// <returns></returns>
 private ident CreateHelperClassName(string helperName, ident className, procedure_definition pd)
 {
     if (className is template_type_name)
     {
         return new template_type_name(helperName, (className as template_type_name).template_args);
     }
     else if (pd.proc_header.template_args != null)
     {
         return new template_type_name(helperName, pd.proc_header.template_args);
     }
     return new ident(helperName);
 }
 /// <summary>
 /// Создает обращение к имени класса по имени класса
 /// </summary>
 /// <param name="className">Имя класса</param>
 /// <returns></returns>
 private type_definition CreateClassReference(ident className)
 {
     if (className is template_type_name)
     {
         return new template_type_reference(
             new named_type_reference(className),
             new template_param_list(string.Join(",", (className as template_type_name).template_args.idents.Select(id => id.name)))
             );
     }
     return new named_type_reference(className);
 }
 public CollectClassPropertiesVisitor(ident className)
 {
     CollectedProperties = new HashSet<ident>();
     _className = className;
 }
Ejemplo n.º 26
0
 public NameExprPair(ident id, expression ex)
 {
     this.id = id;
     this.ex = ex;
 }
Ejemplo n.º 27
0
		public void visit(ident _ident)
		{
			bw.Write((Int16)4);
			write_ident(_ident);
		}
Ejemplo n.º 28
0
        public property_accessors NewPropertySpecifiersRead(ident tkRead, ident opt_identifier, property_accessors property_specifiers, LexLocation loc)
        {
            var nnps = property_specifiers;
			if (nnps == null) 
			{
				nnps = new property_accessors();
			}
            if (opt_identifier != null && opt_identifier.name.ToLower() == "write")
            {
                nnps.read_accessor = new read_accessor_name(null);
                nnps.write_accessor = new write_accessor_name(null);
                nnps.read_accessor.source_context = tkRead.source_context;
                nnps.write_accessor.source_context = opt_identifier.source_context;
            }
            else
            {
                if (opt_identifier != null)
                    nnps.read_accessor = new read_accessor_name(opt_identifier, tkRead.source_context.Merge(opt_identifier.source_context));
                else nnps.read_accessor = new read_accessor_name(opt_identifier, tkRead.source_context);

            }
			nnps.source_context = loc;
            return nnps;
        }
 private void AddState(out int stateNumber, out ident resumeLabel)
 {
     stateNumber = curState++;
     resumeLabel = null;
 }
Ejemplo n.º 30
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;
        }