/// <summary> /// Type check and gather top-level information about a method. This includes /// checking the return type, formal parameter types, and creating a scope for the /// method. /// </summary> /// <param name="n"></param> public override void VisitDeclMethod(ASTDeclarationMethod n) { var methodScope = _scopeMgr.PushScope(string.Format("method {0}", n.Name)); var func = new TypeFunction(n.Name); var formalDescriptors = CollectFormals(n.Formals, func); var returnType = CheckSubTree(n.ReturnType); func.ReturnType = returnType; func.Scope = methodScope; var mods = GatherModifiers(n); _scopeMgr.PopScope(); var methodDesc = _scopeMgr.AddMethod(n.Name, func, _currentClass, mods); n.Descriptor = methodDesc; n.Type = func; foreach (var formal in formalDescriptors) { methodDesc.Formals.Add(formal); } }
public LocalDescriptor AddLocal(string name, CFlatType type, TypeFunction containingMethod) { var descriptior = new LocalDescriptor(type, name); CurrentScope.Descriptors.Add(name, descriptior); containingMethod.AddLocal(name, type); return(descriptior); }
protected InternalMethod(string name, InternalType returnType, Dictionary <string, InternalType> formals) { Name = name; FuncInfo = new TypeFunction(name) { ReturnType = returnType, Formals = formals }; }
public SystemMethod(string name, CFlatType returnType, Dictionary <string, CFlatType> formals) { Name = name; FuncInfo = new TypeFunction(name) { ReturnType = returnType, Formals = formals }; }
public void AddCtor(string typeName, ASTDeclarationCtor n) { TypeBuilderInfo info = TypeBuilderMap[typeName]; TypeFunction function = n.Type as TypeFunction; ConstructorBuilder builderObj = info.Builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ArgumentTypes(function)); info.ConstructorBuilder = new ConstructorBuilderInfo(builderObj, BuildFormalMap(n.Descriptor.Formals)); }
private void AddCtorIfNone(Scope classScope, string name) { var ctor = _currentClass.Descriptor.Methods.Where(p => p.Name.Equals(_currentClass.ClassName, StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); if (ctor == null) { var func = new TypeFunction(name) { ReturnType = new TypeVoid(), IsConstructor = true, Scope = classScope }; _scopeMgr.AddMethod(name, func, _currentClass); } }
protected override OpTypeFunction VisitTypeFunction(TypeFunction node) { var visitTypeFunction = base.VisitTypeFunction(node); Register(visitTypeFunction, _typeInstructions); visitTypeFunction.ParameterTypes = new List <IdRef>(); foreach (var argument in node.Arguments) { visitTypeFunction.ParameterTypes.Add(Visit(argument.Type)); } visitTypeFunction.ReturnType = Visit(node.ReturnType); return(visitTypeFunction); }
/// <summary> /// Restores the method's scope, and adds a new scope for local variables. /// Walks the body of the function and pops the two scopes. /// /// Both VisitDeclMethod and VisitDeclConstructor do the same thing, so moved the code out into 1 method. /// </summary> /// <param name="scopeName"></param> /// <param name="body"></param> /// <param name="f"></param> private void VisitMethodBody(string scopeName, ASTStatementList body, TypeFunction f) { _currentMethod = f; //restore the scope of the formals _scopeMgr.RestoreScope(_currentMethod.Scope); //add a new scope for any locals Scope localScope = _scopeMgr.PushScope(scopeName); CheckSubTree(body); //pop the body scope and the formal scope _scopeMgr.PopScope(); _scopeMgr.PopScope(); }
public void AddMethod(string typeName, ASTDeclarationMethod n) { TypeBuilderInfo info = TypeBuilderMap[typeName]; //we need to know the CIL type for the return type and arguments Type returnType = LookupCilType(n.ReturnType); TypeFunction function = n.Type as TypeFunction; MethodBuilder methodBuilder = info.Builder.DefineMethod(n.Name, MethodAccessibility(n), returnType, ArgumentTypes(function)); //store this MethodBuilder, keyed off its name info.MethodMap.Add(n.Name, new MethodBuilderInfo(methodBuilder, BuildFormalMap(n.Descriptor.Formals))); }
private double FunctionDerivative(double f, TypeFunction function) { switch (function) { case TypeFunction.Sigmoid: return(f * (1 - f)); case TypeFunction.Tanh: return(1 - Math.Pow(f, 2)); case TypeFunction.ReLu: return(Math.Max(0, f)); default: return(0); } }
private List <FormalDescriptor> CollectFormals(ASTFormalList formals, TypeFunction containingFunction) { var descList = new List <FormalDescriptor>(); var formalsType = CheckSubTree(formals); if (!formals.IsEmpty) { var list = formals; while (!list.IsEmpty) { containingFunction.AddFormal(list.Formal.Name, list.Formal.CFlatType); descList.Add(new FormalDescriptor(list.Formal.CFlatType, list.Formal.Name, list.Formal.Modifier)); list = list.Tail; } } return(descList); }
/// <summary> /// Essentially the same as a method declaration, except there is no /// return type to validate. /// </summary> /// <param name="n"></param> public override void VisitDeclConstructor(ASTDeclarationCtor n) { var ctorScope = _scopeMgr.PushScope(string.Format("ctor {0}", n.Name)); var func = new TypeFunction(n.Name) { ReturnType = new TypeVoid(), IsConstructor = true }; var formalDescriptors = CollectFormals(n.Formals, func); func.Scope = ctorScope; _scopeMgr.PopScope(); var methodDesc = _scopeMgr.AddMethod(n.Name, func, _currentClass); n.Descriptor = methodDesc; n.Type = func; foreach (var formal in formalDescriptors) { methodDesc.Formals.Add(formal); } }
public BuiltInFunctions() { // Text Functions["len"] = new Len(); Functions["lower"] = new Lower(); Functions["upper"] = new Upper(); Functions["left"] = new Left(); Functions["right"] = new Right(); Functions["mid"] = new Mid(); Functions["replace"] = new Replace(); Functions["rept"] = new Rept(); Functions["substitute"] = new Substitute(); Functions["concatenate"] = new Concatenate(); Functions["concat"] = new Concat(); Functions["textjoin"] = new Textjoin(); Functions["char"] = new CharFunction(); Functions["exact"] = new Exact(); Functions["find"] = new Find(); Functions["fixed"] = new Fixed(); Functions["proper"] = new Proper(); Functions["search"] = new Search(); Functions["text"] = new Text.Text(); Functions["t"] = new T(); Functions["hyperlink"] = new Hyperlink(); Functions["value"] = new Value(CultureInfo.CurrentCulture); Functions["trim"] = new Trim(); Functions["clean"] = new Clean(); Functions["unicode"] = new Unicode(); Functions["unichar"] = new Unichar(); Functions["numbervalue"] = new NumberValue(); Functions["dollar"] = new Dollar(); // Numbers Functions["int"] = new CInt(); // Math Functions["aggregate"] = new Aggregate(); Functions["abs"] = new Abs(); Functions["asin"] = new Asin(); Functions["asinh"] = new Asinh(); Functions["acot"] = new Acot(); Functions["acoth"] = new Acoth(); Functions["cos"] = new Cos(); Functions["cot"] = new Cot(); Functions["coth"] = new Coth(); Functions["cosh"] = new Cosh(); Functions["csc"] = new Csc(); Functions["csch"] = new Csch(); Functions["power"] = new Power(); Functions["gcd"] = new Gcd(); Functions["lcm"] = new Lcm(); Functions["sec"] = new Sec(); Functions["sech"] = new SecH(); Functions["sign"] = new Sign(); Functions["sqrt"] = new Sqrt(); Functions["sqrtpi"] = new SqrtPi(); Functions["pi"] = new Pi(); Functions["product"] = new Product(); Functions["ceiling"] = new Ceiling(); Functions["ceiling.precise"] = new CeilingPrecise(); Functions["ceiling.math"] = new CeilingMath(); Functions["iso.ceiling"] = new IsoCeiling(); Functions["combin"] = new Combin(); Functions["combina"] = new Combina(); Functions["permut"] = new Permut(); Functions["permutationa"] = new Permutationa(); Functions["count"] = new Count(); Functions["counta"] = new CountA(); Functions["countblank"] = new CountBlank(); Functions["countif"] = new CountIf(); Functions["countifs"] = new CountIfs(); Functions["fact"] = new Fact(); Functions["factdouble"] = new FactDouble(); Functions["floor"] = new Floor(); Functions["floor.precise"] = new FloorPrecise(); Functions["floor.math"] = new FloorMath(); Functions["radians"] = new Radians(); Functions["roman"] = new Roman(); Functions["sin"] = new Sin(); Functions["sinh"] = new Sinh(); Functions["sum"] = new Sum(); Functions["sumif"] = new SumIf(); Functions["sumifs"] = new SumIfs(); Functions["sumproduct"] = new SumProduct(); Functions["sumsq"] = new Sumsq(); Functions["sumxmy2"] = new Sumxmy2(); Functions["sumx2my2"] = new SumX2mY2(); Functions["sumx2py2"] = new SumX2pY2(); Functions["seriessum"] = new Seriessum(); Functions["stdev"] = new Stdev(); Functions["stdeva"] = new Stdeva(); Functions["stdevp"] = new StdevP(); Functions["stdevpa"] = new Stdevpa(); Functions["stdev.s"] = new StdevDotS(); Functions["stdev.p"] = new StdevDotP(); Functions["subtotal"] = new Subtotal(); Functions["exp"] = new Exp(); Functions["log"] = new Log(); Functions["log10"] = new Log10(); Functions["ln"] = new Ln(); Functions["max"] = new Max(); Functions["maxa"] = new Maxa(); Functions["median"] = new Median(); Functions["min"] = new Min(); Functions["mina"] = new Mina(); Functions["mod"] = new Mod(); Functions["mode"] = new Mode(); Functions["mode.sngl"] = new ModeSngl(); Functions["mround"] = new Mround(); Functions["multinomial"] = new Multinomial(); Functions["average"] = new Average(); Functions["averagea"] = new AverageA(); Functions["averageif"] = new AverageIf(); Functions["averageifs"] = new AverageIfs(); Functions["round"] = new Round(); Functions["rounddown"] = new Rounddown(); Functions["roundup"] = new Roundup(); Functions["rand"] = new Rand(); Functions["randbetween"] = new RandBetween(); Functions["rank"] = new Rank(); Functions["rank.eq"] = new RankEq(); Functions["rank.avg"] = new RankAvg(); Functions["percentile"] = new Percentile(); Functions["percentile.inc"] = new PercentileInc(); Functions["percentile.exc"] = new PercentileExc(); Functions["quartile"] = new Quartile(); Functions["quartile.inc"] = new QuartileInc(); Functions["quartile.exc"] = new QuartileExc(); Functions["percentrank"] = new Percentrank(); Functions["percentrank.inc"] = new PercentrankInc(); Functions["percentrank.exc"] = new PercentrankExc(); Functions["quotient"] = new Quotient(); Functions["trunc"] = new Trunc(); Functions["tan"] = new Tan(); Functions["tanh"] = new Tanh(); Functions["atan"] = new Atan(); Functions["atan2"] = new Atan2(); Functions["atanh"] = new Atanh(); Functions["acos"] = new Acos(); Functions["acosh"] = new Acosh(); Functions["covar"] = new Covar(); Functions["covariance.p"] = new CovarianceP(); Functions["covariance.s"] = new CovarianceS(); Functions["var"] = new Var(); Functions["vara"] = new Vara(); Functions["var.s"] = new VarDotS(); Functions["varp"] = new VarP(); Functions["varpa"] = new Varpa(); Functions["var.p"] = new VarDotP(); Functions["large"] = new Large(); Functions["small"] = new Small(); Functions["degrees"] = new Degrees(); Functions["odd"] = new Odd(); Functions["even"] = new Even(); // Information Functions["isblank"] = new IsBlank(); Functions["isnumber"] = new IsNumber(); Functions["istext"] = new IsText(); Functions["isnontext"] = new IsNonText(); Functions["iserror"] = new IsError(); Functions["iserr"] = new IsErr(); Functions["error.type"] = new ErrorType(); Functions["iseven"] = new IsEven(); Functions["isodd"] = new IsOdd(); Functions["islogical"] = new IsLogical(); Functions["isna"] = new IsNa(); Functions["na"] = new Na(); Functions["n"] = new N(); Functions["type"] = new TypeFunction(); // Logical Functions["if"] = new If(); Functions["ifs"] = new Ifs(); Functions["maxifs"] = new MaxIfs(); Functions["minifs"] = new MinIfs(); Functions["iferror"] = new IfError(); Functions["ifna"] = new IfNa(); Functions["not"] = new Not(); Functions["and"] = new And(); Functions["or"] = new Or(); Functions["true"] = new True(); Functions["false"] = new False(); Functions["switch"] = new Switch(); Functions["xor"] = new Xor(); // Reference and lookup Functions["address"] = new Address(); Functions["hlookup"] = new HLookup(); Functions["vlookup"] = new VLookup(); Functions["lookup"] = new Lookup(); Functions["match"] = new Match(); Functions["row"] = new Row(); Functions["rows"] = new Rows(); Functions["column"] = new Column(); Functions["columns"] = new Columns(); Functions["choose"] = new Choose(); Functions["index"] = new RefAndLookup.Index(); Functions["indirect"] = new Indirect(); Functions["offset"] = new Offset(); // Date Functions["date"] = new Date(); Functions["datedif"] = new DateDif(); Functions["today"] = new Today(); Functions["now"] = new Now(); Functions["day"] = new Day(); Functions["month"] = new Month(); Functions["year"] = new Year(); Functions["time"] = new Time(); Functions["hour"] = new Hour(); Functions["minute"] = new Minute(); Functions["second"] = new Second(); Functions["weeknum"] = new Weeknum(); Functions["weekday"] = new Weekday(); Functions["days"] = new Days(); Functions["days360"] = new Days360(); Functions["yearfrac"] = new Yearfrac(); Functions["edate"] = new Edate(); Functions["eomonth"] = new Eomonth(); Functions["isoweeknum"] = new IsoWeekNum(); Functions["workday"] = new Workday(); Functions["workday.intl"] = new WorkdayIntl(); Functions["networkdays"] = new Networkdays(); Functions["networkdays.intl"] = new NetworkdaysIntl(); Functions["datevalue"] = new DateValue(); Functions["timevalue"] = new TimeValue(); // Database Functions["dget"] = new Dget(); Functions["dcount"] = new Dcount(); Functions["dcounta"] = new DcountA(); Functions["dmax"] = new Dmax(); Functions["dmin"] = new Dmin(); Functions["dsum"] = new Dsum(); Functions["daverage"] = new Daverage(); Functions["dvar"] = new Dvar(); Functions["dvarp"] = new Dvarp(); //Finance Functions["cumipmt"] = new Cumipmt(); Functions["cumprinc"] = new Cumprinc(); Functions["dollarde"] = new DollarDe(); Functions["dollarfr"] = new DollarFr(); Functions["ddb"] = new Ddb(); Functions["effect"] = new Effect(); Functions["fvschedule"] = new FvSchedule(); Functions["pduration"] = new Pduration(); Functions["rri"] = new Rri(); Functions["pmt"] = new Pmt(); Functions["ppmt"] = new Ppmt(); Functions["ipmt"] = new Ipmt(); Functions["ispmt"] = new IsPmt(); Functions["pv"] = new Pv(); Functions["fv"] = new Fv(); Functions["npv"] = new Npv(); Functions["rate"] = new Rate(); Functions["nper"] = new Nper(); Functions["nominal"] = new Nominal(); Functions["irr"] = new Irr(); Functions["mirr"] = new Mirr(); Functions["xirr"] = new Xirr(); Functions["sln"] = new Sln(); Functions["syd"] = new Syd(); Functions["xnpv"] = new Xnpv(); Functions["coupdays"] = new Coupdays(); Functions["coupdaysnc"] = new Coupdaysnc(); Functions["coupdaybs"] = new Coupdaybs(); Functions["coupnum"] = new Coupnum(); Functions["coupncd"] = new Coupncd(); Functions["couppcd"] = new Couppcd(); Functions["price"] = new Price(); Functions["yield"] = new Yield(); Functions["yieldmat"] = new Yieldmat(); Functions["duration"] = new Duration(); Functions["disc"] = new Disc(); //Engineering Functions["bitand"] = new BitAnd(); Functions["bitor"] = new BitOr(); Functions["bitxor"] = new BitXor(); Functions["bitlshift"] = new BitLshift(); Functions["bitrshift"] = new BitRshift(); Functions["convert"] = new ConvertFunction(); Functions["bin2dec"] = new Bin2Dec(); Functions["bin2hex"] = new Bin2Hex(); Functions["bin2oct"] = new Bin2Oct(); Functions["dec2bin"] = new Dec2Bin(); Functions["dec2hex"] = new Dec2Hex(); Functions["dec2oct"] = new Dec2Oct(); Functions["hex2bin"] = new Hex2Bin(); Functions["hex2dec"] = new Hex2Dec(); Functions["hex2oct"] = new Hex2Oct(); Functions["oct2bin"] = new Oct2Bin(); Functions["oct2dec"] = new Oct2Dec(); Functions["oct2hex"] = new Oct2Hex(); Functions["delta"] = new Delta(); Functions["erf"] = new Erf(); Functions["erf.precise"] = new ErfPrecise(); Functions["erfc"] = new Erfc(); Functions["erfc.precise"] = new ErfcPrecise(); Functions["besseli"] = new BesselI(); Functions["besselj"] = new BesselJ(); Functions["besselk"] = new BesselK(); Functions["bessely"] = new BesselY(); }
private static void ForeachTypeDo( Assembly assembly, TypeFunction func ) { foreach( Type type in assembly.GetTypes() ) { func( type ); } }
private static void ForeachTypeDo( TypeFunction func ) { foreach( Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() ) { ForeachTypeDo( assembly, func ); } }
public TreeNode_Method(string name, object obj, TypeFunction type, bool export = false) : base(name, obj) { Type = type; Export = export; }
IEnumerator WaittoMove(float seconds) { if (GameObject.Find("Main Camera").GetComponent <CameraController> () != null) { GameController.Instance.cameraController.PlayGameCamera(); GameController.Instance.cameraController.isRunning = true; } int forCount = 0; int auxForCountBack = 0; for (int i = 0; i < inputList.Count; i++) { TypeFunction aux = inputList [i]; playerAnimation.PlayerAnimationWalk(aux.type); // print (aux.type.ToString ()); switch (aux.type) { case TypeFunction.Type.moveUp: aux.OnWorkMe(); playerMove.MoveUp(); yield return(new WaitWhile(() => playerMove.isMove != false)); playerAnimation.PlayerAnimationIdle(); yield return(new WaitForSeconds(seconds)); break; case TypeFunction.Type.moveDown: aux.OnWorkMe(); playerMove.MoveDown(); yield return(new WaitWhile(() => playerMove.isMove != false)); playerAnimation.PlayerAnimationIdle(); yield return(new WaitForSeconds(seconds)); break; case TypeFunction.Type.moveLeft: aux.OnWorkMe(); playerMove.MoveLeft(); yield return(new WaitWhile(() => playerMove.isMove != false)); playerAnimation.PlayerAnimationIdle(); yield return(new WaitForSeconds(seconds)); break; case TypeFunction.Type.moveRight: aux.OnWorkMe(); playerMove.MoveRight(); yield return(new WaitWhile(() => playerMove.isMove != false)); playerAnimation.PlayerAnimationIdle(); yield return(new WaitForSeconds(seconds)); break; case TypeFunction.Type.push: aux.OnWorkMe(); playerMove.push(); yield return(new WaitForSeconds(1f)); playerAnimation.PlayerAnimationIdle(); break; case TypeFunction.Type.funcFor: aux.OnWorkMe(); forCount = aux.contFor; auxForCountBack = i; yield return(new WaitForSeconds(0.2f)); break; case TypeFunction.Type.funcForEnd: aux.OnWorkMe(); if (forCount > 1) { i = auxForCountBack; forCount--; } yield return(new WaitForSeconds(0.2f)); break; } if (!GameController.Instance.playerController.playerMove.canMove) { playerAnimation.PlayerAnimationIdle(); playerAnimation.PlayerAnimationWrong(); yield return(new WaitForSeconds(1f)); GameController.Instance.playerController.playerMove.canMove = true; playerAnimation.PlayerAnimationIdle(); } aux.OffWorkMe(); } GameController.Instance.PlayerWin(); }
public FormalBuilder(TypeFunction f) { _function = f; }
static void Main(string[] args) { IType Int = TypeSingleton.Integer, Bool = TypeSingleton.Boolean, Str = TypeSingleton.String, Func = new TypeFunction(new TypeTuple(), TypeSingleton.Void), Tuple = new TypeTuple(), Union = new TypeUnion(), Void = TypeSingleton.Void, Any = TypeSingleton.Any; Tokenizer Indentation = Tokenizers.Indentation, MathOperator = Tokenizers.Predicate("&|+-".Contains), MathOperator2 = Tokenizers.Predicate("*/%".Contains), ComparisonOperator = Tokenizers.Predicate("=<>".Contains), PrefixOperator = Tokenizers.Match("!"), String = Tokenizers.Quote('"', '"'), Integer = Tokenizers.Predicate(char.IsDigit), Symbol = Tokenizers.Predicate(char.IsLetterOrDigit); var compiler = new CompilerHelper(Indentation, MathOperator, MathOperator2, PrefixOperator, ComparisonOperator, String, Integer, Symbol); Func <string, Token> GetToken = compiler.GetToken; var SymbolParser = Tokens(Symbol); Parser <TypeName> TypeName; Parser <IEnumerable <TypeName> > TypeNames = null; Parser <(string, TypeName)> Variable; Parser <IEnumerable <(string, TypeName)> > Variables; TypeName = parser => new TypeName(SymbolParser.Invoke(parser), TypeNames(parser)); TypeNames = ListOf(GetToken("{"), TypeName, GetToken(","), GetToken("}")); Variable = parser => (SymbolParser.Invoke(parser), TypeName(parser)); Variables = ListOf(GetToken("["), Variable, GetToken(","), GetToken("]")); var expr = new ExprBuilders(new ExprWriters()); // Parser to Analyzer mappings compiler.ParserRules.SetRules( ParserRules.Rule(expr.CheckedCast, Prefix(GetToken("->"), TypeName), Expression), ParserRules.Rule(expr.Sequence, Sequence(Indentation, Expression)), ParserRules.Rule(expr.Function, Variables, Expression), ParserRules.Rule(expr.Function, ListOf(GetToken("{"), Variable, GetToken(","), GetToken("}")), Variables, Expression), ParserRules.Rule(expr.VariableAssign, Prefix(GetToken("let"), Suffix(SymbolParser, GetToken("="))), Expression), ParserRules.Rule(expr.Identity, Prefix(GetToken("("), Suffix(Expression, GetToken(")")))), ParserRules.Rule(expr.LiteralString, Tokens(String)), ParserRules.Rule(expr.LiteralInt, Tokens(Integer)), ParserRules.Rule(expr.LiteralBooleanTrue, GetToken("true")), ParserRules.Rule(expr.LiteralBooleanFalse, GetToken("false")), ParserRules.Rule(expr.If, Prefix(GetToken("if"), Expression), Expression, Prefix(GetToken("else"), Expression)), ParserRules.Rule(expr.This, GetToken("this")), ParserRules.Rule(expr.FunctionOperatorSingle, Tokens(PrefixOperator), Expression), ParserRules.Rule(expr.Variable, SymbolParser) ); compiler.ParserRules.SetInfixRules( ParserRules.Rule(expr.ContextVariable, weight: 6, Prefix(GetToken("."), SymbolParser)), ParserRules.Rule(expr.FunctionSetGenerics, weight: 5, TypeNames), ParserRules.Rule(expr.FunctionOperator, weight: 4, Tokens(MathOperator2), WeightedExpression(4)), ParserRules.Rule(expr.FunctionOperator, weight: 3, Tokens(MathOperator), WeightedExpression(3)), ParserRules.Rule(expr.FunctionOperator, weight: 2, Tokens(ComparisonOperator), WeightedExpression(2)), ParserRules.Rule(expr.BooleanAnd, weight: 1, Prefix(GetToken("and"), WeightedExpression(1))), ParserRules.Rule(expr.BooleanOr, weight: 1, Prefix(GetToken("or"), WeightedExpression(1))), ParserRules.Rule(expr.FunctionCall, weight: 6, ListOf(GetToken("("), Expression, GetToken(","), GetToken(")"))) ); compiler.AddType("int", Int); compiler.AddType("bool", Bool); compiler.AddType("string", Str); compiler.AddType("fun", Func); compiler.AddType("tuple", Tuple); compiler.AddType("union", Union); compiler.AddType("any", Any); compiler.AddType("void", Void); // Set of core functions. // TODO Optimize: compiler should 'unwrap' all short functions compiler.AddFunction("print", VMCommand.Print, Void, Any); compiler.AddFunction("<", VMCommand.CompareLessThan, Bool, Int, Int); compiler.AddFunction("+", VMCommand.MathAddition, Int, Int, Int); compiler.AddFunction("-", VMCommand.MathSubstraction, Int, Int, Int); compiler.AddFunction("*", VMCommand.MathMultiplication, Int, Int, Int); compiler.AddFunction("/", VMCommand.MathDivision, Int, Int, Int); compiler.AddFunction("!", VMCommand.BooleanNot, Bool, Bool); compiler.AddFunction("==", VMCommand.EqualInt, Bool, Bool, Bool); compiler.AddFunction("==", VMCommand.EqualInt, Bool, Int, Int); try { compiler.RunFile("Example"); } catch (CompilationException e) { Console.WriteLine("Compilation Error: " + e.Message); } }
private Type[] ArgumentTypes(TypeFunction f) { return(f.Formals.Values.Select(c => LookupCilType(c)).ToArray()); }
/// <summary> /// Парсит переданный текст на наличие функций и процедур /// </summary> /// <param name="text"></param> /// <returns></returns> public static FunctionList Parse(string[] text, FileModule fileModule) { var result = new FunctionList(fileModule); var countLines = text.Count(); var index = 0; var areas = new Stack <string>(); while (index < countLines) { var str = text[index].Trim(); var strLow = str.ToLower(); var indexStartName = 0; TypeFunction typeFunc = TypeFunction.function; // Если начало области, то поместим в стек ее название if (strLow.StartsWith(strAreaBegin)) { areas.Push(str.Substring(strAreaBegin.Length + 1)); } // Если конец области то уберем имя последней области из стека if (strLow.StartsWith(strAreaEnd)) { if (areas.Count > 0) { areas.Pop(); } } // Определяем процедура или функция. if (strLow.IndexOf(strProc) == 0) { indexStartName = strProc.Length; typeFunc = TypeFunction.procedure; } else if (strLow.IndexOf(strFunc) == 0) { indexStartName = strFunc.Length; } if (indexStartName > 0) { var firstBracket = strLow.IndexOf('('); if (firstBracket == -1) { firstBracket = strLow.IndexOf(';'); if (firstBracket == -1) { firstBracket = strLow.Length; } } var export = strLow.IndexOf(strExport) >= 0; var secondBracket = strLow.IndexOf(')'); var newFunction = new FunctionInfo(result); newFunction.Name = str.Substring(indexStartName, firstBracket - indexStartName).Trim(); newFunction.IndexStartDescript = GetStartDescriptFunction(text, index); newFunction.Type = typeFunc; newFunction.IndexStart = index; newFunction.Export = export; if (areas.Count > 0) { newFunction.Area = areas.ToArray().Reverse().ToArray(); } result.Add(newFunction); } index++; } result.Sort((x, y) => string.Compare(x.Name, y.Name)); return(result); }
public BuiltInFunctions() { // Text Functions["len"] = new Len(); Functions["lower"] = new Lower(); Functions["upper"] = new Upper(); Functions["left"] = new Left(); Functions["right"] = new Right(); Functions["mid"] = new Mid(); Functions["replace"] = new Replace(); Functions["rept"] = new Rept(); Functions["substitute"] = new Substitute(); Functions["concatenate"] = new Concatenate(); Functions["concat"] = new Concat(); Functions["char"] = new CharFunction(); Functions["exact"] = new Exact(); Functions["find"] = new Find(); Functions["fixed"] = new Fixed(); Functions["proper"] = new Proper(); Functions["search"] = new Search(); Functions["text"] = new Text.Text(); Functions["t"] = new T(); Functions["hyperlink"] = new Hyperlink(); Functions["value"] = new Value(); Functions["trim"] = new Trim(); Functions["clean"] = new Clean(); Functions["unicode"] = new Unicode(); Functions["unichar"] = new Unichar(); Functions["numbervalue"] = new NumberValue(); // Numbers Functions["int"] = new CInt(); // Math Functions["abs"] = new Abs(); Functions["asin"] = new Asin(); Functions["asinh"] = new Asinh(); Functions["cos"] = new Cos(); Functions["cosh"] = new Cosh(); Functions["power"] = new Power(); Functions["sign"] = new Sign(); Functions["sqrt"] = new Sqrt(); Functions["sqrtpi"] = new SqrtPi(); Functions["pi"] = new Pi(); Functions["product"] = new Product(); Functions["ceiling"] = new Ceiling(); Functions["count"] = new Count(); Functions["counta"] = new CountA(); Functions["countblank"] = new CountBlank(); Functions["countif"] = new CountIf(); Functions["countifs"] = new CountIfs(); Functions["fact"] = new Fact(); Functions["floor"] = new Floor(); Functions["sin"] = new Sin(); Functions["sinh"] = new Sinh(); Functions["sum"] = new Sum(); Functions["sumif"] = new SumIf(); Functions["sumifs"] = new SumIfs(); Functions["sumproduct"] = new SumProduct(); Functions["sumsq"] = new Sumsq(); Functions["stdev"] = new Stdev(); Functions["stdevp"] = new StdevP(); Functions["stdev.s"] = new Stdev(); Functions["stdev.p"] = new StdevP(); Functions["subtotal"] = new Subtotal(); Functions["exp"] = new Exp(); Functions["log"] = new Log(); Functions["log10"] = new Log10(); Functions["ln"] = new Ln(); Functions["max"] = new Max(); Functions["maxa"] = new Maxa(); Functions["median"] = new Median(); Functions["min"] = new Min(); Functions["mina"] = new Mina(); Functions["mod"] = new Mod(); Functions["average"] = new Average(); Functions["averagea"] = new AverageA(); Functions["averageif"] = new AverageIf(); Functions["averageifs"] = new AverageIfs(); Functions["round"] = new Round(); Functions["rounddown"] = new Rounddown(); Functions["roundup"] = new Roundup(); Functions["rand"] = new Rand(); Functions["randbetween"] = new RandBetween(); Functions["rank"] = new Rank(); Functions["rank.eq"] = new Rank(); Functions["rank.avg"] = new Rank(true); Functions["quotient"] = new Quotient(); Functions["trunc"] = new Trunc(); Functions["tan"] = new Tan(); Functions["tanh"] = new Tanh(); Functions["atan"] = new Atan(); Functions["atan2"] = new Atan2(); Functions["atanh"] = new Atanh(); Functions["acos"] = new Acos(); Functions["acosh"] = new Acosh(); Functions["var"] = new Var(); Functions["varp"] = new VarP(); Functions["large"] = new Large(); Functions["small"] = new Small(); Functions["degrees"] = new Degrees(); Functions["odd"] = new Odd(); Functions["even"] = new Even(); // Information Functions["isblank"] = new IsBlank(); Functions["isnumber"] = new IsNumber(); Functions["istext"] = new IsText(); Functions["isnontext"] = new IsNonText(); Functions["iserror"] = new IsError(); Functions["iserr"] = new IsErr(); Functions["error.type"] = new ErrorType(); Functions["iseven"] = new IsEven(); Functions["isodd"] = new IsOdd(); Functions["islogical"] = new IsLogical(); Functions["isna"] = new IsNa(); Functions["na"] = new Na(); Functions["n"] = new N(); Functions["type"] = new TypeFunction(); // Logical Functions["if"] = new If(); Functions["ifs"] = new Ifs(); Functions["iferror"] = new IfError(); Functions["ifna"] = new IfNa(); Functions["not"] = new Not(); Functions["and"] = new And(); Functions["or"] = new Or(); Functions["true"] = new True(); Functions["false"] = new False(); Functions["switch"] = new Switch(); // Reference and lookup Functions["address"] = new Address(); Functions["hlookup"] = new HLookup(); Functions["vlookup"] = new VLookup(); Functions["lookup"] = new Lookup(); Functions["match"] = new Match(); Functions["row"] = new Row(); Functions["rows"] = new Rows(); Functions["column"] = new Column(); Functions["columns"] = new Columns(); Functions["choose"] = new Choose(); Functions["index"] = new RefAndLookup.Index(); Functions["indirect"] = new Indirect(); Functions["offset"] = new Offset(); // Date Functions["date"] = new Date(); Functions["today"] = new Today(); Functions["now"] = new Now(); Functions["day"] = new Day(); Functions["month"] = new Month(); Functions["year"] = new Year(); Functions["time"] = new Time(); Functions["hour"] = new Hour(); Functions["minute"] = new Minute(); Functions["second"] = new Second(); Functions["weeknum"] = new Weeknum(); Functions["weekday"] = new Weekday(); Functions["days"] = new Days(); Functions["days360"] = new Days360(); Functions["yearfrac"] = new Yearfrac(); Functions["edate"] = new Edate(); Functions["eomonth"] = new Eomonth(); Functions["isoweeknum"] = new IsoWeekNum(); Functions["workday"] = new Workday(); Functions["workday.intl"] = new WorkdayIntl(); Functions["networkdays"] = new Networkdays(); Functions["networkdays.intl"] = new NetworkdaysIntl(); Functions["datevalue"] = new DateValue(); Functions["timevalue"] = new TimeValue(); // Database Functions["dget"] = new Dget(); Functions["dcount"] = new Dcount(); Functions["dcounta"] = new DcountA(); Functions["dmax"] = new Dmax(); Functions["dmin"] = new Dmin(); Functions["dsum"] = new Dsum(); Functions["daverage"] = new Daverage(); Functions["dvar"] = new Dvar(); Functions["dvarp"] = new Dvarp(); //Finance Functions["pmt"] = new Pmt(); }
public NativeJsonFile Do(string Base64File, Dictionary <string, object> FileData) { var Base64EncodedBytes = System.Convert.FromBase64String(Base64File); MemoryStream SourceFile = new MemoryStream(Base64EncodedBytes); object Delimiter = null; FileData.TryGetValue("Delimiter", out Delimiter); if (Delimiter == null) { throw new Exception(ServicesConstants.DelimiterMissing); } object HasTitleInDefinition = null; FileData.TryGetValue("HasTitle", out HasTitleInDefinition); bool HasTitle = HasTitleInDefinition != null && Convert.ToBoolean(HasTitleInDefinition.ToString()); string JsonFileConverted = ""; string [] Columns = null; int Step = 0; List <JObject> JObjectList = new List <JObject>(); using (StreamReader StreamReader = new StreamReader(SourceFile)) { String ActualLine = ""; while ((ActualLine = StreamReader.ReadLine()) != null) { string[] DataInLine = ActualLine.Split(Delimiter.ToString()); int ColumnsQuantity = DataInLine.Length; Step++; if (Step == 1) { if (HasTitle) { Columns = DataInLine; } else { Columns = new string[ColumnsQuantity]; for (int i = 0; i < ColumnsQuantity; i++) { Columns[i] = "Column-" + i.ToString(); } } } dynamic JObjectLine = new JObject(); if (Step > 1 || !HasTitle) { int i = 0; foreach (string Data in DataInLine) { JObjectLine[Columns[i]] = new JValue(TypeFunction.GetTyped(Data));; i++; } JObjectList.Add(JObjectLine); } } } var JSonFileConverted = Newtonsoft.Json.JsonConvert.SerializeObject(JObjectList); NativeJsonFile NativeJsonFile = new NativeJsonFile(); NativeJsonFile.Content = JSonFileConverted; NativeJsonFile.Columns = Columns; return(NativeJsonFile); }
/// <summary> /// VisitInvoke and VisitDereferenceField are very similiar, so this should probably be refactored out /// into a common method. /// </summary> /// <param name="n"></param> public override void VisitInvoke(ASTInvoke n) { //Make sure the lvalue is a type and the method name exists CFlatType lhs = CheckSubTree(n.Object); if (lhs.IsClass) { TypeClass lvalue = (TypeClass)lhs; var descriptor = (ClassDescriptor)_scopeMgr.Find(lvalue.ClassName, p => p is ClassDescriptor); //check if a method with the given name exists in the scope. //This needs to check not only the class's shallow scope, but all the parents as well. MethodDescriptor methodDesc = _scopeMgr.Find(n.Method, d => d is MethodDescriptor, descriptor.Scope) as MethodDescriptor; //if (methodDesc != null && (descriptor.Methods.Contains(methodDesc) || methodDesc.IsCFlatMethod)) if (methodDesc != null) { if (methodDesc.Modifiers.Contains(PRIVATE_MODIFIER, StringComparer.InvariantCultureIgnoreCase)) { if (!_scopeMgr.HasSymbol(n.Method, _currentClass.Scope)) { ReportError(n.Location, "Cannot access the private method {0} in class {1} from class {2}", methodDesc.Name, methodDesc.ContainingClass.Name, _currentClass.ClassName); } } //check if the arguments match TypeFunction method = (TypeFunction)methodDesc.Type; //visit any actuals that need processing CheckSubTree(n.Actuals); //collect the actuals var curMethDesc = _scopeMgr.Find(_currentMethod.Name, d => d is MethodDescriptor) as MethodDescriptor; ActualBuilder builder = new ActualBuilder(curMethDesc); n.Actuals.Visit(builder); if (method.AcceptCall(builder.Actuals)) //if the types check { CheckActualsHaveReadonly(methodDesc, builder, n); CheckReadonlyNotPassedAsModifiable(methodDesc, builder, n); n.Descriptor = methodDesc; n.CFlatType = method.ReturnType; _lastSeenType = method.ReturnType; //check if we're processing an exit instruction, and if so, this counts as a return for the current block. if (IsExitMethod(n)) { _currentMethod.RegisterReturnStatement(); } } else { ReportError(n.Location, "Invalid parameters for method '{0}.{1}'", TypeToFriendlyName(lvalue), n.Method); } } else { ReportError(n.Location, "Method '{0}' does not exist for type '{1}'", n.Method, TypeToFriendlyName(lvalue)); } } else { ReportError(n.Location, "Type '{0}' does not support methods.", TypeToFriendlyName(lhs)); } }
public Function(Spv.FunctionControl functionControl, TypeFunction functionType, string debugName = null) : this(functionType.ReturnType, functionControl, functionType, debugName) { }
public SystemMethod(string name, TypeFunction info) { Name = name; FuncInfo = info; }