static void Main() { // Write a program that calculates the value of given arithmetical expression. // The expression can contain the following elements only: // Real numbers, e.g. 5, 18.33, 3.14159, 12.6 // Arithmetic operators: +, -, *, / (standard priorities) // Mathematical functions: ln(x), sqrt(x), pow(x,y) // Brackets (for changing the default priorities) // Examples: // (3+5.3) * 2.7 - ln(22) / pow(2.2, -1.7) = 10.60... // pow(2, 3.14) * (3 - (3 * sqrt(2) - 3.2) + 1.5*0.3) = 21.22... Console.Write("Please enter a math expression: "); string expression = Console.ReadLine(); ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator(); double result = 0; if (expressionEvaluator.TryEvaluate(expression, out result)) { Console.WriteLine("result: {0}", result); } else { Console.WriteLine("Incorrect expression!"); } }
public void Setup() { mockParser = new Mock<IParser>(); expressionEvaluator = new AlbatrossExpressionEvaluator(mockParser.Object); mockParser.Setup(p => p.Compile("expression").EvalValue(null)).Returns(9266); }
public void ExpressionEvaluator_Complex_EvaluateInRootDataContext() { var view = new RedwoodView() { DataContext = new TestViewModel() { SubObject = new TestViewModel2() { Value = "hello" } }, Children = { new HtmlGenericControl("html") { Children = { new TextBox() { ID = "txb" } } } .WithBinding(RedwoodBindableControl.DataContextProperty, new ValueBindingExpression("SubObject")) } }; var textbox = view.FindControl("txb") as TextBox; var evaluator = new ExpressionEvaluator(); var result = evaluator.Evaluate(new ValueBindingExpression("Value"), RedwoodBindableControl.DataContextProperty, textbox); Assert.IsInstanceOfType(result, typeof(string)); Assert.AreEqual("hello", result); }
/// <summary> /// Creates a new <see cref="TransactionVariables"/>. /// </summary> /// <param name="formId">The form id.</param> /// <param name="applicationId">The application id.</param> /// <param name="applicationData">The application data.</param> /// <returns>A new <see cref="TransactionVariables"/>.</returns> public TransactionVariables Create(string formId, string applicationId, ApplicationData applicationData) { ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(null, formId, null, applicationId, applicationData)); double amountValue = evaluator.Evaluate<double>(this.AmountExpression); string referenceValue = evaluator.Evaluate<string>(this.ReferenceExpression); return new TransactionVariables(this.MerchantPassword, amountValue, referenceValue); }
public HostBridge(GossipLexer gossipLexer) { m_HostCallTable = new HostCallTable(); m_TypeBindingTable = new TypeBindingTable(gossipLexer); m_EnumDefineTable = new EnumDefineTable(); m_ExpressionEvaluator = new ExpressionEvaluator(m_HostCallTable); m_EventBindingTable = new EventBindingTable(); }
public void ExpressionEvaluator_Standalone_Valid_MethodResult() { var viewModel = new TestA() { TestProp = new TestA() }; var evaluator = new ExpressionEvaluator() { AllowMethods = true }; Assert.AreEqual(viewModel.GetType().GetMethod("Test"), evaluator.Evaluate("Test", viewModel)); Assert.AreEqual(viewModel.GetType().GetMethod("Test"), evaluator.Evaluate("_root.Test", viewModel)); Assert.AreEqual(viewModel.GetType().GetMethod("Test2"), evaluator.Evaluate("_root.TestProp.Test2", viewModel)); }
private ExpressionEvaluator GetExpressionEvaluator(CriteriaOperator criteria) { if (criteria.ToString() == lastCriteria) return lastEvaluator; lastCriteria = criteria.ToString(); PropertyDescriptorCollection pdc = ((ITypedList)_View.DataSource).GetItemProperties(null); lastEvaluator = new ExpressionEvaluator(pdc, criteria, false); return lastEvaluator; }
public static bool Fit(this CriteriaOperator criteriaOperator, object targetObject) { if (ReferenceEquals(criteriaOperator, null)) return true; Type objectType = targetObject.GetType(); var wrapper = new LocalizedCriteriaWrapper(objectType, criteriaOperator); wrapper.UpdateParametersValues(targetObject); var objectSpace = XPObjectSpace.FindObjectSpaceByObject(targetObject); EvaluatorContextDescriptor descriptor = objectSpace != null ? objectSpace.GetEvaluatorContextDescriptor(objectType) : new EvaluatorContextDescriptorDefault(objectType); var evaluator = new ExpressionEvaluator(descriptor, wrapper.CriteriaOperator, XpoTypesInfoHelper.GetXpoTypeInfoSource().XPDictionary.CustomFunctionOperators); return evaluator.Fit(targetObject); }
public void SetPlugsByCriteries(Drawing drawing, CriteriaOperator criteria) { var hier = _dataManagersFactory.GetDrawingsHierClassDataManager(); var evaluator = new ExpressionEvaluator(TypeDescriptor.GetProperties(typeof (Drawing)), criteria); var childrens = hier.GetListAllChildrens(drawing.Id); var plugsChildrens = evaluator.Filter(childrens); foreach (Drawing children in plugsChildrens) { children.OP = "З"; hier.Update(children); } }
/// <summary> /// Evaluates the given expression in at the provided line number and returns the values /// that the expression can evaluate to. /// </summary> /// <param name="exprText">The expression to determine the result of.</param> /// <param name="index">The 0-based absolute index into the file where the expression should be evaluated within the module.</param> public IEnumerable<AnalysisValue> GetValuesByIndex(string exprText, int index) { var scope = FindEnvironment(index); var expr = Statement.GetExpression(GetAstFromText(exprText).Block); var unit = GetEvalAnalysisUnit(scope); var eval = new ExpressionEvaluator(unit, scope); var res = AnalysisSet.EmptyUnion; if (expr != null) { var values = eval.Evaluate(expr); foreach (var v in values) { if (v.Value.IsCurrent) { res = res.Add(v); } } } return res.Select(x => x.Value); }
public void ExpressionEvaluator_Standalone_Valid_PropertyAccess() { var viewModel = new { FirstName = "aa", LastName = new { Name = "bb", Title = new[] { 1, 2, 3 } } }; var evaluator = new ExpressionEvaluator(); Assert.AreEqual(viewModel.FirstName, evaluator.Evaluate("FirstName", viewModel)); Assert.AreEqual(viewModel.LastName, evaluator.Evaluate("LastName", viewModel)); Assert.AreEqual(viewModel.LastName.Name, evaluator.Evaluate("LastName.Name", viewModel)); Assert.AreEqual(viewModel.LastName.Title[2], evaluator.Evaluate("LastName.Title[2]", viewModel)); Assert.AreEqual(viewModel.LastName.Title[2], evaluator.Evaluate("_root.LastName.Title[2]", viewModel)); }
/// <summary> /// Evaluates the given expression in at the provided line number and returns the values /// that the expression can evaluate to. /// </summary> /// <param name="exprText">The expression to determine the result of.</param> /// <param name="location">The location in the file where the expression should be evaluated.</param> /// <remarks>New in 2.2</remarks> public IEnumerable<AnalysisValue> GetValues(string exprText, SourceLocation location) { var scope = FindScope(location); var privatePrefix = GetPrivatePrefixClassName(scope); var expr = Statement.GetExpression(GetAstFromText(exprText, privatePrefix).Body); var unit = GetNearestEnclosingAnalysisUnit(scope); var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true); var values = eval.Evaluate(expr); var res = AnalysisSet.EmptyUnion; foreach (var v in values) { MultipleMemberInfo multipleMembers = v as MultipleMemberInfo; if (multipleMembers != null) { foreach (var member in multipleMembers.Members) { if (member.IsCurrent) { res = res.Add(member); } } } else if (v.IsCurrent) { res = res.Add(v); } } return res; }
public RowMatcher(WildCardValueMatcher wildCardValueMatcher, ExpressionEvaluator expressionEvaluator) { _wildCardValueMatcher = wildCardValueMatcher; _expressionEvaluator = expressionEvaluator; }
IEnumerable GetDataSource() { IEnumerable dataSource = null; if (_dataSourceProperty != null) { dataSource = _dataSourceProperty.GetValue(CurrentObject, null) as IEnumerable; if (dataSource != null) { bool hasItems = (dataSource).GetEnumerator().MoveNext(); if (!hasItems) dataSource = null; } } if (dataSource == null) { if (string.IsNullOrEmpty(_isNullCriteria)) { if (_isNullMode == DataSourcePropertyIsNullMode.SelectAll) return descriptor.Values; if (_isNullMode == DataSourcePropertyIsNullMode.SelectNothing) return null; } else { CriteriaOperator criteriaOperator = CriteriaOperator.Parse(_isNullCriteria); if (!ReferenceEquals(criteriaOperator, null)) { dataSource = new List<object>(); foreach (object item in descriptor.Values) ((IList)dataSource).Add(CreateEditItem(item)); criteriaOperator.Accept(new EnumCriteriaParser(PropertyName, _propertyType)); var filteredDataSource = new ExpressionEvaluator(PropertyDescriptorCollection, criteriaOperator, true).Filter(dataSource); ((IList)dataSource).Clear(); foreach (ListEditItem item in filteredDataSource) ((IList)dataSource).Add(item); } } } return dataSource; }
/// <summary> /// Evaluates a given expression and returns a list of members which exist in the expression. /// /// If the expression is an empty string returns all available members at that location. /// /// index is a zero-based absolute index into the file. /// </summary> public IEnumerable<MemberResult> GetMembersByIndex(string exprText, int index, GetMemberOptions options = GetMemberOptions.None) { if (exprText.Length == 0) { return GetAllAvailableMembersByIndex(index, options); } var scope = FindEnvironment(index); var expr = Statement.GetExpression(GetAstFromText(exprText).Block); if (expr == null) { return new MemberResult[0]; } if (expr is ConstantWrapper && ((ConstantWrapper)expr).Value is int) { // no completions on integer ., the user is typing a float return new MemberResult[0]; } var unit = GetEvalAnalysisUnit(scope); var lookup = new ExpressionEvaluator(unit, scope).Evaluate(expr); return GetMemberResults(lookup, scope, options); }
static KeyValuePairList <JoinType, Expression> ResolveJoinInfo(LambdaExpression joinInfoExp) { /* * Usage: * var view = context.JoinQuery<User, City, Province, User, City>((user, city, province, user1, city1) => new object[] * { * JoinType.LeftJoin, user.CityId == city.Id, * JoinType.RightJoin, city.ProvinceId == province.Id, * JoinType.InnerJoin,user.Id==user1.Id, * JoinType.FullJoin,city.Id==city1.Id * }).Select((user, city, province, user1, city1) => new { User = user, City = city, Province = province, User1 = user1, City1 = city1 }); * * To resolve join infomation: * JoinType.LeftJoin, user.CityId == city.Id index of joinType is 0 * JoinType.RightJoin, city.ProvinceId == province.Id index of joinType is 2 * JoinType.InnerJoin,user.Id==user1.Id index of joinType is 4 * JoinType.FullJoin,city.Id==city1.Id index of joinType is 6 */ NewArrayExpression body = joinInfoExp.Body as NewArrayExpression; if (body == null) { throw new ArgumentException(string.Format("Invalid join infomation '{0}'. The correct usage is like: {1}", joinInfoExp, "context.JoinQuery<User, City>((user, city) => new object[] { JoinType.LeftJoin, user.CityId == city.Id })")); } KeyValuePairList <JoinType, Expression> ret = new KeyValuePairList <JoinType, Expression>(); if ((joinInfoExp.Parameters.Count - 1) * 2 != body.Expressions.Count) { throw new ArgumentException(string.Format("Invalid join infomation '{0}'.", joinInfoExp)); } for (int i = 0; i < joinInfoExp.Parameters.Count - 1; i++) { /* * 0 0 * 1 2 * 2 4 * 3 6 * ... */ int indexOfJoinType = i * 2; Expression joinTypeExpression = body.Expressions[indexOfJoinType]; object inputJoinType = ExpressionEvaluator.Evaluate(joinTypeExpression); if (inputJoinType == null || inputJoinType.GetType() != typeof(JoinType)) { throw new ArgumentException(string.Format("Not support '{0}', please pass correct type of 'Chloe.JoinType'.", joinTypeExpression)); } /* * The next expression of join type must be join condition. */ Expression joinCondition = body.Expressions[indexOfJoinType + 1].StripConvert(); if (joinCondition.Type != PublicConstants.TypeOfBoolean) { throw new ArgumentException(string.Format("Not support '{0}', please pass correct join condition.", joinCondition)); } ParameterExpression[] parameters = joinInfoExp.Parameters.Take(i + 2).ToArray(); List <Type> typeArguments = parameters.Select(a => a.Type).ToList(); typeArguments.Add(PublicConstants.TypeOfBoolean); Type delegateType = Utils.GetFuncDelegateType(typeArguments.ToArray()); LambdaExpression lambdaOfJoinCondition = Expression.Lambda(delegateType, joinCondition, parameters); ret.Add((JoinType)inputJoinType, lambdaOfJoinCondition); } return(ret); }
public void SetUp() { engine = new ExpressionEvaluator(); generator = new Random(); }
public void TestRepeaterCalculation() { ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(this.postedData)); ApplicationDataPath path = new ApplicationDataPath(); path.Append("key4"); path.First().Index = 0; Assert.AreEqual(50, evaluator.Evaluate<int>("{%child1%} - {%child2%}", path)); path.First().Index = 1; Assert.AreEqual(150, evaluator.Evaluate<int>("{%child1%} - {%child2%}", path)); }
/// <summary> /// Handles the ExecuteCode event of the PrepareDynamicResolution CodeActivity. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void PrepareDynamicGrammarResolution_ExecuteCode(object sender, EventArgs e) { Logger.Instance.WriteMethodEntry(EventIdentifier.UpdateResourcesForEachDynamicStringForResolutionInitialized); this.DynamicStringsForResolution = new List <string>(); // clear any previous values try { // Load resolved value expressions to the expression evaluator foreach (string key in this.ValueExpressions.Keys) { this.ActivityExpressionEvaluator.LookupCache[key] = this.ValueExpressions[key]; } var newUpdates = new List <Definition>(); // Clear the variable cache for the expression evaluator List <string> variables = this.ActivityExpressionEvaluator.VariableCache.Keys.ToList(); foreach (string variable in variables) { this.ActivityExpressionEvaluator.VariableCache[variable] = null; } foreach (Definition updateDefinition in this.updates) { // Determine if we are targeting a variable // If so, publish the variable bool targetVariable = ExpressionEvaluator.DetermineParameterType(updateDefinition.Right) == ParameterType.Variable; if (targetVariable) { object resolved = this.ActivityExpressionEvaluator.ResolveExpression(updateDefinition.Left); this.ActivityExpressionEvaluator.PublishVariable(updateDefinition.Right, resolved, UpdateMode.Modify); } } foreach (Definition updateDefinition in this.updates) { // Resolve the source expression, including any functions or concatenation, // to retrieve the typed value that should be assigned to the target attribute object resolved = this.ActivityExpressionEvaluator.ResolveExpression(updateDefinition.Left); if (resolved is string) { string updateDefinitionLeft = resolved as string; newUpdates.Add(new Definition(updateDefinitionLeft, updateDefinition.Right, updateDefinition.Check)); if (!this.ActivityExpressionEvaluator.ParseIfExpression(updateDefinitionLeft)) { this.DynamicStringsForResolution.Add(updateDefinitionLeft); } } else { newUpdates.Add(updateDefinition); } } this.updates = newUpdates; } finally { Logger.Instance.WriteMethodExit(EventIdentifier.UpdateResourcesForEachDynamicStringForResolutionInitialized, "DynamicStringsForResolution Count: '{0}'.", this.DynamicStringsForResolution.Count); } }
protected override bool ContextIsSatisfied(ExpressionEvaluator evaluator, TextArea textArea) { return(textArea.IsInString()); }
public TypingTypeInfoFinalizer(ExpressionEvaluator eval, Node node, AnalysisUnit unit) { _eval = eval; _node = node; _unit = unit; }
public virtual object Insert <TEntity>(Expression <Func <TEntity> > body) { Utils.CheckNull(body); TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(typeof(TEntity)); EnsureEntityHasPrimaryKey(typeDescriptor); MappingMemberDescriptor keyMemberDescriptor = typeDescriptor.PrimaryKey; MappingMemberDescriptor autoIncrementMemberDescriptor = typeDescriptor.AutoIncrement; Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(body); DbInsertExpression e = new DbInsertExpression(typeDescriptor.Table); object keyVal = null; foreach (var kv in insertColumns) { MemberInfo key = kv.Key; MappingMemberDescriptor memberDescriptor = typeDescriptor.TryGetMappingMemberDescriptor(key); if (memberDescriptor == null) { throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name)); } if (memberDescriptor == autoIncrementMemberDescriptor) { throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", memberDescriptor.Column.Name)); } if (memberDescriptor.IsPrimaryKey) { object val = ExpressionEvaluator.Evaluate(kv.Value); if (val == null) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", memberDescriptor.MemberInfo.Name)); } else { keyVal = val; e.InsertColumns.Add(memberDescriptor.Column, DbExpression.Parameter(keyVal)); continue; } } e.InsertColumns.Add(memberDescriptor.Column, typeDescriptor.Visitor.Visit(kv.Value)); } //主键为空并且主键又不是自增列 if (keyVal == null && keyMemberDescriptor != autoIncrementMemberDescriptor) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyMemberDescriptor.MemberInfo.Name)); } if (keyMemberDescriptor != autoIncrementMemberDescriptor) { this.ExecuteSqlCommand(e); return(keyVal); } IDbExpressionTranslator translator = this.DbContextServiceProvider.CreateDbExpressionTranslator(); List <DbParam> parameters; string sql = translator.Translate(e, out parameters); sql = string.Concat(sql, ";", this.GetSelectLastInsertIdClause()); //SELECT @@IDENTITY 返回的是 decimal 类型 object retIdentity = this.Session.ExecuteScalar(sql, parameters.ToArray()); if (retIdentity == null || retIdentity == DBNull.Value) { throw new ChloeException("Unable to get the identity value."); } retIdentity = ConvertIdentityType(retIdentity, autoIncrementMemberDescriptor.MemberInfoType); return(retIdentity); }
/// <summary> /// Initializes a new instance of the <see cref="Expression"/> class. /// Expression constructor. /// </summary> /// <param name="evaluator">Information about how to validate and evaluate expression.</param> /// <param name="children">Child expressions.</param> public Expression(ExpressionEvaluator evaluator, params Expression[] children) { Evaluator = evaluator; Children = children; }
/// <summary> /// Validates the inputs. Returns true if all of the UI controls contain valid values. Otherwise, returns false. /// </summary> /// <returns>true if all of the UI controls contain valid values. Otherwise, false.</returns> public override bool ValidateInputs() { Logger.Instance.WriteMethodEntry(); try { if (!this.controller.ValidateInputs()) { return(false); } ExpressionEvaluator evaluator = new ExpressionEvaluator(); switch (GetInputType(this.inputType.Value)) { case PowerShellInputType.Parameters: foreach (DefinitionListing parameter in this.parameters.DefinitionListings.Where(parameter => parameter.Active)) { if (parameter.Definition == null) { // If a value is missing for parameter name or value expression, the definition // will be null and the listing fails validation this.controller.ValidationError = ActivitySettings.ScriptParameterDefintionValidationError; return(false); } // Attempt to parse the value expression try { evaluator.ParseExpression(parameter.Definition.Right); } catch (WorkflowActivityLibraryException ex) { this.controller.ValidationError = ex.Message; return(false); } } break; case PowerShellInputType.Arguments: foreach (DefinitionListing argument in this.arguments.DefinitionListings.Where(argument => argument.Active)) { if (string.IsNullOrEmpty(argument.State.Left)) { // If a value is missing for the expression, fail validation this.controller.ValidationError = ActivitySettings.ScriptArgumentValidationError; return(false); } // Attempt to parse the value expression try { evaluator.ParseExpression(argument.State.Left); } catch (WorkflowActivityLibraryException ex) { this.controller.ValidationError = ex.Message; return(false); } } break; } try { if (!string.IsNullOrEmpty(this.activityExecutionCondition.Value)) { evaluator.ParseExpression(this.activityExecutionCondition.Value); // Verify that the activity execution condition resolves to a Boolean value if (!evaluator.IsBooleanExpression(this.activityExecutionCondition.Value)) { this.controller.ValidationError = ActivitySettings.ActivityExecutionConditionValidationError; return(false); } } } catch (WorkflowActivityLibraryException ex) { this.controller.ValidationError = ex.Message; return(false); } if (this.impersonatePowerShellUser.Value) { if (string.IsNullOrEmpty(this.powerShellUser.Value) || string.IsNullOrEmpty(this.powerShellUserPassword.Value)) { this.controller.ValidationError = ActivitySettings.PowerShellImpersonationSettingsValidationError; return(false); } } if (!string.IsNullOrEmpty(this.powerShellUser.Value)) { var powerShellUserIsExpression = evaluator.ParseIfExpression(this.powerShellUser.Value); if (this.impersonatePowerShellUser.Value && !powerShellUserIsExpression) { if (!this.powerShellUser.Value.Contains(@"\") && !this.powerShellUser.Value.Contains("@")) { this.controller.ValidationError = ActivitySettings.PowerShellUserFormatValidationError; return(false); } } if (string.IsNullOrEmpty(this.powerShellUserPassword.Value)) { this.controller.ValidationError = ActivitySettings.PowerShellUserPasswordValidationError; return(false); } // Limited value in this check as the code runs under the context of submitter instead of FIMService plus // code run on the Portal Server which may not be co-located with FIMService server. ////try ////{ //// ProtectedData.DecryptData(this.powerShellUserPassword.Value); ////} ////catch (WorkflowActivityLibraryException ex) ////{ //// this.controller.ValidationError = ex.Message; //// return false; ////} } // If no errors were found, clear any validation error and return true this.controller.ValidationError = string.Empty; return(true); } catch (Exception e) { Logger.Instance.ReportError(e); throw; } finally { Logger.Instance.WriteMethodExit(); } }
public void Test_AsmSourceTools_Evaluate_1() { { ulong i = 0ul; string s = i + ""; (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 0ul; string s = "0x" + i.ToString("X"); (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 0ul; string s = i.ToString("X") + "h"; (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 1ul; string s = i.ToString("X") + "h"; (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 1ul; string s = "0x" + i.ToString("X");; (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 1ul; string s = i.ToString("X") + "h"; (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 0xFFul; string s = "0x" + i.ToString("X");; (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 0xFFul; string s = i.ToString("X") + "h"; (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(8, NBits, s); } { ulong i = 0x100ul; string s = "0x" + i.ToString("X"); (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(16, NBits, s); } { ulong i = 0xFFFFul; string s = "0x" + i.ToString("X"); (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(16, NBits, s); } { ulong i = 0x10000ul; string s = "0x" + i.ToString("X"); (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(32, NBits, s); } { ulong i = 0xFFFFFFFFul; string s = "0x" + i.ToString("X"); (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid); Assert.AreEqual(i, Value, s); Assert.AreEqual(32, NBits, s); } { ulong i = 0x100000000ul; string s = "0x" + i.ToString("X"); (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid, "could not parse: s=" + s); Assert.AreEqual(i, Value, s); Assert.AreEqual(64, NBits, s); } { ulong i = 0xFFFFFFFFFFFFFFFFul; string s = "0x" + i.ToString("X"); (bool Valid, ulong Value, int NBits) = ExpressionEvaluator.Evaluate_Constant(s); Assert.IsTrue(Valid); Assert.AreEqual(i, Value, s); Assert.AreEqual(64, NBits, s); } }
private async void CalculateButton_Click(object sender, RoutedEventArgs e) { CalculateButton.IsEnabled = false; CancelButton.IsEnabled = true; ExpressionEvaluator evaluator = new ExpressionEvaluator() { OptionScriptNeedSemicolonAtTheEndOfLastExpression = NeedSemicolonAtTheEndCheckBox.IsChecked.GetValueOrDefault(), }; if (UseCachesCheckbox.IsChecked ?? false) { evaluator.CacheTypesResolutions = true; } evaluator.Namespaces.Add("System.Windows"); evaluator.Namespaces.Add("System.Diagnostics"); evaluator.EvaluateVariable += Evaluator_EvaluateVariable; evaluator.EvaluateFunction += Evaluator_EvaluateFunction; Stopwatch stopWatch = new Stopwatch(); try { string script = evaluator.RemoveComments(ScriptTextBox.Text); string sIteration = IterationsTextBox.Text; Exception exception = null; cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.Token.ThrowIfCancellationRequested(); string result = await Task.Run(() => { if (!int.TryParse(sIteration, out int iterations)) { iterations = 1; } iterations = Math.Max(0, iterations); stopWatch.Start(); try { using (cancellationTokenSource.Token.Register(Thread.CurrentThread.Abort)) { string innerResult = "null or void"; for (int i = 0; i < iterations; i++) { innerResult = evaluator.ScriptEvaluate(script)?.ToString() ?? "null or void"; } return(innerResult); } } catch (Exception innerException) { exception = innerException; return(null); } finally { stopWatch.Stop(); } }, cancellationTokenSource.Token).ConfigureAwait(true); if (exception == null) { ResultTextBlock.Text = result; } else { throw exception; } } catch (Exception exception) { ResultTextBlock.Text = exception.Message; } ExecutionTimeTextBlock.Text = $"Execution time : {stopWatch.Elapsed}"; evaluator.EvaluateVariable -= Evaluator_EvaluateVariable; CalculateButton.IsEnabled = true; CancelButton.IsEnabled = false; }
public void TestAllowMixedSlashesAndQuotes() { this.postedData.Add("mixed", @"Top 'o the morning to ye, \iApply!"); ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(this.postedData)); Assert.AreEqual(@"Top 'o the morning to ye, \iApply!", evaluator.Evaluate<string>("if('{%mixed%}' != 0, '{%mixed%}', '')")); }
/// <summary> /// Gets the variables the given expression evaluates to. Variables include parameters, locals, and fields assigned on classes, modules and instances. /// /// Variables are classified as either definitions or references. Only parameters have unique definition points - all other types of variables /// have only one or more references. /// </summary> public IEnumerable <IAnalysisVariable> GetVariables(string exprText, int lineNumber) { var expr = GetExpressionFromText(exprText); var scopes = FindScopes(lineNumber); var eval = new ExpressionEvaluator(_unit.CopyForEval(), FindScopes(lineNumber).ToArray()); NameExpression name = expr as NameExpression; if (name != null) { for (int i = scopes.Count - 1; i >= 0; i--) { VariableDef def; if (IncludeScope(scopes, i, lineNumber) && scopes[i].Variables.TryGetValue(name.Name, out def)) { foreach (var res in ToVariables(def)) { yield return(res); } if (scopes[i] is FunctionScope) { // if this is a parameter or a local indicate any values which we know are assigned to it. foreach (var type in def.Types) { if (type.Location != null) { yield return(new AnalysisVariable(VariableType.Value, type.Location)); } } } else if (scopes[i] is ModuleScope) { foreach (var type in def.Types) { if (type.Location != null) { yield return(new AnalysisVariable(VariableType.Definition, type.Location)); } foreach (var reference in type.References) { yield return(new AnalysisVariable(VariableType.Reference, reference)); } } } } } var variables = _unit.ProjectState.BuiltinModule.GetDefinitions(name.Name); foreach (var referenceable in variables) { foreach (var res in ToVariables(referenceable)) { yield return(res); } } } MemberExpression member = expr as MemberExpression; if (member != null) { var objects = eval.Evaluate(member.Target); foreach (var v in objects) { var container = v as IReferenceableContainer; if (container != null) { var defs = container.GetDefinitions(member.Name); foreach (var def in defs) { foreach (var reference in def.Definitions) { yield return(new AnalysisVariable(VariableType.Definition, new LocationInfo(reference.Key, reference.Value.Line, reference.Value.Column, reference.Value.Length))); } foreach (var reference in def.References) { yield return(new AnalysisVariable(VariableType.Reference, new LocationInfo(reference.Key, reference.Value.Line, reference.Value.Column, reference.Value.Length))); } } } } } }
public void TestAllowQuotes() { this.postedData.Add("quotes", @"O'Malley"); ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(this.postedData)); Assert.AreEqual("O'Malley", evaluator.Evaluate<string>("if('{%quotes%}' != 0, '{%quotes%}', '')")); }
//, = null, CastedSpell spell = null public abstract object Evaluate(List <string> args, ExpressionEvaluator evaluator, Character player, Creature target, CastedSpell spell);
public ExpressionSimplifierVisitor() : base(true, true) { evaluator = new ExpressionEvaluator(); }
private static IAnalysisSet FsReadDirSync(FunctionValue func, Node node, AnalysisUnit unit, IAnalysisSet @this, IAnalysisSet[] args) { var call = node as CallNode; if (call != null && call.Arguments.Length == 1) { var ee = new ExpressionEvaluator(unit); IAnalysisSet arraySet; ReadDirSyncArrayValue array; if (!unit.GetDeclaringModuleEnvironment().TryGetNodeValue(NodeEnvironmentKind.ArrayValue, call, out arraySet)) { array = new ReadDirSyncArrayValue( unit.ProjectEntry, node ); arraySet = array.SelfSet; unit.GetDeclaringModuleEnvironment().AddNodeValue(NodeEnvironmentKind.ArrayValue, call, arraySet); } else { array = (ReadDirSyncArrayValue)arraySet.First().Value; } foreach (var path in ee.MergeStringLiterals(call.Arguments[0])) { array.AddDirectoryMembers(unit, path); } return array.SelfSet; } return AnalysisSet.Empty; }
/// <summary> /// Handles the ExecuteCode event of the PrepareUpdate CodeActivity. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void PrepareUpdate_ExecuteCode(object sender, EventArgs e) { Logger.Instance.WriteMethodEntry(EventIdentifier.UpdateResourcesPrepareUpdateExecuteCode); try { // Load resolved value expressions to the expression evaluator foreach (string key in this.ValueExpressions.Keys) { this.ActivityExpressionEvaluator.LookupCache[key] = this.ValueExpressions[key]; } // Clear the variable cache for the expression evaluator List <string> variables = this.ActivityExpressionEvaluator.VariableCache.Keys.ToList(); foreach (string variable in variables) { this.ActivityExpressionEvaluator.VariableCache[variable] = null; } // Loop through each attribute update definition to build the // update resource parameters which will be used to update each target resource this.LookupUpdates = new List <UpdateLookupDefinition>(); foreach (Definition updateDefinition in this.updates) { // Resolve the source expression, including any functions or concatenation, // to retrieve the typed value that should be assigned to the target attribute object resolved = null; if (!ExpressionEvaluator.IsExpression(updateDefinition.Left)) { // This is a dynamic string for resolution already resolved // so just retrive the value from cache directly resolved = this.ActivityExpressionEvaluator.LookupCache[updateDefinition.Left]; } else { resolved = this.ActivityExpressionEvaluator.ResolveExpression(updateDefinition.Left); } // Determine if we are targeting a variable // If not, assume we are targeting an expression which should result in requests or update // to the workflow dictionary bool targetVariable = ExpressionEvaluator.DetermineParameterType(updateDefinition.Right) == ParameterType.Variable; // Only create an update lookup definition if the value is not null, or if the // update definition is configured to allow null values to be transferred to the target(s) if (resolved == null && updateDefinition.Check) { if (targetVariable) { this.ActivityExpressionEvaluator.PublishVariable(updateDefinition.Right, null, UpdateMode.Modify); } else { this.LookupUpdates.Add(new UpdateLookupDefinition(updateDefinition.Right, null, UpdateMode.Modify)); } } else if (resolved != null) { if (resolved.GetType() == typeof(InsertedValuesCollection)) { // If the resolved object is an InsertedValues collection, the source for the update definition includes the InsertValues function // All associated values should be added to the target foreach (object o in (InsertedValuesCollection)resolved) { if (targetVariable) { this.ActivityExpressionEvaluator.PublishVariable(updateDefinition.Right, o, UpdateMode.Insert); } else { this.LookupUpdates.Add(new UpdateLookupDefinition(updateDefinition.Right, o, UpdateMode.Insert)); } } } else if (resolved.GetType() == typeof(RemovedValuesCollection)) { // If the resolved object is a RemovedValues collection, the source for the update definition includes the RemoveValues function // All associated values should be removed from the target foreach (object o in (RemovedValuesCollection)resolved) { if (targetVariable) { this.ActivityExpressionEvaluator.PublishVariable(updateDefinition.Right, o, UpdateMode.Remove); } else { this.LookupUpdates.Add(new UpdateLookupDefinition(updateDefinition.Right, o, UpdateMode.Remove)); } } } else { // For all other conditions, update the variable or build a new update request parameter for the target attribute if (targetVariable) { this.ActivityExpressionEvaluator.PublishVariable(updateDefinition.Right, resolved, UpdateMode.Modify); } else { this.LookupUpdates.Add(new UpdateLookupDefinition(updateDefinition.Right, resolved, UpdateMode.Modify)); } } } } } finally { Logger.Instance.WriteMethodExit(EventIdentifier.UpdateResourcesPrepareUpdateExecuteCode); } }
public override object Evaluate(List <string> args, ExpressionEvaluator evaluator, Creature player, Target target = null, CastedSpell spell = null, RollResults dice = null) { ExpectingArguments(args, 0); return(GiveTargetFullDamage.ApplyDamage(args, evaluator, player, target, 0.5)); }
protected abstract bool ContextIsSatisfied(ExpressionEvaluator evaluator, TextArea textArea);
public ExpressionEvaluator <T, Z> Prop <Z>(Expression <Func <T, Z> > entityExpression) { var expEvaluator = new ExpressionEvaluator <T, Z>(this, entityExpression); return(expEvaluator); }
private void btnMakePredictions_Click(object sender, EventArgs e) { string[] vars = _model.Keys.ToArray(); _dtVariables = (DataTable)dgvVariables.DataSource; if (_dtVariables == null) return; if (_dtVariables.Rows.Count < 1) return; dgvVariables.EndEdit(); _dtVariables.AcceptChanges(); dgvObs.EndEdit(); _dtObs = (DataTable)dgvObs.DataSource; if (_dtObs != null) _dtObs.AcceptChanges(); ExpressionEvaluator expEval = new ExpressionEvaluator(); DataTable dtPredictions = expEval.Evaluate(_modelExpression, _dtVariables); _dtStats = GeneratePredStats(dtPredictions, _dtObs); if (_dtStats == null) return; dgvStats.DataSource = _dtStats; foreach (DataGridViewColumn dvgCol in dgvStats.Columns) dvgCol.SortMode = DataGridViewColumnSortMode.NotSortable; setViewOnGrid(dgvStats); }
public void Visit(AssignmentNode assignmentNode) { SymbolType expressionType = new ExpressionTypeChecker(CurrentScope).GetType(assignmentNode.Expression); ValueNode expressionValue; switch (expressionType) { case SymbolType.Null: expressionValue = null; break; case SymbolType.Float: var floatEval = new ExpressionEvaluator <float>(new FloatCalculator(assignmentNode.Token)); assignmentNode.Expression.Accept(floatEval); expressionValue = new FloatValueNode() { Value = floatEval.Result }; break; case SymbolType.String: var stringEval = new ExpressionEvaluator <string>(new StringOperations(assignmentNode.Token)); assignmentNode.Expression.Accept(stringEval); expressionValue = new StringNode() { Value = stringEval.Result }; break; case SymbolType.Integer: var intEval = new ExpressionEvaluator <int>(new IntCalculator(assignmentNode.Token)); assignmentNode.Expression.Accept(intEval); expressionValue = new FloatValueNode() { Value = intEval.Result }; break; case SymbolType.Array: var arrayEval = new ExpressionEvaluator <ArrayNode>(new ArrayCalculator(assignmentNode.Token)); assignmentNode.Expression.Accept(arrayEval); expressionValue = arrayEval.Result; break; case SymbolType.Exit: var exitEval = new ExpressionEvaluator <ExitValueNode>(new ExitValueCalculator(assignmentNode.Token)); assignmentNode.Expression.Accept(exitEval); expressionValue = exitEval.Result; break; case SymbolType.Identifier: var idEval = new ExpressionEvaluator <ValueNode>(new NoOpCalculator <ValueNode>(assignmentNode.Token)); assignmentNode.Expression.Accept(idEval); expressionValue = idEval.Result; break; case SymbolType.MemberAccess: expressionValue = (ValueNode)assignmentNode.Expression; break; default: throw new ArgumentOutOfRangeException(); } assignmentNode.Expression = expressionValue; VariableSymbolTableEntry entry = new VariableSymbolTableEntry(expressionValue, expressionType); CurrentScope.AddOrUpdateSymbol(assignmentNode.Identifier, entry); }
protected override bool ContextIsSatisfied(ExpressionEvaluator evaluator, TextArea textArea) { return(string.IsNullOrWhiteSpace(TextLeftOfTemplate) && string.IsNullOrWhiteSpace(TextRightOfTemplate)); }
private Expression Evaluate(Expression e) { Type type = e.Type; // check for nullable converts & strip them if (e.NodeType == ExpressionType.Convert) { var u = (UnaryExpression)e; if (TypeHelper.GetNonNullableType(u.Operand.Type) == TypeHelper.GetNonNullableType(type)) { e = ((UnaryExpression)e).Operand; } } if (e.NodeType == ExpressionType.Call) { var m = e as MethodCallExpression; if (m.Method.DeclaringType == typeof(SqlFunctions) && m.Method.Name == "Convert") { if (TypeHelper.GetNonNullableType(m.Arguments[0].Type) == TypeHelper.GetNonNullableType(type)) { e = m.Arguments[0]; } } } // if we now just have a constant, return it if (e.NodeType == ExpressionType.Constant) { var ce = (ConstantExpression)e; // if we've lost our nullable typeness add it back if (e.Type != type && TypeHelper.GetNonNullableType(e.Type) == TypeHelper.GetNonNullableType(type)) { e = ce = Expression.Constant(ce.Value, type); } return(e); } var me = e as MemberExpression; if (me != null) { // member accesses off of constant's are common, and yet since these partial evals // are never re-used, using reflection to access the member is faster than compiling // and invoking a lambda var ce = me.Expression as ConstantExpression; if (ce != null) { return(Expression.Constant(me.Member.Get(ce.Value), type)); } } if (type.IsValueType) { e = Expression.Convert(e, typeof(object)); } Expression <Func <object> > lambda = Expression.Lambda <Func <object> >(e); #if NOREFEMIT Func <object> fn = ExpressionEvaluator.CreateDelegate(lambda); #else Func <object> fn = lambda.Compile(); #endif var value = fn(); return(Expression.Constant(value, type)); }
private static bool fit(object targetObject, string criteria) { Type objectType = targetObject.GetType(); var wrapper = new LocalizedCriteriaWrapper(objectType, criteria); wrapper.UpdateParametersValues(); var descriptor = new EvaluatorContextDescriptorDefault(objectType); var evaluator = new ExpressionEvaluator(descriptor, wrapper.CriteriaOperator); return evaluator.Fit(targetObject); }
/// <summary> /// Give values from the source data for all variable names in the expression. /// </summary> /// <param name="expression">The expression evaluator.</param> /// <param name="sourceData">The source data.</param> private void FillVariableNamesInExpression(ExpressionEvaluator expression, DataTable sourceData) { var simulationData = new List <Data>(); foreach (var variable in expression.Variables) { if (simulationData.Find(data => data.Name == variable.m_name) == null) { simulationData.Add(new Data(sourceData, variable.m_name)); } } // Need to get a list of common values for the key across the datasets. IEnumerable <object> keyValues = null; foreach (var dataset in simulationData) { if (keyValues == null) { keyValues = dataset.GetValues(FieldNameToMatchOn); } else { keyValues = keyValues.Intersect(dataset.GetValues(FieldNameToMatchOn)); } } // Create a new data set with the key field. var newTable = new DataTable(Name); DataTableUtilities.AddColumnOfObjects(newTable, FieldNameToMatchOn, keyValues.ToArray()); // Add all the double fields into the table. foreach (DataColumn column in sourceData.Columns) { if (column.DataType == typeof(double) && column.ColumnName != FieldNameToMatchOn) { newTable.Columns.Add(column.ColumnName, typeof(double)); } } // Get each dataset to return foreach (DataColumn column in sourceData.Columns) { if (column.DataType == typeof(double) && column.ColumnName != FieldNameToMatchOn) { var expressionVariables = new List <Symbol>(); foreach (var variable in expression.Variables) { var dataset = simulationData.Find(data => data.Name == variable.m_name); var symbol = new Symbol(); symbol.m_name = variable.m_name; symbol.m_values = dataset.GetDoubleValues(column.ColumnName); if (symbol.m_values.Length != keyValues.Count()) { throw new Exception($"Incorrect number of values for simulation {dataset.Name}"); } expressionVariables.Add(symbol); } expression.Variables = expressionVariables; expression.EvaluatePostfix(); if (expression.Error) { throw new Exception($"Error while evaluating expression for column {column.ColumnName}. {expression.ErrorDescription}"); } // Add data to new data table. DataTableUtilities.AddColumn(newTable, column.ColumnName, expression.Results); } } // Give the new data table to the data store. dataStore.Writer.WriteTable(newTable); }
/// <summary> /// Gets the variables the given expression evaluates to. Variables include parameters, locals, and fields assigned on classes, modules and instances. /// /// Variables are classified as either definitions or references. Only parameters have unique definition points - all other types of variables /// have only one or more references. /// /// index is a 0-based absolute index into the file. /// </summary> public IEnumerable<IAnalysisVariable> GetVariablesByIndex(string exprText, int index) { var scope = FindEnvironment(index); var expr = Statement.GetExpression(GetAstFromText(exprText).Block); var unit = GetEvalAnalysisUnit(scope); Lookup name = expr as Lookup; if (name != null) { var defScope = scope.EnumerateTowardsGlobal.FirstOrDefault(s => s.ContainsVariable(name.Name)); if (defScope == null) { defScope = scope.GlobalEnvironment; } return GetVariablesInScope(name, defScope).Distinct(); } var member = expr as Member; if (member != null) { var eval = new ExpressionEvaluator(unit, scope); var objects = eval.Evaluate(member.Root); var refs = Enumerable.Empty<IAnalysisVariable>(); foreach (var v in objects) { var container = v.Value as IReferenceableContainer; if (container != null) { refs = refs.Concat(ReferencablesToVariables(container.GetDefinitions(member.Name))); } } return refs; } return Enumerable.Empty<IAnalysisVariable>(); }
public override object GetValue(string variableName, ExpressionEvaluator evaluator, Character player) { if (Enum.TryParse(variableName, out CreatureKinds result)) return result; return null; }
/// <summary> /// Gets information about the available signatures for the given expression. /// </summary> /// <param name="exprText">The expression to get signatures for.</param> /// <param name="index">The 0-based absolute index into the file.</param> public IEnumerable<IOverloadResult> GetSignaturesByIndex(string exprText, int index) { try { var scope = FindEnvironment(index); var unit = GetEvalAnalysisUnit(scope); var eval = new ExpressionEvaluator(unit, scope); var expr = Statement.GetExpression(GetAstFromText(exprText).Block); if (expr == null || expr is ArrayLiteral) { return Enumerable.Empty<IOverloadResult>(); } var lookup = eval.Evaluate(expr); var result = new HashSet<OverloadResult>(OverloadResultComparer.Instance); foreach (var ns in lookup) { if (ns.Value.Overloads != null) { result.UnionWith(ns.Value.Overloads); } } return result; } catch (Exception) { // TODO: log exception return new[] { new SimpleOverloadResult("Unknown", "IntellisenseError_Sigs", new ParameterResult[0]) }; } }
internal IList GetDataSource(object forObject) { CriteriaOperator criteria = null; if (Properties == null) return null; IList propertyDataSource = (Properties.DataSourceMemberInfo != null) && (GridEditingObject != null) ? Properties.DataSourceMemberInfo.GetValue(forObject) as IList : null; IList dataSource = new List<ImageComboBoxItem>(); if (propertyDataSource == null) for (int i = 0; i < Properties.Items.Count; i++) dataSource.Add(Properties.Items[i]); else for (int i = 0; i < Properties.Items.Count; i++) { ImageComboBoxItem item = Properties.Items[i]; if (propertyDataSource.Contains(item.Value)) dataSource.Add(item); } string criteriaString = Properties.Model.DataSourceCriteria; if (!String.IsNullOrEmpty(criteriaString)) criteria = CriteriaOperator.Parse(criteriaString); if (!ReferenceEquals(criteria, null)) { criteria.Accept(new EnumCriteriaParser( Properties.PropertyMemberInfo.Name, Properties.PropertyMemberInfo.MemberType)); ICollection filteredDataSource = new ExpressionEvaluator(ImageComboBoxItemProperties, criteria, true).Filter(dataSource); dataSource.Clear(); foreach (ImageComboBoxItem item in filteredDataSource) dataSource.Add(item); } return dataSource; }
public void TestSingleFormCalculation() { ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(this.postedData)); Assert.AreEqual(6, evaluator.Evaluate<int>("{%key3%} * {%key2%}")); }
/// <summary> /// Gets information about the available signatures for the given expression. /// </summary> /// <param name="exprText">The expression to get signatures for.</param> /// <param name="location">The location in the file.</param> /// <remarks>New in 2.2</remarks> public IEnumerable<IOverloadResult> GetSignatures(string exprText, SourceLocation location) { try { var scope = FindScope(location); var unit = GetNearestEnclosingAnalysisUnit(scope); var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true); using (var parser = Parser.CreateParser(new StringReader(exprText), _unit.ProjectState.LanguageVersion)) { var expr = GetExpression(parser.ParseTopExpression().Body); if (expr is ListExpression || expr is TupleExpression || expr is DictionaryExpression) { return Enumerable.Empty<IOverloadResult>(); } var lookup = eval.Evaluate(expr); lookup = AnalysisSet.Create(lookup.Where(av => !(av is MultipleMemberInfo)).Concat( lookup.OfType<MultipleMemberInfo>().SelectMany(mmi => mmi.Members) )); var result = new HashSet<OverloadResult>(OverloadResultComparer.Instance); // TODO: Include relevant type info on the parameter... result.UnionWith(lookup // Exclude constant values first time through .Where(av => av.MemberType != PythonMemberType.Constant) .SelectMany(av => av.Overloads ?? Enumerable.Empty<OverloadResult>()) ); if (!result.Any()) { result.UnionWith(lookup .Where(av => av.MemberType == PythonMemberType.Constant) .SelectMany(av => av.Overloads ?? Enumerable.Empty<OverloadResult>())); } return result; } } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } Debug.Fail(ex.ToString()); return GetSignaturesError; } }
public void TestAllowMultipleQuotes() { this.postedData.Add("multiplequotes", @"O''Malley'O'Laughlin"); ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(this.postedData)); Assert.AreEqual("O''Malley'O'Laughlin", evaluator.Evaluate<string>("if('{%multiplequotes%}' != 0, '{%multiplequotes%}', '')")); }
public CountIf(ExpressionEvaluator evaluator) { Require.That(evaluator).Named("evaluator").IsNotNull(); _expressionEvaluator = evaluator; }
public void TestAllowSlashes() { this.postedData.Add("slashes", @"\iApply"); ExpressionEvaluator evaluator = new ExpressionEvaluator(new Application(this.postedData)); Assert.AreEqual(@"\iApply", evaluator.Evaluate<string>("if('{%slashes%}' != 0, '{%slashes%}', '')")); }
public override object Insert <TEntity>(Expression <Func <TEntity> > content, string table) { PublicHelper.CheckNull(content); TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); if (typeDescriptor.PrimaryKeys.Count > 1) { /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */ throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName)); } PropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault(); Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content); DbTable explicitDbTable = null; if (table != null) { explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema); } DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable); DbInsertExpression insertExp = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table); object keyVal = null; foreach (var kv in insertColumns) { MemberInfo key = kv.Key; PropertyDescriptor propertyDescriptor = typeDescriptor.TryGetPropertyDescriptor(key); if (propertyDescriptor == null) { throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name)); } if (propertyDescriptor.IsAutoIncrement) { throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", propertyDescriptor.Column.Name)); } if (propertyDescriptor.HasSequence()) { throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", propertyDescriptor.Column.Name)); } if (propertyDescriptor.IsPrimaryKey) { object val = ExpressionEvaluator.Evaluate(kv.Value); if (val == null) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name)); } else { keyVal = val; insertExp.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType)); continue; } } insertExp.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value)); } foreach (var item in typeDescriptor.PropertyDescriptors.Where(a => a.HasSequence())) { DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(item); insertExp.InsertColumns.Add(item.Column, getNextValueForSequenceExp); } if (keyPropertyDescriptor != null) { //主键为空并且主键又不是自增列 if (keyVal == null && !keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence()) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name)); } } if (keyPropertyDescriptor == null) { this.ExecuteNonQuery(insertExp); return(keyVal); /* It will return null if an entity does not define primary key. */ } if (!keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence()) { this.ExecuteNonQuery(insertExp); return(keyVal); } IDbExpressionTranslator translator = this.DatabaseProvider.CreateDbExpressionTranslator(); List <DbParam> parameters; string sql = translator.Translate(insertExp, out parameters); if (keyPropertyDescriptor.IsAutoIncrement) { /* 自增 id 不能用 output inserted.Id 输出,因为如果表设置了触发器的话会报错 */ sql = string.Concat(sql, ";", this.GetSelectLastInsertIdClause()); } else if (keyPropertyDescriptor.HasSequence()) { insertExp.Returns.Add(keyPropertyDescriptor.Column); } object ret = this.Session.ExecuteScalar(sql, parameters.ToArray()); if (ret == null || ret == DBNull.Value) { throw new ChloeException("Unable to get the identity/sequence value."); } ret = PublicHelper.ConvertObjType(ret, typeDescriptor.AutoIncrement.PropertyType); return(ret); }
public void SetUp() => _sut = new T();
/// <summary>Parses the specified function.</summary> /// <param name="fn">The function.</param> /// <param name="ExpressionProperty">The expression property.</param> private static void Parse(ExpressionEvaluator fn, string ExpressionProperty) { fn.Parse(ExpressionProperty.Trim()); fn.Infix2Postfix(); }
private static bool IsSpecialRequire(AnalysisUnit unit, CallNode n, ref IAnalysisSet res) { bool hitLiteral = false; if (n.Arguments.Length == 1) { var ee = new ExpressionEvaluator(unit); foreach (var name in ee.MergeStringLiterals(n.Arguments[0])) { hitLiteral = true; res = res.Union( unit.Analyzer.Modules.RequireModule( n, unit, name, unit.DeclaringModuleEnvironment.Name ) ); } } return hitLiteral; }
public virtual object Insert <TEntity>(Expression <Func <TEntity> > content, string table) { Utils.CheckNull(content); TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(typeof(TEntity)); if (typeDescriptor.PrimaryKeys.Count > 1) { /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */ throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.EntityType.FullName)); } MappingMemberDescriptor keyMemberDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault(); MappingMemberDescriptor autoIncrementMemberDescriptor = typeDescriptor.AutoIncrement; Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content); DbTable explicitDbTable = null; if (table != null) { explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema); } DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable); DbInsertExpression e = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table); object keyVal = null; foreach (var kv in insertColumns) { MemberInfo key = kv.Key; MappingMemberDescriptor memberDescriptor = typeDescriptor.TryGetMappingMemberDescriptor(key); if (memberDescriptor == null) { throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name)); } if (memberDescriptor == autoIncrementMemberDescriptor) { throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", memberDescriptor.Column.Name)); } if (memberDescriptor.IsPrimaryKey) { object val = ExpressionEvaluator.Evaluate(kv.Value); if (val == null) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", memberDescriptor.MemberInfo.Name)); } else { keyVal = val; e.InsertColumns.Add(memberDescriptor.Column, DbExpression.Parameter(keyVal)); continue; } } e.InsertColumns.Add(memberDescriptor.Column, expressionParser.Parse(kv.Value)); } if (keyMemberDescriptor != null) { //主键为空并且主键又不是自增列 if (keyVal == null && keyMemberDescriptor != autoIncrementMemberDescriptor) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyMemberDescriptor.MemberInfo.Name)); } } if (keyMemberDescriptor == null || keyMemberDescriptor != autoIncrementMemberDescriptor) { this.ExecuteSqlCommand(e); return(keyVal); /* It will return null if an entity does not define primary key. */ } IDbExpressionTranslator translator = this.DbContextServiceProvider.CreateDbExpressionTranslator(); List <DbParam> parameters; string sql = translator.Translate(e, out parameters); sql = string.Concat(sql, ";", this.GetSelectLastInsertIdClause()); //SELECT @@IDENTITY 返回的是 decimal 类型 object retIdentity = this.Session.ExecuteScalar(sql, parameters.ToArray()); if (retIdentity == null || retIdentity == DBNull.Value) { throw new ChloeException("Unable to get the identity value."); } retIdentity = ConvertIdentityType(retIdentity, autoIncrementMemberDescriptor.MemberInfoType); return(retIdentity); }
/// <summary> /// Evaluates a given expression and returns a list of members which /// exist in the expression. /// /// If the expression is an empty string returns all available members /// at that location. /// </summary> /// <param name="exprText">The expression to find members for.</param> /// </param> /// <param name="location"> /// The location in the file where the expression should be evaluated. /// </param> /// <remarks>New in 2.2</remarks> public IEnumerable<MemberResult> GetMembers( string exprText, SourceLocation location, GetMemberOptions options = GetMemberOptions.IntersectMultipleResults ) { if (exprText.Length == 0) { return GetAllAvailableMembers(location, options); } var scope = FindScope(location); var privatePrefix = GetPrivatePrefixClassName(scope); var expr = Statement.GetExpression(GetAstFromText(exprText, privatePrefix).Body); if (expr is ConstantExpression && ((ConstantExpression)expr).Value is int) { // no completions on integer ., the user is typing a float return Enumerable.Empty<MemberResult>(); } var errorWalker = new ErrorWalker(); expr.Walk(errorWalker); if (errorWalker.HasError) { return null; } var unit = GetNearestEnclosingAnalysisUnit(scope); var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true); IAnalysisSet lookup; if (options.HasFlag(GetMemberOptions.NoMemberRecursion)) { lookup = eval.EvaluateNoMemberRecursion(expr); } else { lookup = eval.Evaluate(expr); } return GetMemberResults(lookup, scope, options); }
protected override bool ContextIsSatisfied(ExpressionEvaluator evaluator, TextArea textArea) { return(textArea.Selection.EndPosition.Line != textArea.Selection.StartPosition.Line); }
/// <summary> /// Gets the variables the given expression evaluates to. Variables /// include parameters, locals, and fields assigned on classes, modules /// and instances. /// /// Variables are classified as either definitions or references. Only /// parameters have unique definition points - all other types of /// variables have only one or more references. /// </summary> /// <param name="exprText">The expression to find variables for.</param> /// <param name="location"> /// The location in the file where the expression should be evaluated. /// </param> /// <remarks>New in 2.2</remarks> public VariablesResult GetVariables(string exprText, SourceLocation location) { var scope = FindScope(location); string privatePrefix = GetPrivatePrefixClassName(scope); var ast = GetAstFromText(exprText, privatePrefix); var expr = Statement.GetExpression(ast.Body); var unit = GetNearestEnclosingAnalysisUnit(scope); NameExpression name = expr as NameExpression; IEnumerable<IAnalysisVariable> variables = Enumerable.Empty<IAnalysisVariable>(); if (name != null) { var defScope = scope.EnumerateTowardsGlobal.FirstOrDefault(s => s.ContainsVariable(name.Name) && (s == scope || s.VisibleToChildren || IsFirstLineOfFunction(scope, s, location))); if (defScope == null) { variables = _unit.ProjectState.BuiltinModule.GetDefinitions(name.Name) .SelectMany(ToVariables); } else { variables = GetVariablesInScope(name, defScope).Distinct(); } } else { MemberExpression member = expr as MemberExpression; if (member != null && !string.IsNullOrEmpty(member.Name)) { var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true); var objects = eval.Evaluate(member.Target); foreach (var v in objects) { var container = v as IReferenceableContainer; if (container != null) { variables = ReferencablesToVariables(container.GetDefinitions(member.Name)); break; } } } } return new VariablesResult(variables, ast); }
/// <summary> /// Initializes a new instance of the <see cref="Expression"/> class. /// Expression constructor. /// </summary> /// <param name="evaluator">Information about how to validate and evaluate expression.</param> /// <param name="children">Child expressions.</param> public Expression(ExpressionEvaluator evaluator, params Expression[] children) { Evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator)); Children = children; }