public override void visit(method_call mc) { /*if (mc.dereferencing_value is ident id && (id.name.ToLower() == "read" || id.name.ToLower() == "readln")) * { * syntax_tree_node n = mc; * do * { * n = n.Parent; * } while (n != null && !(n is class_members)); * if (n != null) * ; * //ReadProc = false; * else * ReadProc += 1; * }*/ /*if (mc.dereferencing_value is ident id2) * { * var name = id2.name.ToLower(); * var h = new HashSet<string> { "readinteger", "readlninteger", "readreal", "readlnreal", "readstring", "readlnstring", "readchar", "readlnchar" }; * if (h.Contains(name)) * ReadFuncCount++; * }*/ /*if (mc.dereferencing_value is ident id1 && (id1.name.ToLower() == "write" || id1.name.ToLower() == "writeln") && * mc.parameters != null && mc.parameters.expressions.Any(ex => ex is char_const cc && cc.cconst == ' ')) * { * WriteProcWithSpace += 1; * }*/ base.visit(mc); }
expression_list construct_expression_list_for_slice_expr_multi(slice_expr sl) { if (sl.slices == null) { return(null); // упадёт - это ошибка компилятора } var el = new expression_list(); // будем наполнять кортежами - самое простое var sc = sl.source_context; foreach (var slice in sl.slices) { var tup = new dot_node(new dot_node(new ident("?System", sc), new ident("Tuple", sc), sc), new ident("Create", sc), sc); var eel = new expression_list(); // пытаемся разобраться с ^1 var sl1 = slice.Item1; eel.Add(sl1); IndexVisitor.New.ProcessNode(sl1); // индексный визитор сам не вызывается поскольку в многомерных срезах хранится List кортежей троек expression, который сам не обходится var sl2 = slice.Item2; eel.Add(sl2); IndexVisitor.New.ProcessNode(sl2); var sl3 = slice.Item3; // и step тоже надо обходить!!! eel.Add(sl3); IndexVisitor.New.ProcessNode(sl3); var mc = new method_call(tup, eel, sc); // sc - не очень хорошо - ошибка будет в общем месте el.Add(mc); // по идее все параметры готовы. Надо только проверить, что они целые } return(el); }
public override void visit(method_call _method_call) { _method_call.dereferencing_value.visit(this); if (_method_call.parameters != null) { _method_call.parameters.visit(this); } }
private expression DesugarDeconstructorPatternParameters(deconstructor_pattern pattern) { expression paramCheckExpr = null; for (int i = 0; i < pattern.parameters.Count; ++i) { if (pattern.parameters[i] is const_pattern_parameter constPattern) { var constParamIdent = new ident(NewDeconstructParamId(), pattern.parameters[i].source_context); var eqParams = new expression_list( new List <expression>() { constPattern.const_param, constParamIdent } ); var constParamCheck = new method_call( new dot_node(new ident("object"), new ident("Equals")), eqParams, pattern.source_context ); pattern.parameters[i] = new var_deconstructor_parameter( constParamIdent, GetTypeDefinitionForConstParam(constPattern.const_param), false, pattern.parameters[i].source_context); paramCheckExpr = paramCheckExpr == null ? (expression)constParamCheck : bin_expr.LogicalAnd(paramCheckExpr, constParamCheck); } if (pattern.parameters[i] is wild_card_deconstructor_parameter) { var wildCardGeneratedParamIdent = new ident(NewDeconstructParamId(), pattern.parameters[i].source_context); pattern.parameters[i] = new var_deconstructor_parameter( wildCardGeneratedParamIdent, null, false, pattern.parameters[i].source_context); } if (pattern.parameters[i] is recursive_deconstructor_parameter deconstructor_param) { if (deconstructor_param.pattern is deconstructor_pattern deconstructor_pattern) { var recursiveChecks = DesugarDeconstructorPatternParameters(deconstructor_pattern); paramCheckExpr = paramCheckExpr == null ? recursiveChecks : bin_expr.LogicalAnd(paramCheckExpr, recursiveChecks); } } } return(paramCheckExpr); }
public addressed_value Into(addressed_value x, addressed_value v) // При возникновении новой конструкции в грамматике variable добавить обработку сюда { if (v.GetType() == typeof(dot_question_node)) { var vv = v as dot_question_node; var res = new dot_question_node(Into(x, vv.left), vv.right, x.source_context); return(res); } else if (v.GetType() == typeof(dot_node)) { var vv = v as dot_node; var res = new dot_node(Into(x, vv.left), vv.right, x.source_context); return(res); } else if (v.GetType() == typeof(indexer)) { var vv = v as indexer; var res = new indexer(Into(x, vv.dereferencing_value), vv.indexes, x.source_context); return(res); } else if (v.GetType() == typeof(slice_expr)) { var vv = v as slice_expr; var res = new slice_expr(Into(x, vv.dereferencing_value), vv.from, vv.to, vv.step, x.source_context); return(res); } else if (v.GetType() == typeof(slice_expr_question)) { var vv = v as slice_expr_question; var res = new slice_expr_question(Into(x, vv.dereferencing_value), vv.from, vv.to, vv.step, x.source_context); return(res); } else if (v.GetType() == typeof(method_call)) { var vv = v as method_call; var res = new method_call(Into(x, vv.dereferencing_value), vv.parameters, x.source_context); return(res); } else if (v.GetType() == typeof(roof_dereference)) { var vv = v as roof_dereference; var res = new roof_dereference(Into(x, vv.dereferencing_value), x.source_context); return(res); } else if (v.GetType() == typeof(ident_with_templateparams)) { var vv = v as ident_with_templateparams; var res = new ident_with_templateparams(Into(x, vv.name), vv.template_params, x.source_context); return(res); } else { var res = new dot_node(x, v, x.source_context); return(res); } }
public override void visit(tuple_node tup) { var dn = new dot_node(new dot_node(new ident("?System"), new ident("Tuple")), new ident("Create", tup.source_context)); var mc = new method_call(dn, tup.el, tup.source_context); //var sug = new sugared_expression(tup, mc, tup.source_context); - нет никакой семантической проверки - всё - на уровне синтаксиса! ReplaceUsingParent(tup, mc); visit(mc); }
private expression GetCollectionItemsEqualCheckAfterGap(addressed_value matchingExpression, List <pattern_parameter> toCompare, CollectionDesugaringResult desugaringResult) { var elemFromTail = 1; expression equalChecks = null; foreach (var param in toCompare) { var indexerCall = new indexer( matchingExpression, new expression_list( new bin_expr( new method_call( new dot_node( matchingExpression, new ident("Count", matchingExpression.source_context)), new expression_list()), new int32_const(elemFromTail, matchingExpression.source_context), Operators.Minus), matchingExpression.source_context), matchingExpression.source_context); if (param is const_pattern_parameter constParam) { var eqParams = new expression_list( new List <expression>() { indexerCall, constParam.const_param } ); var equalCall = new method_call( new dot_node( new ident("object"), new ident("Equals")), eqParams, matchingExpression.source_context ); equalChecks = equalChecks == null ? (expression)equalCall : bin_expr.LogicalAnd(equalChecks, equalCall); desugaringResult.ElemTypeChecks.Add(GetTypeCompatibilityCheck(indexerCall, constParam.const_param)); } if (param is collection_pattern_var_parameter varParam) { desugaringResult.VarParametersDeclarations.Add( new var_statement(varParam.identifier, indexerCall)); } ++elemFromTail; } return(equalChecks); }
public expression NewFormatString(string_const str) { try { method_call mc = new method_call(); mc.dereferencing_value = new dot_node(new ident("string", str.source_context), new ident("Format", str.source_context), str.source_context); mc.parameters = new expression_list(); //string[] arr = Regex.Split(str.Value, @"\{[\w\d._]+\}"); //Match match = Regex.Match(str.Value, @"\{[\w\d._]+\}"); string[] arr = Regex.Split(str.Value, @"\{[^\}]+\}"); Match match = Regex.Match(str.Value, @"\{[^\}]+\}"); List <string> vars = new List <string>(); //Dictionary<string, int> var_offsets = new Dictionary<string, int>(); List <int> var_offsets = new List <int>(); while (match.Success) { string s = match.Value.Replace("{", "").Replace("}", ""); vars.Add(s); var_offsets.Add(match.Index); match = match.NextMatch(); } if (vars.Count == 0) { parsertools.errors.Add(new bad_format_string(parsertools.CurrentFileName, str.source_context, str)); return(str); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.Length; i++) { sb.Append(arr[i]); if (i < arr.Length - 1) { sb.Append("{" + i + "}"); } } mc.parameters.Add(new string_const(sb.ToString(), str.source_context), str.source_context); for (int i = 0; i < vars.Count; i++) { string s = vars[i]; var expr = ParseExpression(new string('\n', str.source_context.begin_position.line_num - 1) + new string(' ', str.source_context.begin_position.column_num + var_offsets[i] + 2) + s, str.source_context.begin_position.line_num, str.source_context.begin_position.column_num + var_offsets[i] + 2); expr.source_context.begin_position.line_num = str.source_context.begin_position.line_num; expr.source_context.end_position.line_num = str.source_context.end_position.line_num; mc.parameters.Add(expr); } mc.source_context = str.source_context; return(mc); } catch (Exception ex) { parsertools.errors.Add(new bad_format_string(parsertools.CurrentFileName, str.source_context, str)); } return(str); }
public override void visit(tuple_node tup) { var dn = new dot_node(new dot_node(new ident("?System"), new ident("Tuple")), new ident("Create", tup.source_context)); var mc = new method_call(dn, tup.el, tup.source_context); //var sug = new sugared_expression(tup, mc, tup.source_context); - нет никакой семантической проверки - всё - на уровне синтаксиса! //ReplaceUsingParent(tup, mc); - исправление #1199. Оказывается, ReplaceUsingParent и Replace не эквивалентны - у копии Parent на старого родителя Replace(tup, mc); visit(mc); }
private TupleDesugaringResult DesugarTuplePattern(tuple_pattern pattern, expression matchingExpression) { Debug.Assert(!pattern.IsRecursive, "All recursive patterns should be desugared into simple patterns at this point"); var desugaringResult = new TupleDesugaringResult(); var tupleItems = pattern.parameters; for (int i = 0; i < tupleItems.Count; ++i) { var tupleItemCall = new dot_node( matchingExpression as addressed_value, new ident("Item" + (i + 1).ToString()), matchingExpression.source_context); if (tupleItems[i] is tuple_pattern_var_parameter varParam) { desugaringResult.VarParametersDeclarations.Add( new var_statement( varParam.identifier, tupleItemCall, matchingExpression.source_context ) ); } if (tupleItems[i] is const_pattern_parameter constParam) { var eqParams = new expression_list( new List <expression>() { tupleItemCall, constParam.const_param } ); var equalCall = new method_call( new dot_node(new ident("object"), new ident("Equals")), eqParams, pattern.source_context ); desugaringResult.SuccessMatchingCheck = desugaringResult.SuccessMatchingCheck == null ? (expression)equalCall : bin_expr.LogicalAnd(desugaringResult.SuccessMatchingCheck, equalCall); desugaringResult.ElemTypeChecks.Add(GetTypeCompatibilityCheck(tupleItemCall, constParam.const_param)); } } desugaringResult.TupleLengthCheck = GetTypeCompatibilityCheck(matchingExpression, new int32_const(tupleItems.Count)); if (desugaringResult.SuccessMatchingCheck == null) { desugaringResult.SuccessMatchingCheck = new bool_const(true); } return(desugaringResult); }
public void Emit_Last_Parameter(object o) { if (o is method_call) { method_call mc = o as method_call; mc.param_count++; parse_tree_pkg.emit_method_call_il(mc.name, mc.param_count, this); } else if (o is subchart_call) { subchart_call oc = o as subchart_call; gen.EmitCall(System.Reflection.Emit.OpCodes.Call, oc.proc.subMethodBuilder, null); } }
private expression GetCollectionItemsEqualCheckBeforeGap(addressed_value matchingExpression, List <pattern_parameter> toCompare, CollectionDesugaringResult desugaringResult) { var fromIndex = 0; expression equalChecks = null; foreach (var param in toCompare) { if (param is const_pattern_parameter constParam) { var indexerCall = new indexer( matchingExpression, new expression_list( new int32_const(fromIndex, matchingExpression.source_context), matchingExpression.source_context), matchingExpression.source_context); var eqParams = new expression_list( new List <expression>() { indexerCall, constParam.const_param } ); var equalCall = new method_call( new dot_node( new ident("object"), new ident("Equals")), eqParams, matchingExpression.source_context ); equalChecks = equalChecks == null ? (expression)equalCall : bin_expr.LogicalAnd(equalChecks, equalCall); desugaringResult.ElemTypeChecks.Add(GetTypeCompatibilityCheck(indexerCall, constParam.const_param)); } if (param is collection_pattern_var_parameter varParam) { desugaringResult.VarParametersDeclarations.Add( new var_statement(varParam.identifier, GetIndexerCallForCollectionPattern(matchingExpression as addressed_value, fromIndex))); } ++fromIndex; } return(equalChecks); }
/*private expression convert_field_reference_expression(ICSharpCode.NRefactory.Ast.FieldReferenceExpression expr) * { * expression obj = convert_expression(expr.TargetObject); * if (!string.IsNullOrEmpty(expr.FieldName)) * return new dot_node(obj as addressed_value,new ident(expr.FieldName)); * else return obj; * }*/ private expression convert_invocation_expression(ICSharpCode.NRefactory.Ast.InvocationExpression expr) { List <expression> prms = new List <expression>(); for (int i = 0; i < expr.Arguments.Count; i++) { prms.Add(convert_expression(expr.Arguments[i])); } expression obj = convert_expression(expr.TargetObject); method_call mcall = new method_call(); mcall.dereferencing_value = obj as addressed_value; mcall.parameters = new expression_list(); mcall.parameters.expressions.AddRange(prms); return(mcall); }
public override void visit(index ind) { var indexCreation = new method_call( new dot_node( new ident("SystemIndex", ind.source_context), new ident("Create", ind.source_context), ind.source_context), new expression_list( new List<expression>() { ind.index_expr, new bool_const(ind.inverted, ind.source_context) }, ind.source_context), ind.source_context); syntax_tree_node mc = null; var possibleIndexer = ind.Parent?.Parent; if (possibleIndexer != null && possibleIndexer is indexer indexer) { // Надо подняться до узла indexer и запомнить индекс, под которым данный index входит // Идём по Parent - и смотрим, когда Parent = indexer // Находим у него expressions и ищем, под каким индексом в нем содержится текущий. // Запоминаем это целое число и передаем его последним параметром в Reverse если expressions.Count > 1 expression_list reverseIndexMethodParams = null; if (indexer.indexes.expressions.Count == 1) reverseIndexMethodParams = new expression_list(indexer.dereferencing_value, ind.source_context); else { var i = indexer.indexes.expressions.FindIndex(x => x == ind); if (i >= 0) reverseIndexMethodParams = new expression_list(new List<expression> { indexer.dereferencing_value, new int32_const(i) }, ind.source_context); } mc = new method_call( new dot_node(indexCreation, new ident("Reverse", ind.source_context)), reverseIndexMethodParams, ind.source_context); } else // Это непонятная ветка. Она наступает в частности если индексер не находится на 2 уровня выше, что бывает в случае индекса вида a[1..^1] { mc = indexCreation; } //var sug = new sugared_expression(ind, mc, ind.source_context); ReplaceUsingParent(ind, mc); visit(mc); }
public override void visit(method_call methodCall) { var methodName = methodCall.dereferencing_value as ident_with_templateparams; if (methodName == null) { DefaultVisit(methodCall); return; } var typeclassRestrictions = methodName.template_params as typeclass_param_list; if (typeclassRestrictions == null) { DefaultVisit(methodCall); return; } var paramList = new List <type_definition>(); paramList.AddRange(typeclassRestrictions.params_list); // TODO: Add template types for typeclass instances var methodStrName = (methodName.name as ident).name; var typeclasses = instancesAndRestrictedFunctions.restrictedFunctions[methodStrName]; List <type_definition> newParams = GetTranslatedTypeclassParameters(paramList, typeclasses); paramList.AddRange(newParams); var methodCallTranslated = new method_call( new ident_with_templateparams(methodName.name, new template_param_list(paramList), methodName.source_context), methodCall.parameters, methodCall.source_context); Replace(methodCall, methodCallTranslated); }
public override void visit(index ind) { var indexCreation = new method_call( new dot_node( new ident("SystemIndex", ind.source_context), new ident("Create", ind.source_context), ind.source_context), new expression_list( new List <expression>() { ind.index_expr, new bool_const(ind.inverted, ind.source_context) }, ind.source_context), ind.source_context); syntax_tree_node mc = null; var possibleIndexer = ind.Parent?.Parent; if (possibleIndexer != null && possibleIndexer is indexer indexer) { var reverseIndexMethodParams = new expression_list(indexer.dereferencing_value, ind.source_context); mc = new method_call( new dot_node(indexCreation, new ident("Reverse", ind.source_context)), reverseIndexMethodParams, ind.source_context); } else { mc = indexCreation; } //var sug = new sugared_expression(ind, mc, ind.source_context); Replace(ind, mc); visit(mc); }
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(method_call _method_call) { }
public override void visit(method_call _method_call) { executer.visit(_method_call); if (_method_call.parameters != null) this.visit((dynamic)_method_call.parameters); if (_method_call.dereferencing_value != null) this.visit((dynamic)_method_call.dereferencing_value); if (_method_call.attributes != null) this.visit((dynamic)_method_call.attributes); }
public virtual void visit(method_call _method_call) { DefaultVisit(_method_call); }
protected override void DoAction(int action) { switch (action) { case 2: // module -> MODULE, ident, SEMICOLUMN, mainblock, ident, COMMA { if (ValueStack[ValueStack.Depth - 5].id.name != ValueStack[ValueStack.Depth - 2].id.name) { PT.AddError("Имя " + ValueStack[ValueStack.Depth - 2].id.name + " должно совпадать с именем модуля " + ValueStack[ValueStack.Depth - 5].id.name, LocationStack[LocationStack.Depth - 2]); } // Подключение стандартного модуля Oberon00System, написанного на PascalABC.NET var ul = new uses_list("Oberon00System"); // Формирование модуля основной программы (используется фабричный метод вместо конструктора) root = program_module.create(ValueStack[ValueStack.Depth - 5].id, ul, ValueStack[ValueStack.Depth - 3].bl, CurrentLocationSpan); } 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: // mainblock -> Declarations, BEGIN, StatementSequence, END { CurrentSemanticValue.bl = new block(ValueStack[ValueStack.Depth - 4].decl, ValueStack[ValueStack.Depth - 2].sl, CurrentLocationSpan); } break; case 6: // SetConstant -> LBRACE, SetElemList, RBRACE { CurrentSemanticValue.sc = ValueStack[ValueStack.Depth - 2].sc; } break; case 7: // SetElemList -> SetElem { CurrentSemanticValue.sc = new pascal_set_constant(); CurrentSemanticValue.sc.Add(ValueStack[ValueStack.Depth - 1].ex); } break; case 8: // SetElemList -> SetElemList, COLUMN, SetElem { CurrentSemanticValue.sc = ValueStack[ValueStack.Depth - 3].sc; CurrentSemanticValue.sc.Add(ValueStack[ValueStack.Depth - 1].ex); } break; case 9: // SetElemList -> /* empty */ { CurrentSemanticValue.sc = new pascal_set_constant(); } break; case 11: // SetElem -> expr, DOUBLEPOINT, expr { CurrentSemanticValue.ex = new diapason_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex); } break; case 12: // expr -> ident { CurrentSemanticValue.ex = ValueStack[ValueStack.Depth - 1].id; } break; case 13: // expr -> INTNUM { CurrentSemanticValue.ex = new int32_const(ValueStack[ValueStack.Depth - 1].iVal, CurrentLocationSpan); } break; case 14: // expr -> LONGINTNUM { CurrentSemanticValue.ex = new int64_const(ValueStack[ValueStack.Depth - 1].lVal, CurrentLocationSpan); } break; case 15: // expr -> REALNUM { CurrentSemanticValue.ex = new double_const(ValueStack[ValueStack.Depth - 1].rVal, CurrentLocationSpan); } break; case 16: // expr -> TRUE { CurrentSemanticValue.ex = new bool_const(true, CurrentLocationSpan); } break; case 17: // expr -> FALSE { CurrentSemanticValue.ex = new bool_const(false, CurrentLocationSpan); } break; case 18: // expr -> CHAR_CONST { CurrentSemanticValue.ex = new char_const(ValueStack[ValueStack.Depth - 1].cVal, CurrentLocationSpan); } break; case 19: // expr -> STRING_CONST { CurrentSemanticValue.ex = new string_const(ValueStack[ValueStack.Depth - 1].sVal, CurrentLocationSpan); } break; case 20: // expr -> MINUS, expr { CurrentSemanticValue.ex = new un_expr(ValueStack[ValueStack.Depth - 1].ex, Operators.Minus, CurrentLocationSpan); } break; case 21: // expr -> PLUS, expr { CurrentSemanticValue.ex = new un_expr(ValueStack[ValueStack.Depth - 1].ex, Operators.Plus, CurrentLocationSpan); } break; case 22: // expr -> LPAREN, expr, RPAREN { CurrentSemanticValue.ex = ValueStack[ValueStack.Depth - 2].ex; } break; case 23: // expr -> NOT, expr { CurrentSemanticValue.ex = new un_expr(ValueStack[ValueStack.Depth - 1].ex, Operators.LogicalNOT, CurrentLocationSpan); } break; case 24: // expr -> expr, PLUS, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Plus, CurrentLocationSpan); } break; case 25: // expr -> expr, MINUS, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Minus, CurrentLocationSpan); } break; case 26: // expr -> expr, MULT, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Multiplication, CurrentLocationSpan); } break; case 27: // expr -> expr, DIVIDE, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Division, CurrentLocationSpan); } break; case 28: // expr -> expr, DIV, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.IntegerDivision, CurrentLocationSpan); } break; case 29: // expr -> expr, MOD, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.ModulusRemainder, CurrentLocationSpan); } break; case 30: // expr -> expr, AND, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.LogicalAND, CurrentLocationSpan); } break; case 31: // expr -> expr, OR, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.LogicalOR, CurrentLocationSpan); } break; case 32: // expr -> expr, EQ, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Equal, CurrentLocationSpan); } break; case 33: // expr -> expr, NE, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.NotEqual, CurrentLocationSpan); } break; case 34: // expr -> expr, LT, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Less, CurrentLocationSpan); } break; case 35: // expr -> expr, LE, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.LessEqual, CurrentLocationSpan); } break; case 36: // expr -> expr, GT, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.Greater, CurrentLocationSpan); } break; case 37: // expr -> expr, GE, expr { CurrentSemanticValue.ex = new bin_expr(ValueStack[ValueStack.Depth - 3].ex, ValueStack[ValueStack.Depth - 1].ex, Operators.GreaterEqual, CurrentLocationSpan); } break; case 39: // Assignment -> ident, ASSIGN, expr { CurrentSemanticValue.st = new assign(ValueStack[ValueStack.Depth - 3].id, ValueStack[ValueStack.Depth - 1].ex, Operators.Assignment, CurrentLocationSpan); } break; case 40: // 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 41: // 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 42: // 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 43: // 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 44: // factparams -> expr { CurrentSemanticValue.el = new expression_list(ValueStack[ValueStack.Depth - 1].ex, CurrentLocationSpan); } break; case 45: // 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 46: // ProcCallStatement -> ident, LPAREN, factparams, RPAREN { CurrentSemanticValue.st = new method_call(ValueStack[ValueStack.Depth - 4].id, ValueStack[ValueStack.Depth - 2].el, CurrentLocationSpan); } break; case 47: // EmptyStatement -> /* empty */ { CurrentSemanticValue.st = new empty_statement(); } break; case 54: // StatementSequence -> Statement { CurrentSemanticValue.sl = new statement_list(ValueStack[ValueStack.Depth - 1].st, CurrentLocationSpan); } break; case 55: // 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 56: // type -> ID { CurrentSemanticValue.ntr = new named_type_reference(PT.InternalTypeName(ValueStack[ValueStack.Depth - 1].sVal), CurrentLocationSpan); } break; case 57: // IDList -> ident { CurrentSemanticValue.il = new ident_list(ValueStack[ValueStack.Depth - 1].id, CurrentLocationSpan); } break; case 58: // 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 59: // 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 60: // VarDeclarations -> VarDecl { CurrentSemanticValue.vdss = new variable_definitions(ValueStack[ValueStack.Depth - 1].vds, CurrentLocationSpan); } break; case 61: // VarDeclarations -> VarDeclarations, VarDecl { ValueStack[ValueStack.Depth - 2].vdss.Add(ValueStack[ValueStack.Depth - 1].vds, CurrentLocationSpan); CurrentSemanticValue.vdss = ValueStack[ValueStack.Depth - 2].vdss; } break; case 62: // ConstDecl -> ident, EQ, ConstExpr, SEMICOLUMN { CurrentSemanticValue.scd = new simple_const_definition(ValueStack[ValueStack.Depth - 4].id, ValueStack[ValueStack.Depth - 2].ex, CurrentLocationSpan); } break; case 64: // ConstDeclarations -> ConstDecl { CurrentSemanticValue.cdl = new consts_definitions_list(ValueStack[ValueStack.Depth - 1].scd, CurrentLocationSpan); } break; case 65: // ConstDeclarations -> ConstDeclarations, ConstDecl { ValueStack[ValueStack.Depth - 2].cdl.Add(ValueStack[ValueStack.Depth - 1].scd, CurrentLocationSpan); CurrentSemanticValue.cdl = ValueStack[ValueStack.Depth - 2].cdl; } break; case 66: // ConstDeclarationsSect -> CONST, ConstDeclarations { CurrentSemanticValue.cdl = ValueStack[ValueStack.Depth - 1].cdl; CurrentSemanticValue.cdl.source_context = CurrentLocationSpan; } break; case 67: // VarDeclarationsSect -> VAR, VarDeclarations { CurrentSemanticValue.vdss = ValueStack[ValueStack.Depth - 1].vdss; CurrentSemanticValue.vdss.source_context = CurrentLocationSpan; } break; case 68: // DeclarationsSect -> VarDeclarationsSect { CurrentSemanticValue.decsec = ValueStack[ValueStack.Depth - 1].vdss; } break; case 69: // DeclarationsSect -> ConstDeclarationsSect { CurrentSemanticValue.decsec = ValueStack[ValueStack.Depth - 1].cdl; } break; case 70: // DeclarationsSect -> ProcedureDeclarationSect { CurrentSemanticValue.decsec = ValueStack[ValueStack.Depth - 1].pd; } break; case 71: // Declarations -> /* empty */ { CurrentSemanticValue.decl = new declarations(); } break; case 72: // Declarations -> Declarations, DeclarationsSect { if (ValueStack[ValueStack.Depth - 1].decsec != null) { ValueStack[ValueStack.Depth - 2].decl.Add(ValueStack[ValueStack.Depth - 1].decsec); } CurrentSemanticValue.decl = ValueStack[ValueStack.Depth - 2].decl; CurrentSemanticValue.decl.source_context = CurrentLocationSpan; // Необходимо показать место в программе, т.к. невно это не сделано // (например, в конструкторе) } break; case 73: // ProcedureDeclarationSect -> PROCEDURE, ident, maybeformalparams, maybereturn, // SEMICOLUMN, mainblock, ident, SEMICOLUMN { } break; case 74: // maybeformalparams -> /* empty */ { //$$ = null; } break; case 75: // maybeformalparams -> LPAREN, FPList, RPAREN { //$$ = $2; } break; case 76: // maybereturn -> /* empty */ { } break; case 77: // maybereturn -> COLUMN, type { } break; case 78: // FPList -> FPSect { } break; case 79: // FPList -> FPList, SEMICOLUMN, FPSect { } break; case 80: // FPSect -> maybevar, IDList, COLON, type { } break; case 81: // maybevar -> /* empty */ { CurrentSemanticValue.bVal = false; } break; case 82: // maybevar -> VAR { CurrentSemanticValue.bVal = true; } break; } }
public virtual void post_do_visit(method_call _method_call) { }
public override void visit(method_call _method_call) { prepare_node(_method_call.dereferencing_value, "dereferencing value"); prepare_node(_method_call.parameters, "parameters"); }
public virtual void visit(method_call _method_call) { }
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 void semantic_check_slice_assignment_types(SyntaxTree.expression expr1, SyntaxTree.expression expr2, method_call mc) { var slice = expr1 as slice_expr; var leftValue = convert_strong(slice.v); var leftType = leftValue.type; var rightValue = convert_strong(expr2); var rightType = rightValue.type; var v = slice.v; var from = mc.parameters.expressions[2] as expression; var to = mc.parameters.expressions[3] as expression; expression step = mc.parameters.expressions.Count > 4 ? mc.parameters.expressions[4] : null; var semvar = convert_strong(v); if (semvar is typed_expression) { semvar = convert_typed_expression_to_function_call(semvar as typed_expression); } var IsSlicedType = 0; // проверим, является ли semvar.type динамическим массивом, списком List или строкой if (semvar.type.type_special_kind == SemanticTree.type_special_kind.array_kind) { IsSlicedType = 1; } if (IsSlicedType == 0) { var t = ConvertSemanticTypeNodeToNETType(semvar.type); // не работает для array of T // semvar.type должен быть array of T, List<T> или string if (t == null) { IsSlicedType = 0; // можно ничего не присваивать :) } // else if (t.IsArray) // IsSlicedType = 1; else if (t == typeof(System.String)) { IsSlicedType = 2; } else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(System.Collections.Generic.List <>)) { IsSlicedType = 3; } } if (IsSlicedType == 0) { AddError(get_location(v), "BAD_SLICE_OBJECT"); } var semfrom = convert_strong(from); var fromIsIndex = (semfrom is common_constructor_call fromCall) && fromCall.common_type.comprehensive_namespace.namespace_full_name.Equals("PABCSystem") && fromCall.common_type.PrintableName.Equals("SystemIndex"); var b = convertion_data_and_alghoritms.can_convert_type(semfrom, SystemLibrary.SystemLibrary.integer_type); if (!b && !fromIsIndex) { AddError(get_location(from), "INTEGER_VALUE_EXPECTED"); } var semto = convert_strong(to); var toIsIndex = (semto is common_constructor_call toCall) && toCall.common_type.comprehensive_namespace.namespace_full_name.Equals("PABCSystem") && toCall.common_type.PrintableName.Equals("SystemIndex"); b = convertion_data_and_alghoritms.can_convert_type(semto, SystemLibrary.SystemLibrary.integer_type); if (!b && !toIsIndex) { AddError(get_location(to), "INTEGER_VALUE_EXPECTED"); } if (step != null) { var semstep = convert_strong(step); b = convertion_data_and_alghoritms.can_convert_type(semstep, SystemLibrary.SystemLibrary.integer_type); if (!b) { AddError(get_location(step), "INTEGER_VALUE_EXPECTED"); } } if (!AreTheSameType(leftType, rightType)) { AddError(get_location(expr2), "EXPRESSION_OF_TYPE_{0}_CANNOT_BE_ASSIGNED_TO_SLICE_OF_TYPE_{1}", rightType.PrintableName, leftType.PrintableName); } }
public void Emit_No_Parameters(object o) { method_call mc = o as method_call; parse_tree_pkg.emit_method_call_il(mc.name, mc.param_count, this); }
public override void visit(method_call _method_call) { DefaultVisit(_method_call); pre_do_visit(_method_call); visit(method_call.parameters); post_do_visit(_method_call); }
public expression NewFormatString(string_const str) { try { method_call mc = new method_call(); mc.dereferencing_value = new dot_node(new ident("string", str.source_context), new ident("Format", str.source_context), str.source_context); mc.parameters = new expression_list(); if (!str.Value.Contains("{")) { return(str); } string val = str.Value.Replace("{{", "![&").Replace("}}}", "}&]!").Replace("}}", "&]!"); string[] arr = Regex.Split(val, @"\{[^\}]+\}"); Match match = Regex.Match(val, @"\{[^\}]+\}"); List <string> vars = new List <string>(); //Dictionary<string, int> var_offsets = new Dictionary<string, int>(); List <int> var_offsets = new List <int>(); Dictionary <int, string> var_formats = new Dictionary <int, string>(); int ind = 0; while (match.Success) { string s = match.Value.Replace("{", "").Replace("}", ""); int colon_pos = s.LastIndexOf(':'); int comma_pos = s.LastIndexOf(','); int bracket_pos = s.LastIndexOf(')'); int sqbracked_pos = s.LastIndexOf(']'); if (comma_pos != -1 && comma_pos > bracket_pos && comma_pos > sqbracked_pos) { colon_pos = comma_pos; } if (colon_pos != -1 && s.IndexOf('?') == -1 && s.Substring(colon_pos).IndexOf(']') == -1) { var_formats.Add(ind, s.Substring(colon_pos)); s = s.Substring(0, colon_pos); } if (s.IndexOf("&]!") != -1 || s.IndexOf("![&") != -1) { parsertools.errors.Add(new bad_format_string(parsertools.CurrentFileName, str.source_context, str)); return(str); } vars.Add(s); var_offsets.Add(match.Index); match = match.NextMatch(); ind++; } if (vars.Count == 0 && val.IndexOf("![&") == -1 && val.IndexOf("{") != -1) { parsertools.errors.Add(new bad_format_string(parsertools.CurrentFileName, str.source_context, str)); return(str); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.Length; i++) { if (arr[i].IndexOf("{") != -1 || arr[i].IndexOf("}") != -1) { parsertools.errors.Add(new bad_format_string(parsertools.CurrentFileName, str.source_context, str)); return(str); } sb.Append(arr[i].Replace("![&", "{{").Replace("&]!", "}}")); if (i < arr.Length - 1) { sb.Append("{" + i); string fmt; if (var_formats.TryGetValue(i, out fmt)) { sb.Append(fmt); } sb.Append("}"); } } string str2 = sb.ToString(); if (str2.Trim().EndsWith("{")) { parsertools.errors.Add(new bad_format_string(parsertools.CurrentFileName, str.source_context, str)); return(str); } mc.parameters.Add(new string_const(str2, str.source_context), str.source_context); for (int i = 0; i < vars.Count; i++) { string s = vars[i]; var expr = ParseExpression(new string('\n', str.source_context.begin_position.line_num - 1) + new string(' ', str.source_context.begin_position.column_num + var_offsets[i] + 2) + s, str.source_context.begin_position.line_num, str.source_context.begin_position.column_num + var_offsets[i] + 2); if (expr == null) { var err = parsertools.errors[0] as LocatedError; err.SourceContext.begin_position.line_num = str.source_context.begin_position.line_num; err.SourceContext.begin_position.column_num = str.source_context.begin_position.column_num + var_offsets[i] + vars[i].Length + 3; return(str); } expr.source_context.begin_position.line_num = str.source_context.begin_position.line_num; expr.source_context.end_position.line_num = str.source_context.end_position.line_num; mc.parameters.Add(expr); } mc.source_context = str.source_context; return(mc); } catch (Exception ex) { parsertools.errors.Add(new bad_format_string(parsertools.CurrentFileName, str.source_context, str)); } return(str); }