/// <summary> /// Strong Contruction /// </summary> /// <param name="map">Map to solve</param> public SolverController(SokobanMap map) { if (map == null) throw new ArgumentNullException("map"); this.settings = new Settings(); this.state = States.NotStarted; this.map = map; debugReport = new SolverReport(); debugReport.AppendHeading(1, "SokoSolve | Solver Debug Report v{0}", ProgramVersion.VersionString); debugReport.Append("Creating Statistics"); stats = new SolverStats(this); debugReport.Append("Creating Exit Conditions"); exitConditions = new ItteratorExitConditions(); // TODO: This should be configured, perhaps via a factory pattern debugReport.Append("Creating Forward Strategy"); strategy = new SolverStrategy(this); debugReport.Append("Creating Forward Evaluator"); evaluator = new Evaluator<SolverNode>(true); debugReport.Append("Creating Reverse Strategy"); reverseStrategy = new ReverseStrategy(this); debugReport.Append("Creating Reverse Evaluator"); reverseEvaluator = new Evaluator<SolverNode>(true); }
/// <summary>Called when [first run].</summary> /// /// <exception cref="InvalidDataException">Thrown when an Invalid Data error condition occurs.</exception> protected override void OnFirstRun() { if (varName != null) return; var declaration = Condition.TrimEnd().TrimEnd(';'); var parts = declaration.Split('='); if (parts.Length != 2) throw new InvalidDataException( "Invalid var declaration, should be '@var varName = {MemberExpression} [, {VarDeclaration}]' was: " + declaration); varName = parts[0].Trim(); memberExpr = parts[1].Trim(); this.Condition = memberExpr; const string methodName = "resolveVarType"; var exprParams = GetExprParams(); var evaluator = new Evaluator(ReturnType, Condition, methodName, exprParams); var result = evaluator.Evaluate(methodName, GetParamValues(ScopeArgs).ToArray()); ScopeArgs[varName] = result; if (result != null) this.ReturnType = result.GetType(); base.OnFirstRun(); }
//private volatile bool timesUp; //private double time; //public void timedSearch(int depth) //{ // timesUp = false; // var timer = new Timer(800 - _start); // //timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // timer.Elapsed += timer_Elapsed; // timer.Start(); // expand(depth); // timer.Stop(); //} public MiniMaxNode(GameState g, Evaluator e, int player) { this.State = g; this.e = e; this.player = player; Parent = this; }
public override Token Minify(Evaluator evaluator) { Arguments = Arguments.Select(arg => arg.Minify(evaluator)).ToArray(); if (!Arguments.All(arg => arg is ConstantToken)) return this; return new ConstantToken(Evaluate(evaluator)); }
internal override Result Eval(Evaluator evaluater, Result[] argArray) { if ((bool)argArray[0].Value) { return argArray[1]; } else { return argArray[2]; } }
/// <summary> /// Calculates the tangent, binormal, normal, speed and curvature on the spline at fraction t /// </summary> public override CurveFrame EvaluateFrame( float t ) { Evaluator eval = new Evaluator( ); MakeEvaluator( ref eval, this, t ); return eval.EvaluateFrame( ); }
/// <summary> /// Evaluates the curvature on the spline at fraction t /// </summary> public override float EvaluateCurvature( float t ) { Evaluator eval = new Evaluator( ); MakeEvaluator( ref eval, this, t ); return eval.EvaluateCurvature( ); }
/// <summary> /// Calculates the second derivative on the spline at fraction t /// </summary> public override Vector3 EvaluateSecondDerivative( float t ) { Evaluator eval = new Evaluator( ); MakeEvaluator( ref eval, this, t ); return eval.EvaluateSecondDerivative( ); }
/// <summary> /// Calculates the position on the spline at fraction t /// </summary> public override Point3 EvaluatePosition( float t ) { Evaluator eval = new Evaluator( ); MakeEvaluator( ref eval, this, t ); return eval.EvaluatePosition( ); }
public void TestBools() { Evaluator e = new Evaluator(); Assert.IsTrue(e.Evaluate("true") ? true : false); Assert.IsFalse(e.Evaluate("false") ? true : false); Assert.IsFalse(e.Evaluate("!true") ? true : false); Assert.IsTrue(e.Evaluate("!false") ? true : false); if (e.Evaluate("!!!true")) { Assert.Fail(); } if (!e.Evaluate("10")) { Assert.Fail(); } Assert.IsTrue(e.Evaluate("1 != 2").As<bool>()); Assert.IsTrue(e.Evaluate("(true || false)").As<bool>()); Assert.IsFalse(e.Evaluate("(true && false) || (false)").As<bool>()); Assert.IsFalse(e.Evaluate("(true && false) && (false)").As<bool>()); Assert.IsFalse(e.Evaluate("(true && !false) && (false)").As<bool>()); }
public void FloodFill() { Bitmap map = new Bitmap(new string[] { "111111111111111111", "100000000000001001", "100000000000001001", "100001111111001001", "100001010001001001", "100001000101001001", "100001111111000001", "111011000000001111", "100000001000010001", "100000001000010001", "111111111111111111" }); Debug.WriteLine(map.ToString()); Evaluator<LocationNode> eval = new Evaluator<LocationNode>(); FloodFillStrategy strategy = new FloodFillStrategy(map, new VectorInt(2, 2)); eval.Evaluate(strategy); Debug.WriteLine(strategy.Result.ToString()); List<LocationNode> path = strategy.GetShortestPath(new VectorInt(9, 9)); Assert.IsNotNull(path); Debug.WriteLine(StringHelper.Join(path, delegate(LocationNode node) { return node.Location.ToString(); }, ", ")); Debug.WriteLine(map.ToString()); // Expected value Assert.AreEqual(new VectorInt(9, 9), path[path.Count - 1].Location); }
private int prec = System.Int32.MaxValue; // the precedence this operator has #endregion Fields #region Constructors /// <summary> /// Creates an Operator /// </summary> /// <param name="_operator">string operator symbol</param> /// <param name="arguments">number of arguments</param> /// <param name="precedence">precedence relative to other operators</param> /// <param name="eval">delegate to use for evaluating operator</param> public Operator(String _operator, int arguments, int precedence, Evaluator eval) { this.op = _operator; this.args = arguments; this.prec = precedence; this.evaluator = eval; }
public GameState doSearch(GameState g, Evaluator e, int depth, double time) { HiPerfTimer timer = new HiPerfTimer(); List<MiniMaxNode> trees = new List<MiniMaxNode>(); foreach (GameState gs in g.getSuccessorStates(0)) { timer.Start(); trees.Add(MiniMaxNode.getGameTree(gs, e, depth, time)); timer.Stop(); time += timer.Duration * 1000; } int eval = 0; MiniMaxNode bestNode = new MiniMaxNode(g,e,0); foreach (MiniMaxNode tree in trees) { tree.score = tree.evaluate(int.MinValue, int.MaxValue); if (tree.score > eval) { eval = tree.score; bestNode = tree; } } return bestNode.State; }
public Form1() { mInitializing = true; ev = new Evaluator(Eval3.eParserSyntax.cSharp,false); ev.AddEnvironmentFunctions(this); ev.AddEnvironmentFunctions(new EvalFunctions()); // This call is required by the Windows Form Designer. A = new Eval3.EvalVariable(0.0, typeof(double)); B = new Eval3.EvalVariable(0.0, typeof(double)); C = new Eval3.EvalVariable(0.0, typeof(double)); // This call is required by the Windows Form Designer. InitializeComponent(); A.Value = (double)updownA.Value; B.Value = (double)updownB.Value; C.Value = (double)updownC.Value; // Add any initialization after the InitializeComponent() call mInitializing = false; btnEvaluate_Click(null, null); btnEvaluate2_Click(null, null); btnEvaluate3_Click(null, null); }
public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { Guard.AgainstNullArgument("references", references); Guard.AgainstNullArgument("scriptPackSession", scriptPackSession); references.PathReferences.UnionWith(scriptPackSession.References); SessionState<Evaluator> sessionState; if (!scriptPackSession.State.ContainsKey(SessionKey)) { Logger.Debug("Creating session"); var context = new CompilerContext(new CompilerSettings { AssemblyReferences = references.PathReferences.ToList() }, new ConsoleReportPrinter()); var evaluator = new Evaluator(context); var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct(); var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs); MonoHost.SetHost((ScriptHost)host); evaluator.ReferenceAssembly(typeof(MonoHost).Assembly); evaluator.InteractiveBaseClass = typeof(MonoHost); sessionState = new SessionState<Evaluator> { References = new AssemblyReferences(references.PathReferences, references.Assemblies), Namespaces = new HashSet<string>(), Session = evaluator }; ImportNamespaces(allNamespaces, sessionState); scriptPackSession.State[SessionKey] = sessionState; } else { Logger.Debug("Reusing existing session"); sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey]; var newReferences = sessionState.References == null ? references : references.Except(sessionState.References); foreach (var reference in newReferences.PathReferences) { Logger.DebugFormat("Adding reference to {0}", reference); sessionState.Session.LoadAssembly(reference); } sessionState.References = new AssemblyReferences(references.PathReferences, references.Assemblies); var newNamespaces = sessionState.Namespaces == null ? namespaces : namespaces.Except(sessionState.Namespaces); ImportNamespaces(newNamespaces, sessionState); } Logger.Debug("Starting execution"); var result = Execute(code, sessionState.Session); Logger.Debug("Finished execution"); return result; }
/// <summary> /// Call let* evaluator. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The environment to make the expression in.</param> /// <param name="caller">The caller. Return to this when done.</param> /// <returns>The let evaluator.</returns> internal static Evaluator Call(SchemeObject expr, Environment env, Evaluator caller) { if (expr is EmptyList) { ErrorHandlers.SemanticError("No arguments arguments for let*", null); } if (!(expr is Pair)) { ErrorHandlers.SemanticError("Bad arg list for let*: " + expr, null); } SchemeObject bindings = First(expr); SchemeObject body = Rest(expr); if (body is EmptyList) { caller.ReturnedExpr = Undefined.Instance; return caller; } SchemeObject vars = MapFun(First, bindings); SchemeObject inits = MapFun(Second, bindings); SchemeObject formals = EmptyList.Instance; SchemeObject vals = EmptyList.Instance; return new EvaluateLetStar(expr, env, caller, body, vars, inits, formals, vals); }
/// <summary> /// Create a list evaluator. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The environment to make the expression in.</param> /// <param name="caller">The caller. Return to this when done.</param> /// <returns>A list evaluator.</returns> internal static Evaluator Call(SchemeObject expr, Environment env, Evaluator caller) { // first check for degenerate cases if (expr is EmptyList) { caller.ReturnedExpr = EmptyList.Instance; return caller; } if (!(expr is Pair)) { ErrorHandlers.SemanticError("Bad args for list: " + expr, null); } if (AllEvaluated(expr)) { // Skip creating an evaluator or a list if all elements are constants. caller.ReturnedExpr = expr; return caller; } if (AllSimple(expr)) { // Skip creating an evaluator if all elements are constants or symbols. caller.ReturnedExpr = EvaluateSymbolsInList(expr, env); return caller; } // Something actually needs to be evaluated. return new EvaluateList(expr, env, caller); }
static void Main(string[] args) { string command = ""; do { Console.Write(Prompt); command = Console.ReadLine(); if (string.IsNullOrWhiteSpace(command)) { continue; } command = command.Trim(); if (command.StartsWith("/")) { if (processSpecialCommand(command)) break; continue; } try { sb.Append(command).Append("\n"); string text = sb.ToString(); _evaluator = new Evaluator(text); Console.Write("->\n" + _evaluator.Interpret() + "\n"); } catch (Exception e) { Console.Write("!> " + e.Message + "\n"); sb.Clear(); } } while (command != ExitCommand); }
/// <summary> /// Call letrec evaluator. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The environment to make the expression in.</param> /// <param name="caller">The caller. Return to this when done.</param> /// <returns>The let evaluator.</returns> internal static Evaluator Call(SchemeObject expr, Environment env, Evaluator caller) { if (expr is EmptyList) { ErrorHandlers.SemanticError("No arguments for letrec", null); } if (!(expr is Pair)) { ErrorHandlers.SemanticError("Bad arg list for letrec: " + expr, null); } SchemeObject body = Rest(expr); if (body is EmptyList) { caller.ReturnedExpr = Undefined.Instance; return caller; } SchemeObject bindings = First(expr); //// In the bindings, the variables are first, the values are second, and anything left over is discarded. //// If either is missing, an empty list is used instead. //// To start with, bindings are undefined. SchemeObject formals = MapFun(First, bindings); SchemeObject inits = MapFun(Second, bindings); SchemeObject initVals = Fill(ListLength(formals), Undefined.Instance); return new EvaluateLetRec(expr, new Environment(formals, initVals, env), caller, body, formals, inits); }
public MiniMaxNode(GameState g, Evaluator e, int player, MiniMaxNode parent) { this.State = g; this.e = e; this.player = player; this.Parent = parent; }
/// <summary> /// Initializes a new instance of the EvaluateLet class. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The evaluation environment</param> /// <param name="caller">The caller. Return to this when done.</param> /// <param name="name">The name of a named let.</param> /// <param name="body">The let body.</param> /// <param name="vars">The variables to bind.</param> /// <param name="inits">The initial values of the variables.</param> private EvaluateLet(SchemeObject expr, Environment env, Evaluator caller, Symbol name, SchemeObject body, SchemeObject vars, SchemeObject inits) : base(InitialStep, expr, env, caller) { this.name = name; this.body = body; this.vars = vars; this.inits = inits; }
internal override double Evaluate(Evaluator evaluator) { FunctionCallback function; bool success = evaluator.Functions.TryGetValue(FunctionName, out function); if (!success) throw new EvaluationException(string.Format("Could not find a function named `{0}`.", FunctionName), this); return function(this, evaluator); }
/// <summary> /// Initializes a new instance of the EvaluateList class. /// This is used in the "list" primitive, and ALSO to evaluate the /// arguments in a list that is part of procedure application. /// Because it is used internally, the evaluator must not use destructive /// operations on its member variables. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The evaluation environment</param> /// <param name="caller">The caller. Return to this when done.</param> private EvaluateList(SchemeObject expr, Environment env, Evaluator caller) : base(EvalExprStep, expr, env, caller) { // Start with an empty list. As exprs are evaluated, they will be consed on the // front. The list will be reversed before it is returned. Because this is done // destructively, cloning needs to copy the result. this.result = EmptyList.Instance; }
public void TestMethod5() { var evaluator = new Evaluator(); var reader = new Reader(); var program = "((lambda () #t))"; var sexp = reader.Read(program, evaluator.Environment); var rexp = evaluator.Evaluate(sexp); }
/// <summary> /// Initializes a new instance of the EvaluateLetStar class. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The evaluation environment</param> /// <param name="caller">The caller. Return to this when done.</param> /// <param name="body">The let* body.</param> /// <param name="vars">The list of variables to bind.</param> /// <param name="inits">The initialization expressions.</param> /// <param name="formals">The list of parameters to pass to the lambda.</param> /// <param name="vals">Evaluated values of inits.</param> private EvaluateLetStar(SchemeObject expr, Environment env, Evaluator caller, SchemeObject body, SchemeObject vars, SchemeObject inits, SchemeObject formals, SchemeObject vals) : base(EvalInitStep, expr, env, caller) { this.body = body; this.vars = vars; this.inits = inits; this.formals = formals; this.vals = vals; }
/// <summary> /// Initializes a new instance of the EvaluateLetRec class. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The evaluation environment</param> /// <param name="caller">The caller. Return to this when done.</param> /// <param name="body">The let body.</param> /// <param name="vars">The variables to be bound.</param> /// <param name="inits">The initialization expressions.</param> private EvaluateLetRec(SchemeObject expr, Environment env, Evaluator caller, SchemeObject body, SchemeObject vars, SchemeObject inits) : base(EvalInitStep, expr, env, caller) { this.body = body; this.vars = vars; this.inits = inits; this.formals = vars; this.vals = EmptyList.Instance; }
/// <summary> /// Apply the recipient function to the value of the test. /// The recipient must evaluate to a procecure. /// </summary> /// <param name="s">This evaluator.</param> /// <returns>The next evaluator to execute (the return).</returns> private static Evaluator ApplyRecipientStep(Evaluator s) { var step = (EvaluateCond)s; return EvaluateProc.CallQuoted( Procedure.EnsureProcedure(s.ReturnedExpr), MakeList(step.test), s.Env, s.Caller); }
public void TestDoubleArithmetic() { Evaluator e = new Evaluator(); Assert.AreEqual(5.0, e.Evaluate("2.5 * 2").As<double>()); Assert.AreEqual(5.0, e.Evaluate("2.5 * 2").As<double>()); Assert.AreEqual(5, e.Evaluate("2.6 * 2").As<int>()); Assert.AreEqual(5.2, e.Evaluate("2.6 * 2").As<double>()); }
public int averageStateEvaluation(Evaluator e) { int score = 0; foreach (GameState g in gameStates) { score += e.evaluation(g, MyTronBot.Player); } return score / gameStates.Count; }
/// <summary> /// Initializes a new instance of the EvaluateDo class. /// </summary> /// <param name="expr">The expression to evaluate.</param> /// <param name="env">The evaluation environment</param> /// <param name="caller">The caller. Return to this when done.</param> /// <param name="vars">The variables.</param> /// <param name="inits">The initialization expressions.</param> /// <param name="steps">The steps.</param> /// <param name="exprs">The expressions.</param> /// <param name="commands">The commands.</param> /// <param name="testProc">The test proc to execute each interation.</param> private EvaluateDo(SchemeObject expr, Environment env, Evaluator caller, SchemeObject vars, SchemeObject inits, SchemeObject steps, SchemeObject exprs, SchemeObject commands, Lambda testProc) : base(InitialStep, expr, new Environment(env), caller) { this.vars = vars; this.inits = inits; this.steps = steps; this.exprs = exprs; this.commands = commands; this.testProc = testProc; }
public TranslateResult Translate(Expression expression) { expression = Evaluator.PartialEval(expression); return(new QueryTranslator( ).Translate(expression)); }
public void TestPlusInvalidVariable() { Evaluator.Evaluate("5+xx", s => 0); }
public CommonExpressionEvaluator() { this.ExprEvaluator = new Evaluator(); this.ExprErrorHandler = new ErrorHandler(new ErrorNodeList()); }
public IMetadataConstant /*?*/ GetCompileTimeConstantValueFor(Instruction expression, AiBasicBlock <Instruction> /*?*/ block = null) { Contract.Requires(expression != null); var result = this.compileTimeConstantValueForExpression[expression] as IMetadataConstant; if (result != null) { return(result); } var ce = this.GetCanonicalExpressionFor(expression); if (ce == null) { return(null); } result = this.compileTimeConstantValueForExpression[ce] as IMetadataConstant; if (result != null || block == null) { return(result); } result = block.ConstantForExpression[expression] as IMetadataConstant; if (result != null) { if (result == Dummy.Constant) { return(null); } return(result); } var operand1 = ce.Operand1 as Instruction; if (operand1 == null) { return(null); } var operand2 = ce.Operand2 as Instruction; if (operand2 != null) { result = Evaluator.Evaluate(ce.Operation, operand1, operand2, this, block); block.ConstantForExpression[expression] = result ?? Dummy.Constant; if (result != null && result != Dummy.Constant) { return(result); } } else { var operands2toN = ce.Operand2 as Instruction[]; if (operands2toN != null) { result = Evaluator.Evaluate(ce.Operation, operand1, operands2toN, this, block); block.ConstantForExpression[expression] = result ?? Dummy.Constant; if (result != null && result != Dummy.Constant) { return(result); } } } return(null); }
public UniqueRowsConstraint() { Engine = new IndexEvaluator(); }
public void TestParensNoOperator() { Evaluator.Evaluate("5+7+(5)8", s => 0); }
private static bool Prefix(Corpse corpse) => (corpse.InnerPawn == null) || !Evaluator.IsListedPawnKind(corpse.InnerPawn) || Evaluator.IsExplosionImmiment();
public override string ExportTableInsertScript() { SQLTableScript table = new SQLTableScript("id", "code", "id INT NOT NULL", "code VARCHAR(6) NOT NULL", "name TEXT NOT NULL", "formatted_name TEXT NOT NULL", "display_string TEXT NOT NULL", "ilvl_range TEXT NOT NULL", "allowed_types TEXT NOT NULL", "faction TEXT" , "feed_costs TEXT NOT NULL" ); var affixes = Manager.GetDataTable("AFFIXES"); string id, code, magicName, formattedName, displayString, levelRange, typeList, faction; string[] feeds; string quality, property1, allowType; bool isMonster = false; Evaluator evaluator = new Evaluator(); ItemDisplay.Manager = Manager; evaluator.Manager = Manager; foreach (DataRow row in affixes.Rows) { //don't show affixes that aren't used/implemented if ((int)row["spawn"] == 0) { continue; } isMonster = false; magicName = row["magicNameString_string"].ToString(); if (String.IsNullOrWhiteSpace(magicName)) { continue; } typeList = string.Empty; faction = row["onlyOnItemsRequiringUnitType_string"].ToString(); if (!String.IsNullOrWhiteSpace(faction)) { faction = GetSqlString(faction); } for (int i = 1; i < 7; i++) { allowType = row[String.Format("allowTypes{0}_string", i)].ToString(); if (String.IsNullOrWhiteSpace(allowType)) { break; } else if (allowType.CompareTo("monster") == 0) { isMonster = true; break; } if (!String.IsNullOrWhiteSpace(typeList)) { typeList += ", "; } typeList += GetItemType(allowType); } if (isMonster) { continue; } typeList = GetSqlString(typeList); levelRange = GetSqlString(row["minLevel"].ToString() + "-" + row["maxLevel"].ToString()); Unit unit = new Item(); Game3 game3 = new Game3(); evaluator.Unit = unit; evaluator.Game3 = game3; for (int i = 1; i < 7; i++) { property1 = row["property" + i].ToString(); evaluator.Evaluate(property1); } String[] displayStrings = ItemDisplay.GetDisplayStrings(unit); feeds = ItemDisplay.GetFeedCosts(unit); id = row["Index"].ToString(); code = GetSqlString(((int)row["code"]).ToString("X")); magicName = magicName.Replace("[item]", string.Empty).Trim(); formattedName = String.Format("'''{0}'''", magicName); quality = row["affixType1_string"].ToString(); switch (quality) { case "common": //just leave it bold break; case "rare": formattedName = Colorize(formattedName, WikiColors.Rare); break; case "legendary": formattedName = Colorize(formattedName, WikiColors.Legendary); break; case "mythic": formattedName = Colorize(formattedName, WikiColors.Mythic); break; default: throw new NotImplementedException(String.Format("Apparently we need '{0}'?", quality)); } magicName = GetSqlString(magicName); formattedName = GetSqlString(formattedName); displayString = GetSqlString(FormatAffixList(displayStrings)); Debug.WriteLine(id + ", " + row["affix"] + ", " + displayString); table.AddRow(id, code, magicName, formattedName, displayString, levelRange, typeList, faction, GetSqlString(FormatAffixList(feeds))); } return(table.GetFullScript()); }
public void TestSingleNumber() { Assert.AreEqual(5, Evaluator.Evaluate("5", s => 0)); }
public void TestRepeatedVar() { Assert.AreEqual(0, Evaluator.Evaluate("a4-a4*a4/a4", s => 3)); }
public void TestComplexNestedParensLeft() { Assert.AreEqual(12, Evaluator.Evaluate("((((x1+x2)+x3)+x4)+x5)+x6", s => 2)); }
public void TestComplexNestedParensRight() { Assert.AreEqual(6, Evaluator.Evaluate("x1+(x2+(x3+(x4+(x5+x6))))", s => 1)); }
public void TestOperatorAfterParens() { Assert.AreEqual(0, Evaluator.Evaluate("(1*1)-2/2", s => 0)); }
public void TestComplexTimesParentheses() { Assert.AreEqual(26, Evaluator.Evaluate("2+3*(3+5)", s => 0)); }
public static Token Parse(Node node) { try { if (node.Token.Type == TOKENTYPE.Expression) { //operand if (node.Token.Value == ACTIONS.OperandEval) { node.Token = Evaluator.OperandEval(node.Children[0].Token); } //negative number (-1) else if (node.Token.Value == ACTIONS.NegativeNumberEval) { node.Children[1].Token = Parse(node.Children[1]); if (node.Children[1].Token.Type == TOKENTYPE.ERROR) { return(node.Children[1].Token); } node.Token = Evaluator.NegativeNumberEval(node.Children[0].Token, node.Children[1].Token); } //ex: .Length | .IsNullOrEmpty else if (node.Token.Value == ACTIONS.PostfixUnaryEval) { node.Children[0].Token = Parse(node.Children[0]); if (node.Children[0].Token.Type == TOKENTYPE.ERROR) { return(node.Children[0].Token); } node.Token = Evaluator.PostfixUnaryEval(node.Children[0].Token, node.Children[1].Token); } //ex: .GetValueAt(int) else if (node.Token.Value == ACTIONS.PostfixUnaryWithArgEval) { node.Children[0].Token = Parse(node.Children[0]); if (node.Children[0].Token.Type == TOKENTYPE.ERROR) { return(node.Children[0].Token); } List <Token> parametersToken = new List <Token>(); for (var index = 3; index < node.Children.Count - 1; index++) { if (node.Children[index] != null) { if (node.Children[index].Token.Type == TOKENTYPE.Delimiter) { continue; } node.Children[index].Token = Parse(node.Children[index]); if (node.Children[index].Token.Type == TOKENTYPE.ERROR) { return(node.Children[index].Token); } parametersToken.Add(node.Children[index].Token); } } node.Token = Evaluator.PostfixUnaryWithArgEval(node.Children[0].Token, node.Children[1].Token, parametersToken); } // (!) else if (node.Token.Value == ACTIONS.PrefixUnaryEval) { node.Children[1].Token = Parse(node.Children[1]); if (node.Children[1].Token.Type == TOKENTYPE.ERROR) { return(node.Children[1].Token); } node.Token = Evaluator.PrefixUnaryEval(node.Children[0].Token, node.Children[1].Token); } //( + - / * ) else if (node.Token.Value == ACTIONS.Arithmatic) { node.Children[0].Token = Parse(node.Children[0]); if (node.Children[0].Token.Type == TOKENTYPE.ERROR) { return(node.Children[0].Token); } node.Children[2].Token = Parse(node.Children[2]); if (node.Children[2].Token.Type == TOKENTYPE.ERROR) { return(node.Children[2].Token); } node.Token = Evaluator.Arithmetic(node.Children[0].Token, node.Children[1].Token, node.Children[2].Token); } //[ exp , exp , exp ] else if (node.Token.Value == ACTIONS.ArrayEval) { List <dynamic> temp = new List <dynamic>(); for (int i = 1; i < node.Children.Count - 1; i++) { if (node.Children[i].Token.Type == TOKENTYPE.Expression) { var result = Parse(node.Children[i]); if (result.Type == TOKENTYPE.ERROR) { return(result); } temp.Add(result); } } node.Token = new Token { Value = temp, Type = TOKENTYPE.Array }; } // exp ? exp : exp else if (node.Token.Value == ACTIONS.Ternary) { node.Children[0].Token = Parse(node.Children[0]); if (node.Children[0].Token.Type == TOKENTYPE.Boolean) { if (node.Children[0].Token.Value == true) { node.Token = Parse(node.Children[2]); } else { node.Token = Parse(node.Children[4]); } if (node.Token.Type == TOKENTYPE.ERROR) { return(node.Token); } } else { node.Token.Type = TOKENTYPE.ERROR; node.Token.Value = "Condition must return boolean"; return(node.Children[0].Token.Type == TOKENTYPE.ERROR ? node.Children[0].Token : node.Token); } } else { throw new Exception("No matching Action found for the expression."); } } else if (node.Token.Type == TOKENTYPE.ERROR) { throw new Exception(node.Token.Value); } else { throw new Exception("Expression is not declared."); } return(node.Token); } catch (Exception ex) { return(new Token { Value = ex.ToString(), Type = TOKENTYPE.ERROR }); } }
public void TestExtraParentheses() { Evaluator.Evaluate("2+5*7)", s => 0); }
public void FunctionParsing() { var evaluator1 = new Evaluator(); Assert.AreEqual("sin(30)", Parser.Parse("sin(30)").ToString()); }
private static bool IsTheSameObject(Expression expression, Expression other) { bool isTheSameObject = new ExpressionComparison(Evaluator.PartialEval(expression), Evaluator.PartialEval(other)).ExpressionsAreEqual; return(isTheSameObject); }
public void TestSingleOperator() { Evaluator.Evaluate("+", s => 0); }
protected override string OnAssembleLine(SourceLine line) { if (Reserved.IsOneOf("Assignments", line.InstructionName) || line.InstructionName.Equals("=")) { if (string.IsNullOrEmpty(line.LabelName)) { Assembler.Log.LogEntry(line, line.Label, "Invalid assignment expression.", true); } else { if (line.LabelName.Equals("*")) { if (line.InstructionName.Equals(".global")) { Assembler.Log.LogEntry(line, line.Instruction, "Invalid use of Program Counter in expression.", true); } else { Assembler.Output.SetPC((int)Evaluator.Evaluate(line.Operand, short.MinValue, ushort.MaxValue)); } } else if (line.LabelName.Equals("+") || line.LabelName.Equals("-")) { if (line.InstructionName.Equals(".global")) { Assembler.Log.LogEntry(line, line.Instruction, "Invalid use of reference label in expression.", true); } else { var value = Evaluator.Evaluate(line.Operand, short.MinValue, ushort.MaxValue); Assembler.SymbolManager.DefineLineReference(line.LabelName, value); } } else { if (line.InstructionName.Equals(".global")) { if (line.OperandHasToken) { Assembler.SymbolManager.DefineGlobal(line.Label, line.Operand, false); } else { Assembler.SymbolManager.DefineGlobal(line.LabelName, Assembler.Output.LogicalPC); } } else { Assembler.SymbolManager.Define(line); } } } } else if (line.InstructionName.Equals(".let")) { if (!line.OperandHasToken || line.Operand.Children[0].Children.Count < 3) { Assembler.Log.LogEntry(line, line.Instruction, $"Directive \".let\" expects an assignment expression."); } else if (line.Operand.Children.Count > 1) { Assembler.Log.LogEntry(line, line.Operand.LastChild, "Extra expression not valid."); } else { Assembler.SymbolManager.Define(line.Operand.Children[0].Children, true); } } else if (line.InstructionName.Equals(".org")) { if (line.LabelName.Equals("*")) { Assembler.Log.LogEntry(line, line.Label, "Program Counter symbol is redundant for \".org\" directive.", false); } Assembler.Output.SetPC((int)Evaluator.Evaluate(line.Operand, short.MinValue, ushort.MaxValue)); } else if (Reserved.IsOneOf("Pseudo", line.InstructionName)) { if (line.InstructionName.Equals(".pseudopc") || line.InstructionName.Equals(".relocate")) { Assembler.Output.SetLogicalPC((int)Evaluator.Evaluate(line.Operand.Children, short.MinValue, ushort.MaxValue)); } else { Assembler.Output.SynchPC(); } } if (Reserved.IsOneOf("Pseudo", line.InstructionName)) { return($".{Assembler.Output.LogicalPC,-8:x4}"); } if (!line.LabelName.Equals("*") && !Assembler.PassNeeded) { string symbol; if (line.InstructionName.Equals(".let")) { symbol = line.Operand.Children[0].Children[0].Name; } else { symbol = line.LabelName; } if (Assembler.SymbolManager.SymbolIsScalar(symbol)) { return(string.Format("=${0}{1}", ((int)Assembler.SymbolManager.GetNumericValue(symbol)).ToString("x").PadRight(41), line.UnparsedSource)); } } return(string.Empty); }
public void TestDivideByZero() { Evaluator.Evaluate("5/0", s => 0); }
public void TestExtraOperator() { Evaluator.Evaluate("2+5+", s => 0); }
public UniqueRowsConstraint Using(Evaluator evaluator) { this.Engine = evaluator; return(this); }
/// <summary> /// Uses Arithmetic and Boolean laws to simplify expressions. /// </summary> /// <typeparam name="Instruction"></typeparam> /// <param name="instruction"></param> /// <param name="mappings"></param> /// <param name="canonicalizer"></param> /// <returns></returns> internal static Instruction SimplifyBinary <Instruction>(Instruction instruction, ValueMappings <Instruction> mappings, ExpressionCanonicalizer <Instruction> canonicalizer) where Instruction : Microsoft.Cci.Analysis.Instruction, new() { Contract.Requires(instruction != null); Contract.Requires(mappings != null); Contract.Requires(canonicalizer != null); Contract.Ensures(Contract.Result <Instruction>() != null); var operation = instruction.Operation; Contract.Assume(instruction.Operand1 is Instruction); var operand1 = (Instruction)instruction.Operand1; Contract.Assume(instruction.Operand2 is Instruction); var operand2 = (Instruction)instruction.Operand2; IMetadataConstant constantResult = null; var compileTimeConstant1 = mappings.GetCompileTimeConstantValueFor(operand1); var compileTimeConstant2 = mappings.GetCompileTimeConstantValueFor(operand2); if (compileTimeConstant1 != null) { if (compileTimeConstant2 != null) { constantResult = Evaluator.Evaluate(instruction.Operation, compileTimeConstant1, compileTimeConstant2); } else { constantResult = Evaluator.Evaluate(instruction.Operation, compileTimeConstant1, operand2, mappings); } } else if (compileTimeConstant2 != null) { constantResult = Evaluator.Evaluate(instruction.Operation, operand1, compileTimeConstant2, mappings); } else { constantResult = Evaluator.Evaluate(instruction.Operation, operand1, operand2, mappings); } if (constantResult != null) { return(canonicalizer.GetAsCanonicalizedLoadConstant(constantResult, instruction)); } //If we get here, the instruction does not simplify to a constant, but it could still simplify to a simpler expression. bool operand1IsZero = compileTimeConstant1 != null && MetadataExpressionHelper.IsIntegralZero(compileTimeConstant1); bool operand1IsOne = compileTimeConstant1 != null && (operand1IsZero ? false : MetadataExpressionHelper.IsIntegralOne(compileTimeConstant1)); bool operand1IsMinusOne = compileTimeConstant1 != null && ((operand1IsZero || operand1IsOne) ? false : MetadataExpressionHelper.IsIntegralMinusOne(compileTimeConstant1)); bool operand2IsZero = compileTimeConstant2 != null && MetadataExpressionHelper.IsIntegralZero(compileTimeConstant2); bool operand2IsOne = compileTimeConstant2 != null && (operand1IsZero ? false : MetadataExpressionHelper.IsIntegralOne(compileTimeConstant2)); bool operand2IsMinusOne = compileTimeConstant2 != null && ((operand2IsZero || operand2IsOne) ? false : MetadataExpressionHelper.IsIntegralMinusOne(compileTimeConstant2)); operand1 = Simplify(operand1, mappings, canonicalizer); operand2 = Simplify(operand2, mappings, canonicalizer); switch (operation.OperationCode) { case OperationCode.Add: case OperationCode.Add_Ovf: case OperationCode.Add_Ovf_Un: if (operand1IsZero) { return(operand2); } if (operand2IsZero) { return(operand1); } //TODO: factor out common mults/divs/etc (subject to overflow checks). break; case OperationCode.And: if (operand1IsZero) { return(operand1); } if (operand2IsZero) { return(operand2); } if (operand1IsMinusOne) { return(operand2); } if (operand2IsMinusOne) { return(operand1); } if (operand1.Operation.OperationCode == OperationCode.Not && operand2.Operation.OperationCode == OperationCode.Not) { var opnd11 = operand1.Operand1 as Instruction; var opnd21 = operand2.Operand1 as Instruction; Contract.Assume(opnd11 != null && opnd21 != null); var or = new Operation() { OperationCode = OperationCode.Or, Location = operation.Location, Offset = operation.Offset }; var orInst = new Instruction() { Operation = or, Operand1 = opnd11, Operand2 = opnd21, Type = instruction.Type }; var not = new Operation { OperationCode = OperationCode.Not, Location = operation.Location, Offset = operation.Offset }; return(new Instruction() { Operation = not, Operand1 = orInst, Type = instruction.Type }); } break; case OperationCode.Ceq: //If one of the operands is const 0 and the other is a boolean expression, invert the boolean expression if (operand2IsZero && operand1.Type.TypeCode == PrimitiveTypeCode.Boolean) { var not = new Operation() { Location = instruction.Operation.Location, Offset = instruction.Operation.Offset, OperationCode = OperationCode.Not }; instruction = new Instruction() { Operation = not, Operand1 = operand1, Type = instruction.Type }; return(SimplifyUnary(instruction, mappings, canonicalizer)); } else if (operand1IsZero && operand2.Type.TypeCode == PrimitiveTypeCode.Boolean) { var not = new Operation() { Location = instruction.Operation.Location, Offset = instruction.Operation.Offset, OperationCode = OperationCode.Not }; instruction = new Instruction() { Operation = not, Operand1 = operand2, Type = instruction.Type }; return(SimplifyUnary(instruction, mappings, canonicalizer)); } else { operation = new Operation() { Location = instruction.Operation.Location, Offset = instruction.Operation.Offset, OperationCode = OperationCode.Beq }; } break; case OperationCode.Cgt: operation = new Operation() { Location = instruction.Operation.Location, Offset = instruction.Operation.Offset, OperationCode = OperationCode.Bgt }; break; case OperationCode.Cgt_Un: operation = new Operation() { Location = instruction.Operation.Location, Offset = instruction.Operation.Offset, OperationCode = OperationCode.Bgt_Un }; break; case OperationCode.Clt: operation = new Operation() { Location = instruction.Operation.Location, Offset = instruction.Operation.Offset, OperationCode = OperationCode.Blt }; break; case OperationCode.Clt_Un: operation = new Operation() { Location = instruction.Operation.Location, Offset = instruction.Operation.Offset, OperationCode = OperationCode.Blt_Un }; break; case OperationCode.Div: case OperationCode.Div_Un: if (operand2IsOne) { return(operand1); } break; case OperationCode.Mul: case OperationCode.Mul_Ovf: case OperationCode.Mul_Ovf_Un: if (operand1IsOne) { return(operand2); } if (operand2IsOne) { return(operand1); } break; case OperationCode.Or: if (operand1IsZero) { return(operand2); } if (operand2IsZero) { return(operand1); } if (operand1.Operation.OperationCode == OperationCode.Not && operand2.Operation.OperationCode == OperationCode.Not) { var opnd11 = operand1.Operand1 as Instruction; var opnd21 = operand2.Operand1 as Instruction; Contract.Assume(opnd11 != null && opnd21 != null); var and = new Operation() { OperationCode = OperationCode.And, Location = operation.Location, Offset = operation.Offset }; var andInst = new Instruction() { Operation = and, Operand1 = opnd11, Operand2 = opnd21, Type = instruction.Type }; var not = new Operation { OperationCode = OperationCode.Not, Location = operation.Location, Offset = operation.Offset }; return(new Instruction() { Operation = not, Operand1 = andInst, Type = instruction.Type }); } if (operand1.Operand1 == operand2.Operand1 && operand1.Operand2 == operand2.Operand2 && operand1.Operation.OperationCode != operand2.Operation.OperationCode && operand2.Operand1 != null && operand1.Operation.OperationCode == GetInverse(operand2.Operation.OperationCode, operand2.Operand1.Type.TypeCode == PrimitiveTypeCode.Float32 || operand2.Operand1.Type.TypeCode == PrimitiveTypeCode.Float64)) { return(canonicalizer.GetAsCanonicalizedLoadConstant(new MetadataConstant() { Value = true, Type = instruction.Type }, instruction)); } break; case OperationCode.Rem: case OperationCode.Rem_Un: break; case OperationCode.Shl: case OperationCode.Shr: case OperationCode.Shr_Un: if (operand2IsZero) { return(operand1); } break; case OperationCode.Sub: case OperationCode.Sub_Ovf: case OperationCode.Sub_Ovf_Un: if (operand2IsZero) { return(operand1); } break; case OperationCode.Xor: break; case OperationCode.Beq: case OperationCode.Beq_S: if (operand1IsZero && operand2.Type.TypeCode == PrimitiveTypeCode.Boolean) { var operand2inv = TryToGetSimplerLogicalInverse(operand2); if (operand2inv != null) { return(operand2inv); } } else if (operand2IsZero && operand1.Type.TypeCode == PrimitiveTypeCode.Boolean) { var operand1inv = TryToGetSimplerLogicalInverse(operand1); if (operand1inv != null) { return(operand1inv); } } goto case OperationCode.Bge_S; case OperationCode.Bne_Un: case OperationCode.Bne_Un_S: if (operand1IsZero && operand2.Type.TypeCode == PrimitiveTypeCode.Boolean) { return(operand2); } if (operand2IsZero && operand1.Type.TypeCode == PrimitiveTypeCode.Boolean) { return(operand1); } goto case OperationCode.Bge_S; case OperationCode.Bge_S: case OperationCode.Bge_Un_S: case OperationCode.Bgt_S: case OperationCode.Bgt_Un_S: case OperationCode.Ble_S: case OperationCode.Ble_Un_S: case OperationCode.Blt_S: case OperationCode.Blt_Un_S: operation = new Operation() { Location = operation.Location, Offset = operation.Offset, OperationCode = LongVersionOf(operation.OperationCode), Value = operation.Value }; break; } if (operation != instruction.Operation || operand1 != instruction.Operand1 || operand2 != instruction.Operand2) { return new Instruction() { Operation = operation, Operand1 = operand1, Operand2 = operand2, Type = instruction.Type } } ; return(instruction); }
private static void ExampleLevels() { Utilities.PrintExampleBanner("Example: Levels"); /* * In this examples we describe the concept of `levels' in BFV and CKKS and the * related objects that represent them in Microsoft SEAL. * * In Microsoft SEAL a set of encryption parameters (excluding the random number * generator) is identified uniquely by a 256-bit hash of the parameters. This * hash is called the `ParmsId' and can be easily accessed and printed at any * time. The hash will change as soon as any of the parameters is changed. * * When a SEALContext is created from a given EncryptionParameters instance, * Microsoft SEAL automatically creates a so-called `modulus switching chain', * which is a chain of other encryption parameters derived from the original set. * The parameters in the modulus switching chain are the same as the original * parameters with the exception that size of the coefficient modulus is * decreasing going down the chain. More precisely, each parameter set in the * chain attempts to remove the last coefficient modulus prime from the * previous set; this continues until the parameter set is no longer valid * (e.g., PlainModulus is larger than the remaining CoeffModulus). It is easy * to walk through the chain and access all the parameter sets. Additionally, * each parameter set in the chain has a `chain index' that indicates its * position in the chain so that the last set has index 0. We say that a set * of encryption parameters, or an object carrying those encryption parameters, * is at a higher level in the chain than another set of parameters if its the * chain index is bigger, i.e., it is earlier in the chain. * * Each set of parameters in the chain involves unique pre-computations performed * when the SEALContext is created, and stored in a SEALContext.ContextData * object. The chain is basically a linked list of SEALContext.ContextData * objects, and can easily be accessed through the SEALContext at any time. Each * node can be identified by the ParmsId of its specific encryption parameters * (PolyModulusDegree remains the same but CoeffModulus varies). */ EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV); ulong polyModulusDegree = 8192; parms.PolyModulusDegree = polyModulusDegree; /* * In this example we use a custom CoeffModulus, consisting of 5 primes of * sizes 50, 30, 30, 50, and 50 bits. Note that this is still OK according to * the explanation in `1_BFV_Basics.cs'. Indeed, * * CoeffModulus.MaxBitCount(polyModulusDegree) * * returns 218 (less than 50+30+30+50+50=210). * * Due to the modulus switching chain, the order of the 5 primes is significant. * The last prime has a special meaning and we call it the `special prime'. Thus, * the first parameter set in the modulus switching chain is the only one that * involves the special prime. All key objects, such as SecretKey, are created * at this highest level. All data objects, such as Ciphertext, can be only at * lower levels. The special modulus should be as large as the largest of the * other primes in the CoeffModulus, although this is not a strict requirement. * * special prime +---------+ | | v | CoeffModulus: { 50, 30, 30, 50, 50 } +---+ Level 4 (all keys; `key level') | | | CoeffModulus: { 50, 30, 30, 50 } +---+ Level 3 (highest `data level') | | | CoeffModulus: { 50, 30, 30 } +---+ Level 2 | | | CoeffModulus: { 50, 30 } +---+ Level 1 | | | CoeffModulus: { 50 } +---+ Level 0 (lowest level) */ parms.CoeffModulus = CoeffModulus.Create( polyModulusDegree, new int[] { 50, 30, 30, 50, 50 }); /* * In this example the PlainModulus does not play much of a role; we choose * some reasonable value. */ parms.PlainModulus = new SmallModulus(1 << 20); SEALContext context = new SEALContext(parms); Utilities.PrintParameters(context); /* * There are convenience method for accessing the SEALContext.ContextData for * some of the most important levels: * * SEALContext.KeyContextData: access to key level ContextData * SEALContext.FirstContextData: access to highest data level ContextData * SEALContext.LastContextData: access to lowest level ContextData * * We iterate over the chain and print the ParmsId for each set of parameters. */ Console.WriteLine(); Utilities.PrintLine(); Console.WriteLine("Print the modulus switching chain."); /* * First print the key level parameter information. */ SEALContext.ContextData contextData = context.KeyContextData; Console.WriteLine("----> Level (chain index): {0} ...... KeyContextData", contextData.ChainIndex); Console.WriteLine($" ParmsId: {contextData.ParmsId}"); Console.Write(" CoeffModulus primes: "); foreach (SmallModulus prime in contextData.Parms.CoeffModulus) { Console.Write($"{Utilities.ULongToString(prime.Value)} "); } Console.WriteLine(); Console.WriteLine("\\"); Console.Write(" \\--> "); /* * Next iterate over the remaining (data) levels. */ contextData = context.FirstContextData; while (null != contextData) { Console.Write($"Level (chain index): {contextData.ChainIndex}"); if (contextData.ParmsId.Equals(context.FirstParmsId)) { Console.WriteLine(" ...... FirstContextData"); } else if (contextData.ParmsId.Equals(context.LastParmsId)) { Console.WriteLine(" ...... LastContextData"); } else { Console.WriteLine(); } Console.WriteLine($" ParmsId: {contextData.ParmsId}"); Console.Write(" CoeffModulus primes: "); foreach (SmallModulus prime in contextData.Parms.CoeffModulus) { Console.Write($"{Utilities.ULongToString(prime.Value)} "); } Console.WriteLine(); Console.WriteLine("\\"); Console.Write(" \\--> "); /* * Step forward in the chain. */ contextData = contextData.NextContextData; } Console.WriteLine("End of chain reached"); Console.WriteLine(); /* * We create some keys and check that indeed they appear at the highest level. */ KeyGenerator keygen = new KeyGenerator(context); PublicKey publicKey = keygen.PublicKey; SecretKey secretKey = keygen.SecretKey; RelinKeys relinKeys = keygen.RelinKeys(); GaloisKeys galoisKeys = keygen.GaloisKeys(); Utilities.PrintLine(); Console.WriteLine("Print the parameter IDs of generated elements."); Console.WriteLine($" + publicKey: {publicKey.ParmsId}"); Console.WriteLine($" + secretKey: {secretKey.ParmsId}"); Console.WriteLine($" + relinKeys: {relinKeys.ParmsId}"); Console.WriteLine($" + galoisKeys: {galoisKeys.ParmsId}"); Encryptor encryptor = new Encryptor(context, publicKey); Evaluator evaluator = new Evaluator(context); Decryptor decryptor = new Decryptor(context, secretKey); /* * In the BFV scheme plaintexts do not carry a ParmsId, but ciphertexts do. Note * how the freshly encrypted ciphertext is at the highest data level. */ Plaintext plain = new Plaintext("1x^3 + 2x^2 + 3x^1 + 4"); Ciphertext encrypted = new Ciphertext(); encryptor.Encrypt(plain, encrypted); Console.WriteLine($" + plain: {plain.ParmsId} (not set in BFV)"); Console.WriteLine($" + encrypted: {encrypted.ParmsId}"); Console.WriteLine(); /* * `Modulus switching' is a technique of changing the ciphertext parameters down * in the chain. The function Evaluator.ModSwitchToNext always switches to the * next level down the chain, whereas Evaluator.ModSwitchTo switches to a parameter * set down the chain corresponding to a given ParmsId. However, it is impossible * to switch up in the chain. */ Utilities.PrintLine(); Console.WriteLine("Perform modulus switching on encrypted and print."); contextData = context.FirstContextData; Console.Write("----> "); while (null != contextData.NextContextData) { Console.WriteLine($"Level (chain index): {contextData.ChainIndex}"); Console.WriteLine($" ParmsId of encrypted: {contextData.ParmsId}"); Console.WriteLine(" Noise budget at this level: {0} bits", decryptor.InvariantNoiseBudget(encrypted)); Console.WriteLine("\\"); Console.Write(" \\--> "); evaluator.ModSwitchToNextInplace(encrypted); contextData = contextData.NextContextData; } Console.WriteLine($"Level (chain index): {contextData.ChainIndex}"); Console.WriteLine($" ParmsId of encrypted: {contextData.ParmsId}"); Console.WriteLine(" Noise budget at this level: {0} bits", decryptor.InvariantNoiseBudget(encrypted)); Console.WriteLine("\\"); Console.Write(" \\--> "); Console.WriteLine("End of chain reached"); Console.WriteLine(); /* * At this point it is hard to see any benefit in doing this: we lost a huge * amount of noise budget (i.e., computational power) at each switch and seemed * to get nothing in return. Decryption still works. */ Utilities.PrintLine(); Console.WriteLine("Decrypt still works after modulus switching."); decryptor.Decrypt(encrypted, plain); Console.WriteLine($" + Decryption of encrypted: {plain} ...... Correct."); Console.WriteLine(); /* * However, there is a hidden benefit: the size of the ciphertext depends * linearly on the number of primes in the coefficient modulus. Thus, if there * is no need or intention to perform any further computations on a given * ciphertext, we might as well switch it down to the smallest (last) set of * parameters in the chain before sending it back to the secret key holder for * decryption. * * Also the lost noise budget is actually not as issue at all, if we do things * right, as we will see below. * * First we recreate the original ciphertext and perform some computations. */ Console.WriteLine("Computation is more efficient with modulus switching."); Utilities.PrintLine(); Console.WriteLine("Compute the fourth power."); encryptor.Encrypt(plain, encrypted); Console.WriteLine(" + Noise budget before squaring: {0} bits", decryptor.InvariantNoiseBudget(encrypted)); evaluator.SquareInplace(encrypted); evaluator.RelinearizeInplace(encrypted, relinKeys); Console.WriteLine(" + Noise budget after squaring: {0} bits", decryptor.InvariantNoiseBudget(encrypted)); /* * Surprisingly, in this case modulus switching has no effect at all on the * noise budget. */ evaluator.ModSwitchToNextInplace(encrypted); Console.WriteLine(" + Noise budget after modulus switching: {0} bits", decryptor.InvariantNoiseBudget(encrypted)); /* * This means that there is no harm at all in dropping some of the coefficient * modulus after doing enough computations. In some cases one might want to * switch to a lower level slightly earlier, actually sacrificing some of the * noise budget in the process, to gain computational performance from having * smaller parameters. We see from the print-out that the next modulus switch * should be done ideally when the noise budget is down to around 81 bits. */ evaluator.SquareInplace(encrypted); evaluator.RelinearizeInplace(encrypted, relinKeys); Console.WriteLine(" + Noise budget after squaring: {0} bits", decryptor.InvariantNoiseBudget(encrypted)); evaluator.ModSwitchToNextInplace(encrypted); Console.WriteLine(" + Noise budget after modulus switching: {0} bits", decryptor.InvariantNoiseBudget(encrypted)); /* * At this point the ciphertext still decrypts correctly, has very small size, * and the computation was as efficient as possible. Note that the decryptor * can be used to decrypt a ciphertext at any level in the modulus switching * chain. */ decryptor.Decrypt(encrypted, plain); Console.WriteLine(" + Decryption of fourth power (hexadecimal) ...... Correct."); Console.WriteLine($" {plain}"); Console.WriteLine(); /* * In BFV modulus switching is not necessary and in some cases the user might * not want to create the modulus switching chain, except for the highest two * levels. This can be done by passing a bool `false' to SEALContext constructor. */ context = new SEALContext(parms, expandModChain: false); /* * We can check that indeed the modulus switching chain has been created only * for the highest two levels (key level and highest data level). The following * loop should execute only once. */ Console.WriteLine("Optionally disable modulus switching chain expansion."); Utilities.PrintLine(); Console.WriteLine("Print the modulus switching chain."); Console.Write("----> "); for (contextData = context.KeyContextData; null != contextData; contextData = contextData.NextContextData) { Console.WriteLine($"Level (chain index): {contextData.ChainIndex}"); Console.WriteLine($" ParmsId of encrypted: {contextData.ParmsId}"); Console.Write(" CoeffModulus primes: "); foreach (SmallModulus prime in contextData.Parms.CoeffModulus) { Console.Write($"{Utilities.ULongToString(prime.Value)} "); } Console.WriteLine(); Console.WriteLine("\\"); Console.Write(" \\--> "); } Console.WriteLine("End of chain reached"); Console.WriteLine(); /* * It is very important to understand how this example works since in the CKKS * scheme modulus switching has a much more fundamental purpose and the next * examples will be difficult to understand unless these basic properties are * totally clear. */ }
public void TestInvalidVariable() { Evaluator.Evaluate("xx", s => 0); }
/// <summary> /// /// </summary> /// <typeparam name="Instruction"></typeparam> /// <param name="instruction"></param> /// <param name="mappings"></param> /// <param name="canonicalizer"></param> /// <returns></returns> internal static Instruction SimplifyUnary <Instruction>(Instruction instruction, ValueMappings <Instruction> mappings, ExpressionCanonicalizer <Instruction> canonicalizer) where Instruction : Microsoft.Cci.Analysis.Instruction, new() { Contract.Requires(instruction != null); Contract.Requires(mappings != null); Contract.Requires(canonicalizer != null); Contract.Ensures(Contract.Result <Instruction>() != null); var operation = instruction.Operation; Contract.Assume(instruction.Operand1 is Instruction); var operand1 = (Instruction)instruction.Operand1; var operand = Simplify(operand1, mappings, canonicalizer); var compileTimeConstant = mappings.GetCompileTimeConstantValueFor(operand); if (compileTimeConstant != null) { var constantResult = Evaluator.Evaluate(instruction.Operation, compileTimeConstant); if (constantResult != null) { return(canonicalizer.GetAsCanonicalizedLoadConstant(constantResult, instruction)); } } switch (operation.OperationCode) { case OperationCode.Neg: if (operand.Operation.OperationCode == OperationCode.Neg) { Contract.Assume(operand.Operand1 is Instruction); return((Instruction)operand.Operand1); } //TODO: if the operand is a binary operation with arithmetic operands where one of them is a Neg //distribute the neg over the binary operation, if doing so is safe w.r.t. overflow. break; case OperationCode.Not: var simplerInverse = TryToGetSimplerLogicalInverse(operand); if (simplerInverse != null) { return(simplerInverse); } if (operand != operand1) { var operation1 = operand1.Operation; switch (operation1.OperationCode) { case OperationCode.Bne_Un: case OperationCode.Bne_Un_S: case OperationCode.Beq: case OperationCode.Beq_S: OperationCode newOpcode = GetInverse(operation1.OperationCode, operand1.Type.TypeCode == PrimitiveTypeCode.Float32 || operand1.Type.TypeCode == PrimitiveTypeCode.Float64); return(new Instruction() { Operation = new Operation() { OperationCode = newOpcode, Offset = operation.Offset, Location = operation.Location }, Operand1 = operand1.Operand1, Operand2 = operand1.Operand2, Type = instruction.Type }); } } return(new Instruction() { Operation = operation, Operand1 = operand, Type = instruction.Type }); } return(instruction); }
public void TestComplexAndParentheses() { Assert.AreEqual(194, Evaluator.Evaluate("2+3*5+(3+4*8)*5+2", s => 0)); }
public void TestEmpty() { Evaluator.Evaluate("", s => 0); }
public void TestComplexMultiVar() { Assert.AreEqual(6, Evaluator.Evaluate("y1*3-8/2+4*(8-9*2)/14*x7", s => (s == "x7") ? 1 : 4)); }