public StackMachineEntry(OperatorBase policyOperator) { m_policyOperator = policyOperator; m_entryType = EntryType.Operator; m_policyValue = null; m_opCodeType = typeof(T); }
public void PushOperator(OperatorBase op) { if (op.NeedLeftUnit()) { if (op is SeparatorEndOperator) { if (m_RightResultCache == null) { throw new System.Exception("Need Right unit"); } op.SetLeftUnit(m_RightResultCache); //op.DebugText(Owner); OperatorBase preOp = m_CacheOperatorList.Pop(); if (preOp is SeparatorStartOperator) { PushUnit(op.GetOperatorResult()); } else { throw new System.Exception("Need Separator Start Operator"); } } else { IExpressionUnit left = m_LeftResultCaches.Pop(); op.SetLeftUnit(left); } } if (op.NeedRightUnit()) { m_CacheOperatorList.Push(op); } }
private void HandleOperator(int i, OperatorBase assignment) { var binary = assignment as BinaryOperator; var unary = assignment as UnaryOperator; if (unary != null) { var analysis = _pointsOfAnalysis[i]; var variableState = analysis.GetConstVariableState(unary.Left as LocalVariable); if (variableState != null) { unary.Left = variableState; Result = true; } } if (binary != null) { var analysis = _pointsOfAnalysis[i]; var variableState = analysis.GetConstVariableState(binary.Left as LocalVariable); if (variableState != null) { binary.Left = variableState; Result = true; } variableState = analysis.GetConstVariableState(binary.Right as LocalVariable); if (variableState != null) { binary.Right = variableState; Result = true; } } }
private void EvaluateExpression() { var rightOperand = _numberStack.Pop(); var leftOperand = _numberStack.Pop(); var @operator = _operatorStack.Pop(); var result = OperatorBase.Evaluate(leftOperand, rightOperand, @operator); _numberStack.Push(result); }
public void TestExecute_LogicalOr_AssertResults() { OperatorBase equalsOperator = PolicyOperator.FromToken(("=_" + "Boolean_Boolean").GetHashCode()); equalsOperator.Should().NotBeNull(); Assert.True(PolicyOperator <bool> .LOGICAL_OR.Execute(true, true)); Assert.True(PolicyOperator <bool> .LOGICAL_OR.Execute(true, false)); Assert.True(PolicyOperator <bool> .LOGICAL_OR.Execute(false, true)); Assert.False(PolicyOperator <bool> .LOGICAL_OR.Execute(false, false)); }
/// <summary> /// Sets the formula function result to a double /// </summary> /// <param name="value">The value you wish to be the result of the function</param> /// <remarks>Use this method when the result of your function is a double</remarks> public void SetValue(double value) { if (OperatorBase.IsInvalidDouble(value)) { SetError(ErrorValueType.Num); } else { MyOperand = new DoubleOperand(value); } }
public void TestEqualsFindTokenOperators() { OperatorBase equalsOperator = PolicyOperator.FromToken(("=_" + "Boolean_Boolean").GetHashCode()); equalsOperator.Should().NotBeNull(); equalsOperator = PolicyOperator.FromToken(("=_" + "Int32_Int32").GetHashCode()); equalsOperator.Should().NotBeNull(); equalsOperator = PolicyOperator.FromToken(("=_" + "String_String").GetHashCode()); equalsOperator.Should().NotBeNull(); }
/// <summary> /// Adds new operator or function to the operator list. If action was succesfull returns true. /// </summary> /// <param name="newOperator">The new operator.</param> /// <returns></returns> public static bool AddOperator(OperatorBase newOperator) { for (int i = 0; i < Symbols.Count; i++) { if (newOperator.Symbol == Symbols[i].Symbol) { return(false); } } Symbols.Add(newOperator); SortSymbols(); return(true); }
public void TestExecute_NotEquals_Convertparamspecial_AssertResults() { Assert.False(PolicyOperator <Int64, Int64, bool> .NOT_EQUALS.Execute("00F74F1C4FE4E1762E".HexAsLong(), "f74f1c4fe4e1762e".HexAsLong())); Assert.False(PolicyOperator <Int64, String, bool> .NOT_EQUALS.Execute("00F74F1C4FE4E1762E".HexAsLong(), "f74f1c4fe4e1762e")); Assert.True(PolicyOperator <Int64, String, bool> .NOT_EQUALS.Execute("00F74F1C4FE4E17600".HexAsLong(), "f74f1c4fe4e1762e")); Delegate del = PolicyOperator <Int64, String, bool> .NOT_EQUALS.ExecuteRef; Assert.False((bool)del.DynamicInvoke(new object[] { "00F74F1C4FE4E1762E".HexAsLong(), "f74f1c4fe4e1762e" })); Assert.True((bool)del.DynamicInvoke(new object[] { "00F74F1C4FE4E17600".HexAsLong(), "f74f1c4fe4e1762e" })); var tokenHashCode = "!=_Int32_String".GetHashCode(); OperatorBase operatorBase = PolicyOperator.FromToken(tokenHashCode); operatorBase.Should().NotBeNull(); }
/// <summary> /// Replaces existing operator represented by a given string with a given operator. If action was succesfull returns true. /// </summary> /// <param name="oldOperatorSymbol"></param> /// <param name="newOperator"></param> /// <returns></returns> public static bool ReplaceOperator(string oldOperatorSymbol, OperatorBase newOperator) { if (newOperator == null) { return(false); } for (int i = 0; i < Symbols.Count; i++) { if (oldOperatorSymbol == Symbols[i].Symbol) { Symbols[i] = newOperator; SortSymbols(); return(true); } } return(false); }
/// <summary> /// 计算表达式的值 /// </summary> /// <param name="expression">文本表达式</param> /// <returns>计算结果</returns> public static double Calculate(string expression) { // 预处理后缀表达式 List <IOperatorOrOperand> postfix = Expressions.ConvertInfixToPostfix(expression); // 操作数栈 System.Collections.Generic.Stack <double> data = new System.Collections.Generic.Stack <double>(); // 遍历 foreach (IOperatorOrOperand item in postfix) { if (item.IsOperator) { // 运算符 OperatorBase opr = item as OperatorBase; // 从操作数栈中取出操作数 if (data.Count < opr.OperandCount) { throw new InvalidCastException("无效的表达式。缺少运算符或出现多余的操作数。"); } double[] operands = new double[opr.OperandCount]; for (int i = opr.OperandCount - 1; i >= 0; i--) { operands[i] = data.Pop(); } // 计算并将结果压回栈中 data.Push(opr.Calculate(operands)); } else { // 操作数 // 压入操作数栈 data.Push(((OperandInfo)item).Value); } } // 取最后结果 if (data.Count != 1) { throw new InvalidCastException("无效的表达式。缺少运算符或出现多余的操作数。"); } return(data.Pop()); }
public void PushUnit(IExpressionUnit unit) { if (m_CacheOperatorList.Count == 0) { if (!_IsInitialized) { m_Result = unit; _IsInitialized = true; } m_LeftResultCaches.Push(unit); } else { m_RightResultCache = unit; int count = m_CacheOperatorList.Count; for (int i = 0; i < count; i++) { OperatorBase op = m_CacheOperatorList.Pop(); if (op is SeparatorStartOperator) { m_CacheOperatorList.Push(op); m_LeftResultCaches.Push(m_RightResultCache); break; } else { op.SetRightUnit(m_RightResultCache); m_RightResultCache = op.GetOperatorResult(); //op.DebugText(Owner); } if (i == count - 1) { if (!_IsInitialized) { _IsInitialized = true; } m_Result = m_RightResultCache; m_LeftResultCaches.Push(m_RightResultCache); } } } }
// Token: 0x0600007A RID: 122 RVA: 0x00003AE5 File Offset: 0x00001CE5 public override Evaluator BindEvaluator(OperatorBase op, IEvaluationContext context) { if (op is DLPClassificationOperator) { return(new DLPClassificationEvaluator()); } if (op is DLPQuerySecurityOperator) { return(new DLPQuerySecurityEvaluator()); } if (op is DLPQuerySensitiveResultTranslationOperator) { return(new DLPQuerySensitiveResultTranslationEvaluator()); } if (op is DLPQuerySensitiveTypeTranslationOperator) { return(new DLPQuerySensitiveTypeTranslationEvaluator()); } return(null); }
private void Awake() { m_oper = GetComponent <OperatorBase>(); m_inputOperators = new OperatorLink[m_oper.inputCount]; m_outputOperators = new List <OperatorLink>(); m_outputOperatorIdx = new List <int>(); UITable inputUITable = transform.Find("Input/Table").GetComponent <UITable>(); List <Transform> children = inputUITable.GetChildList(); for (int i = children.Count; i < m_oper.inputCount; ++i) { GameObject child = NGUITools.AddChild(inputUITable.gameObject, m_inputUISample); child.SetActive(true); } children = inputUITable.GetChildList(); for (int i = 0; i != children.Count; ++i) { if (i < m_oper.inputCount) { children[i].gameObject.SetActive(true); children[i].gameObject.name = i.ToString(); UIEventListener.Get(children[i].gameObject).onClick = OnClickInputChild; } else { children[i].gameObject.SetActive(false); } } inputUITable.Reposition(); Transform outputNode = transform.Find("Output"); if (outputNode != null) { UIEventListener.Get(outputNode.gameObject).onClick = OnClickOutput; } }
/** * Builds an aggregated {@link PolicyExpression} from a parsed list of tokens. * @param tokens Parsed list of tokens used to build the {@link PolicyExpression}. * @param level Used for keeping track of depth of operations. * @return A {@link PolicyExpression} built from the parsed list of tokens. * @throws PolicyParseException */ protected IPolicyExpression BuildExpression(IEnumerator <TokenTypeAssociation> tokens, bool operandFrame) { if (!tokens.MoveNext()) { return(null); } IList <IPolicyExpression> builtOperandExpressions = new List <IPolicyExpression>(); do { TokenTypeAssociation assos = tokens.Current; switch (assos.GetTokenType()) { case TokenType.START_LEVEL: { IncrementLevel(); IPolicyExpression expression = BuildExpression(tokens); if (operandFrame) { return(expression); } builtOperandExpressions.Add(expression); break; } case TokenType.END_LEVEL: if (GetLevel() == 0) { throw new PolicyGrammarException("To many \")\" tokens. Delete this token"); } if (builtOperandExpressions.Count == 0) { throw new PolicyGrammarException("Group must contain at least one expression."); } DecrementLevel(); return(builtOperandExpressions[0]); case TokenType.OPERATOR_BINARY_EXPRESSION: case TokenType.OPERATOR_UNARY_EXPRESSION: { // regardless if this is a unary or binary expression, then next set of tokens should consist // of a parameter to this operator IPolicyExpression subExpression = BuildExpression(tokens, true); int tokenHashCode = 0; if (subExpression != null) { //TODO Refactor if (assos.GetTokenType() == TokenType.OPERATOR_UNARY_EXPRESSION) { tokenHashCode = (assos.GetToken() + "_" + GetOperandType(subExpression)).GetHashCode(); } if (assos.GetTokenType() == TokenType.OPERATOR_BINARY_EXPRESSION) { string leftOperandType = GetOperandType(builtOperandExpressions.First()); string rightOperandType = GetOperandType(subExpression); tokenHashCode = (assos.GetToken() + "_" + leftOperandType + "_" + rightOperandType).GetHashCode(); } } else //(subExpression == null) { throw new PolicyGrammarException("Missing parameter. Operator must be followed by an expression."); } builtOperandExpressions.Add(subExpression); // get the operator for this token OperatorBase operatorBase = PolicyOperator.FromToken(tokenHashCode); // now add the parameters to the operator if (builtOperandExpressions.Count == 1 && operatorBase is BinaryOperator) { throw new PolicyGrammarException("Missing parameter. Binary operators require two parameters."); } IPolicyExpression operatorExpression = new OperationPolicyExpression(operatorBase, builtOperandExpressions); if (operandFrame) { return(operatorExpression); } builtOperandExpressions = new List <IPolicyExpression>(); builtOperandExpressions.Add(operatorExpression); break; } case TokenType.LITERAL_EXPRESSION: { IPolicyExpression expression = new LiteralPolicyExpression <string>(new PolicyValue <string>(assos.GetToken())); if (operandFrame) { return(expression); // exit this operand frame } builtOperandExpressions.Add(expression); break; } case TokenType.CERTIFICATE_REFERENCE_EXPRESSION: { IPolicyExpression expression = BuildCertificateReferenceField(assos.GetToken()); if (operandFrame) { return(expression); // exit this operand frame } builtOperandExpressions.Add(expression); break; } } } while(tokens.MoveNext()); if (builtOperandExpressions.Count > 1) { throw new PolicyGrammarException("Erroneous expression."); } return(builtOperandExpressions[0]); }
public void OnWarn(OperatorBase op, string message) { _actualMessages.Add(message); }
/// <inheritdoc /> public bool Evaluate(IList <IOpCode> opCodes) { bool retVal = false; foreach (var opCode in opCodes) { switch (opCode.EntryType) { case EntryType.Value: machineStack.Push(opCode.PolicyValue); break; case EntryType.Operator: Delegate executor = null; Object[] args = null; if (opCode.PolicyOperator is BinaryOperator) { if (machineStack.Count < 2) { throw new InvalidOperationException("Stack machine must have at least two pushed operands for " + opCode.PolicyOperator.GetOperatorText() + " operator"); } OperatorBase policyOperator = PolicyOperator.TokenOperatorMap.Single(t => t.Key == opCode.PolicyOperator.GetHashCode()).Value; executor = policyOperator.ExecuteRef; var rightArg = machineStack.Pop(); var leftArg = machineStack.Pop(); args = new[] { leftArg, rightArg }; } if (opCode.PolicyOperator is UnaryOperator) { if (machineStack.Count < 1) { throw new InvalidOperationException("Stack machine must have at least one pushed operand for " + opCode.PolicyOperator.GetOperatorText() + " operator"); } OperatorBase policyOperator = PolicyOperator.TokenOperatorMap.Single(t => t.Key == opCode.PolicyOperator.GetHashCode()).Value; executor = policyOperator.ExecuteRef; args = new[] { machineStack.Pop() }; } if (executor != null) { object result = executor.DynamicInvoke(args); machineStack.Push(result); } break; } } if (!machineStack.Any() || machineStack.Count > 1) { throw new InvalidOperationException("Stack machine is either empty or has remaining parameters to be processed." + "\r\n\tFinal stack size: " + machineStack.Count); } object finalValue = machineStack.Pop(); try { retVal = (bool)finalValue; } catch (InvalidCastException e) { throw new InvalidCastException("Final machine value must be a boolean litteral" + "\r\n\tFinal value type: " + finalValue.GetType() + "\r\n\tFinal value value:" + finalValue, e); } return(retVal); }
/// <summary> /// 将表达式转换为后缀表达式 /// </summary> /// <param name="expression">文本表达式</param> /// <returns>转换后的后缀表达式</returns> internal static List <IOperatorOrOperand> ConvertInfixToPostfix(string expression) { // 预处理中缀表达式 List <IOperatorOrOperand> infix = SplitExpression(expression); // 运算符栈 System.Collections.Generic.Stack <OperatorBase> opr = new System.Collections.Generic.Stack <OperatorBase>(); // 后缀表达式输出 List <IOperatorOrOperand> output = new List <IOperatorOrOperand>(); // 遍历 foreach (IOperatorOrOperand item in infix) { if (item.IsOperator) { // 是运算符 if (item.GetType() == typeof(OperatorCloseBracket)) { // 闭括号 // 弹出运算符,直至遇到左括号为止 while (opr.Peek().GetType() != typeof(OperatorOpenBracket)) { output.Add(opr.Pop()); if (opr.Count == 0) { // 括号不配对 throw new InvalidCastException("左右括号不匹配。"); } } // 弹出左括号 opr.Pop(); } else { // 其它运算符 OperatorBase thisopr = item as OperatorBase; // 弹出优先级高或相等的运算符 int thisPriority = thisopr.Priority; while (opr.Count > 0) { OperatorBase topopr = opr.Peek(); if (topopr.GetType() != typeof(OperatorOpenBracket)) { // 如果栈顶运算符不为左括号 if (topopr.Priority > thisopr.Priority) { // 如果栈顶中的运算符优先级高于当前运算符,则输出并弹出栈 output.Add(opr.Pop()); } else if (topopr.Priority == thisopr.Priority) { // 如果栈顶中的运算符优先级与当前运算符相等 if (topopr.Direction == OperatingDirection.LeftToRight) { // 如果栈顶运算符结合性方向为从左至右,则输出并弹出栈 output.Add(opr.Pop()); } else { // 如果是从右至左,终止弹栈 break; } } else { // 终止弹栈 break; } } else { // 终止弹栈 break; } } // 将当前运算符压入栈中 opr.Push(thisopr); } } else { // 是操作数 // 直接输出 output.Add(item); } } // 遍历结束,输出栈中全部剩余 while (opr.Count > 0) { output.Add(opr.Pop()); } return(output); }
/// <summary> /// 将表达式中的操作数和运算符分割出来 /// </summary> /// <param name="expression">文本表达式</param> /// <returns>操作数与运算符表</returns> internal static List <IOperatorOrOperand> SplitExpression(string expression) { List <IOperatorOrOperand> output = new List <IOperatorOrOperand>(); StringBuilder operandbuf = new StringBuilder(); StringBuilder operatorbuf = new StringBuilder(); // 记录刚才最后输出的表达式项 IOperatorOrOperand lastItem = null; // 在尾部添加一个空格,帮助分离最后一个操作数或运算符 expression = expression + " "; double result = 0; for (int i = 0; i < expression.Length; i++) { if (char.IsDigit(expression[i]) == true || expression[i] == '.') { // 如果是数字或小数点(操作数成份) // 结束前一个运算符 if (operatorbuf.Length > 0) { // 尝试获取运算符 OperatorBase opr = TryGetOperator(operatorbuf.ToString(), lastItem); if (opr != null) { output.Add(opr); lastItem = opr; operatorbuf.Length = 0; } else { throw new InvalidCastException(operatorbuf.ToString() + " 无法解析为合法的运算符。"); } } // 合并入当前操作数项 operandbuf.Append(expression[i]); } else { // 不是数字或小数点(运算符成份) // 结束前一个操作数 if (operandbuf.Length > 0) { if (double.TryParse(operandbuf.ToString(), out result) == false) { throw new FormatException(operandbuf.ToString() + " 无法解析为合法的操作数。"); } // 输出操作数 OperandInfo operand = new OperandInfo(double.Parse(operandbuf.ToString())); output.Add(operand); lastItem = operand; operandbuf.Length = 0; } // 合并非空白字符到当前运算符项 if (char.IsWhiteSpace(expression[i]) == false) { operatorbuf.Append(expression[i]); } // 分析并输出运算符 if (operatorbuf.Length > 0) { // 尝试获取运算符 OperatorBase opr = TryGetOperator(operatorbuf.ToString(), lastItem); if (opr != null) { output.Add(opr); lastItem = opr; operatorbuf.Length = 0; } } } } return(output); }
/** * Constructor * @param operator The operator that will be executed when the expression is evaluated. * @param operands The parameters that will be used by the operator when the expression is evaluated. */ public OperationPolicyExpression(OperatorBase pOperator, IEnumerable <IPolicyExpression> operands) { this.Operator = pOperator; this.Operands = new List <IPolicyExpression>(operands); }
Queue <Token> GetPostFix(string input, TokenFactory tokenFactory) { Queue <Token> output = new Queue <Token>(); Stack <Token> stack = new Stack <Token>(); int position = 0; while (position < input.Length) { Token token = GetNextToken(ref position, input, tokenFactory); if (token == null) { break; } if (token is NumberBase) { output.Enqueue(token); } else if (token is FunctionBase) { stack.Push(token); } else if (token is LeftBracket) { stack.Push(token); } else if (token is RightBracket) { while (true) { Token taken = stack.Pop(); if (!(taken is LeftBracket)) { output.Enqueue(taken); } else { break; } } } else if (token is OperatorBase) { if (stack.Count > 0) { Token top = stack.Peek(); bool nested = true; while (nested) { if (top == null || !(top is OperatorBase)) { break; } OperatorBase o1 = (OperatorBase)token; OperatorBase o2 = (OperatorBase)top; if (o1.Associativity == Associativity.Left && (o2.Precedence >= o1.Precedence)) { output.Enqueue(stack.Pop()); } else if (o2.Associativity == Associativity.Right && (o2.Precedence > o1.Precedence)) { output.Enqueue(stack.Pop()); } else { nested = false; } top = (stack.Count > 0) ? stack.Peek() : null; } } stack.Push(token); } } while (stack.Count > 0) { Token next = stack.Pop(); if (next is LeftBracket || next is RightBracket) { throw new ArgumentException(InvalidMessage); } output.Enqueue(next); } return(output); }