private static UnaryExpression ToUnaryExpression(Expression value, UnaryOp operation) { return(new UnaryExpression( value, operation )); }
public UnaryOpNode(Token tok, UnaryOp op, ExprNode arg) : base(tok) { Contracts.AssertValue(arg); Arg = arg; Op = op; }
/// <summary> /// Collects benchmark stats for a specified unary operator /// </summary> /// <param name="f">The unary operator</param> /// <param name="min">The minimum operand value</param> /// <param name="max">The maximum operand value</param> /// <param name="oplabel">The name of the operation, excluding type info</param> /// <typeparam name="K">The primal operand type</typeparam> protected OpTime BenchmarkOp <K>(UnaryOp <K> f, string oplabel, K min, K max) where K : unmanaged { var buffer = new K[SampleSize]; var sw = stopwatch(false); for (var round = 0; round < RoundCount; round++) { for (var cycle = 0; cycle < CycleCount; cycle++) { Random.StreamTo((min, max), buffer.Length, ref buffer[0]); sw.Start(); for (var k = 0; k < buffer.Length; k++) { f(buffer[k]); } sw.Stop(); } } var opname = oplabel + angled(type <K>().DisplayName()); OpTime timing = (SampleSize * CycleCount * RoundCount, sw, opname); Collect(timing); return(timing); }
internal static UnaryOp CreateUnaryOp01() { Token type = Token.ArithmeticFirst; UnaryOp unaryOp = UnaryOp.CreateOp(type); return(unaryOp); }
internal static Expression CreateExpression02() { Token type = Token.BooleanNot; Expression expression = UnaryOp.CreateOp(type); return(expression); }
internal static UnaryOp CreateUnaryOp03() { Token type = Token.BitwiseNot; UnaryOp unaryOp = UnaryOp.CreateOp(type); return(unaryOp); }
internal static UnaryOp CreateUnaryOp02() { Token type = Token.BooleanNot; UnaryOp unaryOp = UnaryOp.CreateOp(type); return(unaryOp); }
public void UnexpectedTypeInConstructor() { Assert.Throws <AstException>(() => { var unused = new UnaryOp(UnaryOp.OpType.Conversion, null); }); }
public ExprUnary(Ctx ctx, UnaryOp op, TypeReference type, Expr expr) : base(ctx) { this.Op = op; this.type = type; this.Expr = expr; }
// 计算一元运算 private object applyUnaryOperator(UnaryOp Operator, object Right, int LineNumber) { switch (Operator) { case UnaryOp.Negative: if (Right is double) { return(-(double)Right); } else if (Right is Vector2) { Vector2 tOrg = (Vector2)Right; tOrg.x = -tOrg.x; tOrg.y = -tOrg.y; return(tOrg); } else { throw new RuntimeException(LineNumber, String.Format("can't perform negative operator on type {0}.", Right.GetType().ToString())); } default: throw new RuntimeException(LineNumber, "internal error."); } }
UnaryExpression ParseUnaryExpr(ParseTreeNode node) { if (node.Term.Name == "UnaryExpr") { IExpression expr = ParseExpression(node.ChildNodes[1]); var opNode = node.ChildNodes[0].ChildNodes[0]; UnaryOp op = UnaryOp.Invert; switch (opNode.Token.ValueString) { case "not": op = UnaryOp.Negate; break; case "-": op = UnaryOp.Invert; break; case "#": op = UnaryOp.Length; break; } return(new UnaryExpression() { Expression = expr, Operation = op }); } throw new Exception("Invalid UnaryExpr node"); }
private IAST factor() { switch (tokenType()) { case Dictionary.LexemeType.sub: case Dictionary.LexemeType.add: Token t = lexer.token; lexer.consume(); UnaryOp node0 = new UnaryOp(t, factor()); return(node0); case Dictionary.LexemeType.number: Num node1 = new Num(lexer.token); lexer.consume(); return(node1); case Dictionary.LexemeType.ident: Var node2 = new Var(lexer.token.getValue()); lexer.consume(); return(node2); case Dictionary.LexemeType.lbracket: consumeToken(Dictionary.LexemeType.lbracket, Dictionary.lbracket_exp); dynamic node3 = expression(); consumeToken(Dictionary.LexemeType.rbracket, Dictionary.rbracket_exp); return(node3); default: throw new Exception(Dictionary.factor_exp + pos()); } }
/// <summary> /// Instantiate a new instance of the EvalNodeUnaryOp node. /// </summary> /// <param name="operation">Specifies the unary operation to represent.</param> /// <param name="child">Specifies the child node.</param> /// <param name="language">Language used for evaluation.</param> public EvalNodeUnaryOp(UnaryOp operation, EvalNode child, Language language) { _operation = operation; _language = language; Append(child); }
public UnaryOpDelegationStrategy(UnaryOp op, TexlFunction function) : base(function) { Contracts.AssertValue(function); _unaryOp = op; _function = function; }
private void AddNext(UnaryOp op) { if (_prevElement is Variable || IsCloseBracket(_prevElement)) { throw new LogicException("Before unary operation can not be variable or close bracket."); } _operationsStack.Push(op); }
void ParseUnaryOp() { Token token = this.PeekToken(); this.CheckStartableToken(token); UnaryOp uo = UnaryOp.CreateOp(_current.token); _tree.AddOperator(uo); }
/// <summary> /// Configures constant values that will not change during the lifetime of the class. /// </summary> /// <remarks> /// This method should be called once only after the class is instantiated. In future, it will likely become /// the class constructor. /// </remarks> public void Reset() { // Create array for 'firstCoin_uses' backwards messages. this.firstCoin_uses_B = new Bernoulli[0]; this.vBernoulli0 = new Bernoulli(0.5); this.firstCoin_F = ArrayHelper.MakeUniform <Bernoulli>(vBernoulli0); // Message to 'firstCoin' from Random factor this.firstCoin_F = UnaryOp <bool> .RandomAverageConditional <Bernoulli>(this.vBernoulli0); }
/// <summary> /// Configures constant values that will not change during the lifetime of the class. /// </summary> /// <remarks> /// This method should be called once only after the class is instantiated. In future, it will likely become /// the class constructor. /// </remarks> public void Reset() { // Create array for 'vint0_uses' backwards messages. this.vint0_uses_B = new Discrete[0]; this.vint0_F = ArrayHelper.MakeUniform <Discrete>(new Discrete(0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647, 0.0588235294117647)); this.vDiscrete0 = new Discrete(0.5, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // Message to 'vint0' from Random factor this.vint0_F = UnaryOp <int> .RandomAverageConditional <Discrete>(this.vDiscrete0); }
public UnaryExpr(UnaryOp op, Expr arg) { if (op == UnaryOp.Undefined) { throw new ArgumentException("Undefined operand.", nameof(op)); } this.Op = op; this.Key = Parser.DescriptionAttr(op); this.Argument = arg; }
public UnaryOpNode(ref int idNext, Token primaryToken, SourceList sourceList, UnaryOp op, TexlNode child) : base(ref idNext, primaryToken, sourceList) { Contracts.AssertValue(child); Child = child; Child.Parent = this; Op = op; _depth = child.Depth + 1; MinChildID = Math.Min(child.MinChildID, MinChildID); }
public object Visit_UnaryOp(UnaryOp node) { TreeViewItem item = new TreeViewItem(); item.IsExpanded = true; item.Header = "UnaryOp " + node.Token.Value; item.Items.Add(node.Expression.Visit(this)); return(item); }
static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****\n"); const int operand1 = 5; const int operand2 = 12; Console.WriteLine($"operand1 is {operand1}, operand2 is {operand2}"); // create operators classes to be used to assign to delegates // note the methods of each class are unary or binary SimpleMathOperators simpleMathOps = new SimpleMathOperators(); OtherMathOperators anotherMathOp = new OtherMathOperators(); // Create a BinaryOp delegate object that // "points to" SimpleMathOperators.Add(). BinaryOp addTheseTogether = new BinaryOp(simpleMathOps.Add); DisplayDelegateInfo(addTheseTogether); // Invoke Add() method indirectly using delegate object. Console.WriteLine($"Add: {operand1} and {operand2} is {addTheseTogether(operand1, operand2)}"); // now do the same for each unary or binary method in the classes UnaryOp squareOf = new UnaryOp(simpleMathOps.SquareNumber); DisplayDelegateInfo(squareOf); Console.WriteLine($"SquareNumber: {operand1} squared is {squareOf(operand1)}"); BinaryOp differenceOfSquaresOf = new BinaryOp(anotherMathOp.DifferenceBetweenSquares); DisplayDelegateInfo(differenceOfSquaresOf); Console.WriteLine($"DifferenceBetweenSquares: {operand1} squared minus {operand2} squared is {differenceOfSquaresOf(operand1, operand2)}"); UnaryOp factorialOf = new UnaryOp(anotherMathOp.Factorial); DisplayDelegateInfo(factorialOf); Console.WriteLine($"Factorial: factorial of {operand1} is {factorialOf(operand1)}"); UnaryOp seriesSum = new UnaryOp(anotherMathOp.SumOfSeries); DisplayDelegateInfo(seriesSum); Console.WriteLine($"SeriesSum: sum of series of {operand1} is {seriesSum(operand1)}"); Console.ReadLine(); }
public virtual bool IsUnaryOpSupportedByTable(UnaryOp op) { if (!IsUnaryOpInDelegationSupported(op)) { return(false); } Contracts.Assert(DelegationCapability.UnaryOpToDelegationCapabilityMap.ContainsKey(op)); return(IsDelegationSupportedByTable(DelegationCapability.UnaryOpToDelegationCapabilityMap[op].Capabilities)); }
string Eval_UnaryOp(UnaryOp node) { switch (node.oper.type) { case TYPE.PLUS: return(Interpret(node.right)); case TYPE.MINUS: return((-1 * int.Parse(Interpret(node.right))).ToString()); } return(""); }
public void TestCreateUnaryOp02() { UnaryOp unaryOp = CreateUnaryOp02(); unaryOp.ToString(); Assert.IsNotNull(unaryOp); #region Record State ValueRecorder recorder = new ValueRecorder(); recorder.Record((OperatorPriority)unaryOp.Priority); recorder.FinishRecording(); #endregion }
public virtual bool IsUnaryOpInDelegationSupportedByColumn(UnaryOp op, DPath columnPath) { Contracts.AssertValid(columnPath); if (!IsUnaryOpInDelegationSupported(op)) { return(false); } Contracts.Assert(DelegationCapability.UnaryOpToDelegationCapabilityMap.ContainsKey(op)); return(IsDelegationSupportedByColumn(columnPath, DelegationCapability.UnaryOpToDelegationCapabilityMap[op])); }
internal static bool FindOperation(string name, out UnaryOp op) { foreach (var item in Enum.GetValues(typeof(UnaryOp)) as UnaryOp[]) { if (DescriptionAttr(item).Equals(name)) { op = item; return(true); } } op = UnaryOp.Undefined; return(false); }
public object Visit_UnaryOp(UnaryOp node) { if (node.Token.TokenType == TokenType.PLUS) { return(+(double)node.Expression.Visit(this)); } else if (node.Token.TokenType == TokenType.MINUS) { return(-(double)node.Expression.Visit(this)); } throw new Exception("Unknown UnaryOP TokenType"); }
protected void VerifyOp <K>(UnaryOp <K> subject, UnaryOp <K> baseline, bool nonzero = false, [CallerMemberName] string caller = null, [CallerFilePath] string file = null, [CallerLineNumber] int?line = null) where K : struct { var kind = PrimalKinds.kind <K>(); var src = RandArray <K>(nonzero); var timing = stopwatch(); for (var i = 0; i < src.Length; i++) { Claim.eq(baseline(src[i]), subject(src[i]), caller, file, line); } }
public ExprAtom(Node exprNode) { var firstChild = exprNode.GetChildAt(0); if (firstChild.Id == (int)DefConstants.NOT || firstChild.Id == (int)DefConstants.SUB) { firstChild = exprNode.GetChildAt(1); Op = firstChild.Id == (int)DefConstants.NOT ? UnaryOp.Not : UnaryOp.Inverse; if (firstChild.Id == (int)DefConstants.OPEN_PARENT) { firstChild = exprNode.GetChildAt(2); } } else if (firstChild.Id == (int)DefConstants.OPEN_PARENT) { firstChild = exprNode.GetChildAt(1); } if (firstChild.Id == (int)DefConstants.EXPRESSION) { Content = new Expression(firstChild); } else if (firstChild.Id == (int)DefConstants.SCOPE) { Content = new Scope(firstChild); } else if (firstChild.Id == (int)DefConstants.ATOM) { Content = Atom.FromNode(firstChild); } else { //if (ScriptEngine.ParseDebug) //Debug.LogFormat ("{0} Expr node {1}", ID, exprNode); // Debug.LogFormat ("{0} First child node {1}", ID++, firstChild); if (exprNode.Id == (int)DefConstants.MUL_TERM) { Content = new Expression(exprNode, false); } else if (firstChild.Id == (int)DefConstants.FACTOR) { Content = new Expression(firstChild, false); } else { Content = new Expression(exprNode, false); } } }
internal static expr Convert(Compiler.Ast.Expression expr, expr_context ctx) { expr ast; if (expr is ConstantExpression) ast = Convert((ConstantExpression)expr); else if (expr is NameExpression) ast = new Name((NameExpression)expr, ctx); else if (expr is UnaryExpression) ast = new UnaryOp((UnaryExpression)expr); else if (expr is BinaryExpression) ast = Convert((BinaryExpression)expr); else if (expr is AndExpression) ast = new BoolOp((AndExpression)expr); else if (expr is OrExpression) ast = new BoolOp((OrExpression)expr); else if (expr is CallExpression) ast = new Call((CallExpression)expr); else if (expr is ParenthesisExpression) return Convert(((ParenthesisExpression)expr).Expression); else if (expr is LambdaExpression) ast = new Lambda((LambdaExpression)expr); else if (expr is ListExpression) ast = new List((ListExpression)expr, ctx); else if (expr is TupleExpression) ast = new Tuple((TupleExpression)expr, ctx); else if (expr is DictionaryExpression) ast = new Dict((DictionaryExpression)expr); else if (expr is ListComprehension) ast = new ListComp((ListComprehension)expr); else if (expr is GeneratorExpression) ast = new GeneratorExp((GeneratorExpression)expr); else if (expr is MemberExpression) ast = new Attribute((MemberExpression)expr, ctx); else if (expr is YieldExpression) ast = new Yield((YieldExpression)expr); else if (expr is ConditionalExpression) ast = new IfExp((ConditionalExpression)expr); else if (expr is IndexExpression) ast = new Subscript((IndexExpression)expr, ctx); else if (expr is SliceExpression) ast = new Slice((SliceExpression)expr); else if (expr is BackQuoteExpression) ast = new Repr((BackQuoteExpression)expr); else throw new ArgumentTypeException("Unexpected expression type: " + expr.GetType()); ast.GetSourceLocation(expr); return ast; }
public UnaryExp(Exp left, UnaryOp op) { Debug.Assert(left != null); m_filerange = left.Location; m_left = left; m_op = op; }
private ExprUnary Unary(UnaryOp op, TypeReference type = null) { var e = this.stack.Pop(); return new ExprUnary(this.ctx, op, (type ?? e.Type).FullResolve(this.ctx), e); }
public UnaryExpression(IExpression inner, UnaryOp op) { this.inner = inner; this.op = op; }
/// <summary> /// This routine will actually execute an operation and return its value /// </summary> /// <param name="op">Operator Information</param> /// <param name="v">right operand</param> /// <returns>(op)v</returns> private static object PerformUnaryOp(UnaryOp op, object v) { IExpression tempv = v as IExpression; if (tempv != null) v = tempv.Evaluate(); switch (op.Op) { case "+": return (Convert.ToDouble(v, CultureInfo.CurrentCulture)); case "-": return (-Convert.ToDouble(v, CultureInfo.CurrentCulture)); case "!": return (!Convert.ToBoolean(v, CultureInfo.CurrentCulture)); case "~": return (~Convert.ToUInt64(v, CultureInfo.CurrentCulture)); } throw new ArgumentException("Unary Operator " + op.Op + "not defined."); }
/// <summary> /// This will search the expression for the next token (operand, operator, etc) /// </summary> /// <param name="nIdx">Start Position of Search</param> /// <returns>First character index after token.</returns> //[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private int NextToken(int nIdx) { Match mRet = null; int nRet = nIdx; object val = null; //Check for preceeding white space from last token index Match m = DefinedRegex.WhiteSpace.Match(Expression, nIdx); if (m.Success && m.Index == nIdx) return nIdx + m.Length; //Check Parenthesis m = DefinedRegex.Parenthesis.Match(Expression, nIdx); if (m.Success) mRet = m; //Check Function if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.Function.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) mRet = m; } //Check Variable if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.Variable.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = new Variable(m.Groups["Variable"].Value, _variables); } } //Check Unary Operator if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.UnaryOp.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = new UnaryOp(m.Value); } } //Check Hexadecimal if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.Hexadecimal.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = Convert.ToInt32(m.Value, 16); } } //Check Boolean if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.Boolean.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = bool.Parse(m.Value); } } //Check DateTime if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.DateTime.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = Convert.ToDateTime(m.Groups["DateString"].Value, CultureInfo.CurrentCulture); } } //Check Timespan if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.TimeSpan.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = new TimeSpan( int.Parse("0" + m.Groups["Days"].Value), int.Parse(m.Groups["Hours"].Value), int.Parse(m.Groups["Minutes"].Value), int.Parse("0" + m.Groups["Seconds"].Value), int.Parse("0" + m.Groups["Milliseconds"].Value) ); } } //Check Numeric if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.Numeric.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { while (m.Success && ("" + m.Value == "")) m = m.NextMatch(); if (m.Success) { mRet = m; val = double.Parse(m.Value, CultureInfo.CurrentCulture); } } } if (mRet == null || mRet.Index > nIdx) { //Check String m = DefinedRegex.String.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = m.Groups["String"].Value.Replace("\\\"", "\""); } } //Check Binary Operator if (mRet == null || mRet.Index > nIdx) { m = DefinedRegex.BinaryOp.Match(Expression, nIdx); if (m.Success && (mRet == null || m.Index < mRet.Index)) { mRet = m; val = new BinaryOp(m.Value); } } if (mRet == null) throw new ArgumentException("Invalid expression construction: \"" + Expression + "\"."); if (mRet.Index != nIdx) { throw new ArgumentException( "Invalid token in expression: [" + Expression.Substring(nIdx, mRet.Index - nIdx).Trim() + "]" ); } if (mRet.Value == "(" || mRet.Value.StartsWith("$")) { nRet = mRet.Index + mRet.Length; int nDepth = 1; bool bInQuotes = false; while (nDepth > 0) { if (nRet >= Expression.Length) throw new ArgumentException("Missing " + (bInQuotes ? "\"" : ")") + " in Expression"); if (!bInQuotes && Expression[nRet] == ')') nDepth--; if (!bInQuotes && Expression[nRet] == '(') nDepth++; if (Expression[nRet] == '"' && (nRet == 0 || Expression[nRet - 1] != '\\')) bInQuotes = !bInQuotes; nRet++; } if (mRet.Value == "(") { ExpressionEval expr = new ExpressionEval( Expression.Substring(mRet.Index + 1, nRet - mRet.Index - 2) ); if (this.AdditionalFunctionEventHandler != null) expr.AdditionalFunctionEventHandler += this.AdditionalFunctionEventHandler; expr._variables = this._variables; _expressionlist.Add(expr); } else { FunctionEval func = new FunctionEval( Expression.Substring(mRet.Index, (nRet) - mRet.Index) ); if (this.AdditionalFunctionEventHandler != null) func.AdditionalFunctionEventHandler += this.AdditionalFunctionEventHandler; func._variables = this._variables; _expressionlist.Add(func); } } else { nRet = mRet.Index + mRet.Length; _expressionlist.Add(val); } return nRet; }
public virtual void Visit(UnaryOp<bool, TypedExpression<bool>> node) { }
public virtual void Visit(UnaryOp<int, TypedExpression<int>> node) { }