public void FunctionDef(FunctionDef e) { CurrentFuncDef = new Hashtable(); DoVars = new Hashtable(); CurrentFuncName = e.Name; //Functions.Add(e.Name, e); e.Body.Visit(this); for (int i = 0; i < e.Params.Count; i++) { if (CurrentFuncDef[e.Params[i]] == null) { e.Params[i] = typeof(void); } else { e.Params[i] = CurrentFuncDef[e.Params[i]]; //Now Params have Types } } CurrentFuncDef = null; CurrentFuncName = null; DoVars = null; e.ExpType = e.Body.ExpType; Functions.Add(e.Name, e); }
public dynamic Invoke(Scope scope) { //Params.ForEach(p => { context.ArgSet[((Identifier) p).Id] = null; }); var function = new FunctionDef { Body = Body, Params = Params }; scope.SetFunction(((Identifier)Id).Id, function); return function; }
///<summary> /// Проверка доступных операций сравнения для двух детейловых свойств. ///</summary> ///<param name="func">Функция сравнения, для проверки.</param> ///<returns>Результат проверки.</returns> public bool CheckConditionFunctionForExistDetails(FunctionDef func) { string operation = func.StringedView; return(operation == funcEQ || operation == funcNEQ || operation == funcG || operation == funcL || operation == funcGEQ || operation == funcLEQ); }
internal CodeVariableDeclarationStatement GenerateLambdaVariable(FunctionDef f) { var type = this.gen.TypeRef("Func", Enumerable.Range(0, f.parameters.Count + 1) .Select(x => "object") .ToArray()); return new CodeVariableDeclarationStatement(type, f.name.Name); }
private void EnterFunctionDef(FunctionDef context, int line, LatteParser.BlockContext block, LatteParser.ArgContext arg) { _environment.DetachVarEnv(); _environment.CurrentFunctionName = context.Id; if (!context.Type.Equals(new LatteParser.TVoidContext()) && !new ReturnsCheckVisitor().Visit(block)) { _errorState.AddErrorMessage(new ErrorMessage( line, ErrorMessages.FunctionBranchWithoutRet(_environment.CurrentFunctionName))); } if (arg == null) { return; } var args = arg.type().Zip(arg.ID(), (a, b) => (a, b)); foreach (var(type, id) in args) { var ident = id.GetText(); if (_environment.NameToVarDef.ContainsKey(ident)) { _errorState.AddErrorMessage(new ErrorMessage( line, ErrorMessages.VarAlreadyDefined(ident))); } _environment.NameToVarDef[ident] = new VarDef(type, ident); } }
public void VisitFuncdef(FunctionDef f) { if (VisitDecorators(f)) { return; } MethodGenerator mgen; MemberAttributes attrs = 0; if (this.gen.CurrentMember != null) { GenerateLocalFunction(f); return; } if (this.classDef != null) { // Inside a class; is this a instance method? bool hasSelf = f.parameters.Any(p => p.Id != null && p.Id.Name == "self"); if (hasSelf) { // Presence of 'self' says it _is_ an instance method. var adjustedPs = f.parameters.Where(p => p.Id == null || p.Id.Name != "self").ToList(); var fnName = f.name.Name; if (fnName == "__init__") { // Magic function __init__ is a ctor. mgen = new ConstructorGenerator(this.classDef, f, adjustedPs, types, gen); } else { if (f.name.Name == "__str__") { attrs = MemberAttributes.Override; fnName = "ToString"; } mgen = new MethodGenerator(this.classDef, f, fnName, adjustedPs, false, async, types, gen); } } else { mgen = new MethodGenerator(this.classDef, f, f.name.Name, f.parameters, true, async, types, gen); } } else { mgen = new MethodGenerator(this.classDef, f, f.name.Name, f.parameters, true, async, types, gen); } ICodeFunction fn = mgen.Generate(); //$TODO: move into generate if (fn is CodeMember m) { m.Attributes |= attrs; if (customAttrs != null) { m.CustomAttributes.AddRange(this.customAttrs); customAttrs = null; } } }
public Node FunDef() { var n1 = new FunctionDef() { AnchorToken = Expect(TokenCategory.IDENTIFIER) }; Expect(TokenCategory.PARENTHESIS_OPEN); if (CurrentToken == TokenCategory.IDENTIFIER) { n1.Add(IDList(new ParamList())); } else { n1.Add(new ParamList()); } Expect(TokenCategory.PARENTHESIS_CLOSE); Expect(TokenCategory.BRACE_OPEN); while (CurrentToken == TokenCategory.VAR) { n1.Add(VarDef()); } if (firstOfStatement.Contains(CurrentToken)) { var listStmt = new ListStatements(); while (firstOfStatement.Contains(CurrentToken)) { listStmt.Add(Statement()); } n1.Add(listStmt); } Expect(TokenCategory.BRACE_CLOSE); return(n1); }
private void GenerateLocalFunction(FunctionDef f) { var mgen = new FunctionGenerator(f, f.name.Name, f.parameters, true, async, types, gen); var localFn = mgen.Generate(); gen.CurrentStatements !.Add((CodeStatement)localFn); }
private FunctionDef _GenerateDelete(Table Table) { var t_Gen = new FunctionDef("Delete", new UDT("void"), new List <IFileComponentGenerator> { }); return(t_Gen); }
private FunctionDef _GenerateRead(Table Table) { var t_Gen = new FunctionDef("Read", new UDTTemplate("std::vector", Table.Name + "DTO"), new List <IFileComponentGenerator> { }); return(t_Gen); }
public ConstructorGenerator( FunctionDef f, List <Syntax.Parameter> args, TypeReferenceTranslator types, CodeGenerator gen) : base(f, "", args, false, false, types, gen) { }
void VerifyFDefNodes(FunctionDef fdef, string[] nodes) { ASSERT_EQ(nodes.Length, fdef.NodeDef.Count); foreach (var node in fdef.NodeDef) { ASSERT_TRUE(nodes.Contains(node.Name), $"Got unexpected node: {node.Name} in fdef: {fdef}"); } }
public LambdaBodyGenerator(FunctionDef f, List <Parameter> args, bool isStatic, bool isAsync, TypeReferenceTranslator types, CodeGenerator gen) : base(f, null, args, isStatic, isAsync, types, gen) { }
internal CodeVariableDeclarationStatement GenerateLambdaVariable(FunctionDef f) { var type = this.gen.TypeRef("Func", Enumerable.Range(0, f.parameters.Count + 1) .Select(x => "object") .ToArray()); return(new CodeVariableDeclarationStatement(type, f.name.Name)); }
public MethodGenerator(FunctionDef f, string fnName, List <Parameter> args, bool isStatic, CodeGenerator gen) { this.f = f; this.fnName = fnName; this.args = args; this.isStatic = isStatic; this.gen = gen; }
public MethodGenerator(FunctionDef f, string fnName, List<Parameter> args, bool isStatic, CodeGenerator gen) { this.f = f; this.fnName = fnName; this.args = args; this.isStatic = isStatic; this.gen = gen; }
public void VisitFuncdef(FunctionDef f) { MethodGenerator mgen; MemberAttributes attrs = 0; if (this.gen.CurrentMember != null) { var lgen = new LambdaBodyGenerator(f, f.parameters, true, gen); var def = lgen.GenerateLambdaVariable(f); var meth = lgen.Generate(); def.InitExpression = gen.Lambda( meth.Parameters.Select(p => new CodeVariableReferenceExpression(p.ParameterName)).ToArray(), meth.Statements); gen.CurrentMemberStatements.Add(def); return; } if (this.currentClass != null) { // Inside a class; is this a instance method? bool hasSelf = f.parameters.Any(p => p.Id != null && p.Id.Name == "self"); if (hasSelf) { // Presence of 'self' says it _is_ an instance method. var adjustedPs = f.parameters.Where(p => p.Id == null || p.Id.Name != "self").ToList(); var fnName = f.name.Name; if (fnName == "__init__") { // Magic function __init__ is a ctor. mgen = new ConstructorGenerator(f, adjustedPs, gen); } else { if (f.name.Name == "__str__") { attrs = MemberAttributes.Override; fnName = "ToString"; } mgen = new MethodGenerator(f, fnName, adjustedPs, false, gen); } } else { mgen = new MethodGenerator(f, f.name.Name, f.parameters, true, gen); } } else { mgen = new MethodGenerator(f, f.name.Name, f.parameters, true, gen); } CodeMemberMethod m = mgen.Generate(); m.Attributes |= attrs; if (customAttrs != null) { m.CustomAttributes.AddRange(this.customAttrs); customAttrs = null; } }
public ConstructorGenerator( ClassDef classDef, FunctionDef f, List <Parameter> args, TypeReferenceTranslator types, CodeGenerator gen) : base(classDef, f, "", args, false, false, types, gen) { }
//----------------------------------------------------------- public string Visit(FunctionDef node) { var sb = new StringBuilder(); foreach (var j in node) { sb.Append(Visit((dynamic)j)); } return(sb.ToString()); }
public FunctionGeneratorState(FunctionDef function) { CurrentFunction = function.Id; function.Args.ForEach(arg => VarToLabelToRegister.Add( arg.Id, new Dictionary <string, RegisterLabelContext> { { EntryLabel, new RegisterLabelContext(NewRegister, EntryLabel, arg.Type) } })); }
public void ValidateFunctionCall(FunctionDef fDef, string functionId, LatteParser.ExprContext[] expr, int line) { if (fDef.Args.Count != (expr?.Length ?? 0)) { _errorState.AddErrorMessage(new ErrorMessage( line, ErrorMessages.WrongArgsCountFuncCall(functionId))); } CheckFunctionCallArgsForEqualCount(fDef, expr, functionId, line); }
public FunctionGenerator( FunctionDef f, string fnName, List <Parameter> args, bool isStatic, bool isAsync, TypeReferenceTranslator types, CodeGenerator gen) : base( null, f, fnName, args, isStatic, isAsync, types, gen) { }
public static bool TryGetFunction(string functionName, out FunctionDef def) { FillCache(); def = new FunctionDef(); if (_functionMap is null || !_functionMap.TryGetValue(functionName, out FunctionDef? found) || found is null) return false; def = found; return true; }
public MethodGenerator(FunctionDef f, string fnName, List <Parameter> args, bool isStatic, CodeGenerator gen) { this.f = f; this.fnName = fnName; this.args = args; this.isStatic = isStatic; this.gen = gen; this.gensym = new SymbolGenerator(); this.xlat = new ExpTranslator(gen, gensym); this.stmtXlat = new StatementTranslator(gen, gensym); }
/// <summary> /// Binds the parameters of a call to the called function. /// </summary> /// <param name="analyzer"></param> /// <param name="call"></param> /// <param name="func"></param> /// <param name="funcTable"></param> /// <param name="parameters"></param> /// <param name="rest"></param> /// <param name="restKw"></param> /// <param name="pTypes"></param> /// <param name="dTypes"></param> /// <param name="hash"></param> /// <param name="kw"></param> /// <param name="star"></param> /// <returns></returns> private static DataType BindParameters( Analyzer analyzer, Node call, FunctionDef func, State funcTable, List <Parameter> parameters, Identifier rest, Identifier restKw, List <DataType> pTypes, List <DataType> dTypes, IDictionary <string, DataType> hash, DataType kw, DataType star) { TupleType fromType = analyzer.TypeFactory.CreateTuple(); int pSize = parameters == null ? 0 : parameters.Count; int aSize = pTypes == null ? 0 : pTypes.Count; int dSize = dTypes == null ? 0 : dTypes.Count; int nPos = pSize - dSize; if (star != null && star is ListType list) { star = list.ToTupleType(); } for (int i = 0, j = 0; i < pSize; i++) { Parameter param = parameters[i]; DataType aType; if (i < aSize) { aType = pTypes[i]; } else if (i - nPos >= 0 && i - nPos < dSize) { aType = dTypes[i - nPos]; } else { if (hash != null && hash.ContainsKey(parameters[i].Id.Name)) { aType = hash[parameters[i].Id.Name]; hash.Remove(parameters[i].Id.Name); } else { if (star != null && star is TupleType tup && j < tup.eltTypes.Count) { aType = tup.get(j); ++j; }
private void CheckFunctionCallArgsForEqualCount(FunctionDef fDef, LatteParser.ExprContext[] fExpr, string id, int line) { var argsWithExpr = fDef.Args.Zip(fExpr, (arg, expr) => (arg, expr)); foreach (var(arg, expr) in argsWithExpr) { if (!Visit(expr).Equals(arg.Type)) { _errorState.AddErrorMessage(new ErrorMessage( line, expr.start.Column, ErrorMessages.WrongArgTypeFuncCall(id, arg.Id, arg.Type.GetText()))); } } }
private bool ClassHasMethod(ClassDef classDef, string methodId, out FunctionDef method) { if (classDef.Methods.ContainsKey(methodId)) { method = classDef.Methods[methodId].Item1; return(true); } if (classDef.ParentId != null) { return(ClassHasMethod(_environment.NameToClassDef[classDef.ParentId], methodId, out method)); } method = null; return(false); }
//----------------------------------------------------------- public string Visit(FunctionDef node) { var sb = new StringBuilder(); var result = ""; funName = node.AnchorToken.Lexeme; result = "\t.method public static void '" + funName + "'() {\n"; sb.Append(result); sb.Append("\t\t.entrypoint\n"); sb.Append(VisitChildren(node)); //sb.Append("\t\tpop\n"); sb.Append("\t\tret\n"); sb.Append("\t}\n"); return(sb.ToString()); }
void VerifyFDefOutputs(FunctionDef fdef, List <IOSpec> outputs) { var signature = fdef.Signature; ASSERT_EQ(outputs.Count, signature.OutputArg.Count); for (int i = 0; i < outputs.Count; ++i) { var arg = signature.OutputArg[i]; var output = outputs[i]; if (output.Value != DataType.DtInvalid) { ASSERT_EQ(arg.Type, output.Value, $""); } ASSERT_EQ(arg.Name, output.Key, $"Got unexpected name for input {i}. fdef: {fdef}"); } }
public DataType VisitFunctionDef(FunctionDef f) { State env = scope.getForwarding(); FunType fun = new FunType(f, env); fun.Table.Parent = this.scope; fun.Table.Path = scope.extendPath(analyzer, f.name.Name); fun.setDefaultTypes(ResolveList(f.parameters .Where(p => p.test != null) .Select(p => p.test))); analyzer.AddUncalled(fun); BindingKind funkind; if (scope.stateType == State.StateType.CLASS) { if ("__init__" == f.name.Name) { funkind = BindingKind.CONSTRUCTOR; } else { funkind = BindingKind.METHOD; } } else { funkind = BindingKind.FUNCTION; } DataType outType = scope.Type; if (outType is ClassType) { fun.Class = ((ClassType)outType); } scope.Bind(analyzer, f.name, fun, funkind); var sOld = this.scope; this.scope = fun.Table; f.body.Accept(this); this.scope = sOld; return(DataType.Cont); }
public static DataType FirstArgumentType(FunctionDef f, FunType func, DataType selfType) { if (f.parameters.Count == 0) { return(null); } if (!func.Definition.IsStaticMethod()) { if (func.Definition.IsClassMethod()) { if (func.Class != null) { return(func.Class); } else if (selfType != null && selfType is InstanceType inst) { return(inst.classType); } } else { // usual method if (selfType != null) { return(selfType); } else { if (func.Class != null) { if (func.Definition.name.Name != "__init__") { throw new NotImplementedException("return func.Class.getInstance(null, this, call));"); } else { return(func.Class.GetInstance()); } } } } } return(null); }
void VerifyFDefEdges(FunctionDef fdef, List <EdgeSpec> e_edges, List <EdgeSpec> c_edges, bool is_exact_edges = true) { // Build a set of edges from fdef var a_edges = new List <EdgeSpec>(); // actual edges // Get edges from inputs to body nodes and between body nodes foreach (var node in fdef.NodeDef) { for (int i = 0; i < node.Input.Count; ++i) { var input = node.Input[i]; a_edges.Add(new EdgeSpec(input, $"{node.Name}:{i}")); } } // Get edges from body nodes to outputs and from inputs to outputs foreach (var arg in fdef.Signature.OutputArg) { var iter = fdef.Ret.FirstOrDefault(x => x.Key == arg.Name); if (iter.Key != null) { a_edges.Add(new EdgeSpec(iter.Value, arg.Name)); } else { a_edges.Add(new EdgeSpec(arg.Name, arg.Name)); } } // Verify edges foreach (var edge in e_edges) { ASSERT_TRUE(a_edges.Contains(edge)); } foreach (var edge in c_edges) { ASSERT_TRUE(a_edges.Contains(edge)); } // If caller specified all edges, check that we have seen all if (is_exact_edges) { ASSERT_EQ(e_edges.Count + c_edges.Count, a_edges.Count, $"Expected edges: {e_edges}, Expected Control edges: {c_edges}, Actual edges: {a_edges}"); } }
public static string FunctionalType(FunctionDef func) { var result = new StringBuilder(Type(func.Type) + "("); var isFirst = true; func.Args.ForEach(arg => { if (!isFirst) { result.Append(", "); } result.Append(Type(arg.Type)); isFirst = false; }); result.Append(")*"); return(result.ToString()); }
public ConstructorGenerator(FunctionDef f, List<Syntax.Parameter> args, CodeGenerator gen) : base(f, "", args, false, gen) { }
public void VisitFuncdef(FunctionDef f) { w.Write("def"); w.Write(" "); w.WriteName(f.name.Name); w.Write("("); var sep = ""; foreach (var p in f.parameters) { w.Write(sep); sep = ","; w.Write(p.ToString()); } w.WriteLine("):"); ++w.IndentLevel; f.body.Accept(this); --w.IndentLevel; }
public void VisitFuncdef(FunctionDef f) { MethodGenerator mgen; MemberAttributes attrs = 0; if (this.gen.CurrentMethod != null) { var lgen = new LambdaBodyGenerator(f, f.parameters, true, gen); var def = lgen.GenerateLambdaVariable(f); var meth = lgen.Generate(); def.InitExpression = gen.Lambda( meth.Parameters.Select(p => new CodeVariableReferenceExpression(p.ParameterName)).ToArray(), meth.Statements); gen.CurrentMethod.Statements.Add(def); return; } if (this.currentClass != null) { // Inside a class; is this a instance method? bool hasSelf = f.parameters.Where(p => p.Id != null && p.Id.Name == "self").Count() > 0; if (hasSelf) { // Presence of 'self' says it _is_ an instance method. var adjustedPs = f.parameters.Where(p => p.Id == null || p.Id.Name != "self").ToList(); var fnName = f.name.Name; if (fnName == "__init__") { // Magic function __init__ is a ctor. mgen = new ConstructorGenerator(f, adjustedPs, gen); } else { if (f.name.Name == "__str__") { attrs = MemberAttributes.Override; fnName = "ToString"; } mgen = new MethodGenerator(f, fnName, adjustedPs, false, gen); } } else { mgen = new MethodGenerator(f, f.name.Name, f.parameters, true, gen); } } else { mgen = new MethodGenerator(f, f.name.Name, f.parameters, true, gen); } CodeMemberMethod m = mgen.Generate(); m.Attributes |= attrs; if (customAttrs != null) { m.CustomAttributes.AddRange(this.customAttrs); customAttrs = null; } }
public LambdaBodyGenerator(FunctionDef f, List<Parameter> args, bool isStatic, CodeGenerator gen) : base(f, null, args, isStatic, gen) { }
internal static stmt Convert(Statement stmt) { stmt ast; if (stmt is FunctionDefinition) ast = new FunctionDef((FunctionDefinition)stmt); else if (stmt is ReturnStatement) ast = new Return((ReturnStatement)stmt); else if (stmt is AssignmentStatement) ast = new Assign((AssignmentStatement)stmt); else if (stmt is AugmentedAssignStatement) ast = new AugAssign((AugmentedAssignStatement)stmt); else if (stmt is DelStatement) ast = new Delete((DelStatement)stmt); else if (stmt is PrintStatement) ast = new Print((PrintStatement)stmt); else if (stmt is ExpressionStatement) ast = new Expr((ExpressionStatement)stmt); else if (stmt is ForStatement) ast = new For((ForStatement)stmt); else if (stmt is WhileStatement) ast = new While((WhileStatement)stmt); else if (stmt is IfStatement) ast = new If((IfStatement)stmt); else if (stmt is WithStatement) ast = new With((WithStatement)stmt); else if (stmt is RaiseStatement) ast = new Raise((RaiseStatement)stmt); else if (stmt is TryStatement) ast = Convert((TryStatement)stmt); else if (stmt is AssertStatement) ast = new Assert((AssertStatement)stmt); else if (stmt is ImportStatement) ast = new Import((ImportStatement)stmt); else if (stmt is FromImportStatement) ast = new ImportFrom((FromImportStatement)stmt); else if (stmt is ExecStatement) ast = new Exec((ExecStatement)stmt); else if (stmt is GlobalStatement) ast = new Global((GlobalStatement)stmt); else if (stmt is ClassDefinition) ast = new ClassDef((ClassDefinition)stmt); else if (stmt is BreakStatement) ast = new Break(); else if (stmt is ContinueStatement) ast = new Continue(); else if (stmt is EmptyStatement) ast = new Pass(); else throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType()); ast.GetSourceLocation(stmt); return ast; }