Best Atata code snippet using Atata.ExpressionStringBuilder.ToString
ExpressionStringBuilder.cs
Source:ExpressionStringBuilder.cs
...24 {25 builder = new StringBuilder();26 }2728 public override string ToString()29 {30 return builder.ToString();31 }3233 private void AddLabel(LabelTarget label)34 {35 if (ids == null)36 {37 ids = new Dictionary<object, int>();38 ids.Add(label, 0);39 }40 else41 {42 if (!ids.ContainsKey(label))43 {44 ids.Add(label, ids.Count);45 }46 }47 }4849 protected int GetLabelId(LabelTarget label)50 {51 if (ids == null)52 {53 ids = new Dictionary<object, int>();54 AddLabel(label);55 return 0;56 }57 else58 {59 if (!ids.TryGetValue(label, out int id))60 {61 // label is met the first time62 id = ids.Count;63 AddLabel(label);64 }6566 return id;67 }68 }6970 private void AddParam(ParameterExpression p)71 {72 if (ids == null)73 {74 ids = new Dictionary<object, int>();75 ids.Add(ids, 0);76 }77 else78 {79 if (!ids.ContainsKey(p))80 {81 ids.Add(p, ids.Count);82 }83 }84 }8586 protected int GetParamId(ParameterExpression p)87 {88 if (ids == null)89 {90 ids = new Dictionary<object, int>();91 AddParam(p);92 return 0;93 }94 else95 {96 if (!ids.TryGetValue(p, out int id))97 {98 // p is met the first time99 id = ids.Count;100 AddParam(p);101 }102103 return id;104 }105 }106107 protected virtual void Out(string s)108 {109 builder.Append(s);110 }111112 protected virtual void Out(char c)113 {114 builder.Append(c);115 }116117 /// <summary>118 /// Output a given expression tree to a string.119 /// </summary>120 /// <param name="node">The expression node.</param>121 /// <returns>The string representing the expression.</returns>122 public static string ExpressionToString(Expression node)123 {124 Debug.Assert(node != null, "'node' should not be null.");125126 ExpressionStringBuilder expressionStringBuilder = new ExpressionStringBuilder();127 expressionStringBuilder.Visit(node);128 return expressionStringBuilder.ToString();129 }130131 // More proper would be to make this a virtual method on Action132 private static string FormatBinder(CallSiteBinder binder)133 {134 ConvertBinder convert;135 GetMemberBinder getMember;136 SetMemberBinder setMember;137 DeleteMemberBinder deleteMember;138 InvokeMemberBinder call;139 UnaryOperationBinder unary;140 BinaryOperationBinder binary;141142 if ((convert = binder as ConvertBinder) != null)143 {144 return "Convert " + convert.Type;145 }146 else if ((getMember = binder as GetMemberBinder) != null)147 {148 return "GetMember " + getMember.Name;149 }150 else if ((setMember = binder as SetMemberBinder) != null)151 {152 return "SetMember " + setMember.Name;153 }154 else if ((deleteMember = binder as DeleteMemberBinder) != null)155 {156 return "DeleteMember " + deleteMember.Name;157 }158 else if (binder is GetIndexBinder)159 {160 return "GetIndex";161 }162 else if (binder is SetIndexBinder)163 {164 return "SetIndex";165 }166 else if (binder is DeleteIndexBinder)167 {168 return "DeleteIndex";169 }170 else if ((call = binder as InvokeMemberBinder) != null)171 {172 return "Call " + call.Name;173 }174 else if (binder is InvokeBinder)175 {176 return "Invoke";177 }178 else if (binder is CreateInstanceBinder)179 {180 return "Create";181 }182 else if ((unary = binder as UnaryOperationBinder) != null)183 {184 return unary.Operation.ToString();185 }186 else if ((binary = binder as BinaryOperationBinder) != null)187 {188 return binary.Operation.ToString();189 }190 else191 {192 return "CallSiteBinder";193 }194 }195196 protected void VisitExpressions<T>(char open, IList<T> expressions, char close)197 where T : Expression198 {199 VisitExpressions(open, expressions, close, ", ");200 }201202 private void VisitExpressions<T>(char open, IList<T> expressions, char close, string seperator)203 where T : Expression204 {205 Out(open);206207 if (expressions != null)208 {209 bool isFirst = true;210 foreach (T e in expressions)211 {212 if (isFirst)213 isFirst = false;214 else215 Out(seperator);216217 Visit(e);218 }219 }220221 Out(close);222 }223224 protected override Expression VisitDynamic(DynamicExpression node)225 {226 Out(FormatBinder(node.Binder));227 VisitExpressions('(', node.Arguments, ')');228 return node;229 }230231 protected override Expression VisitBinary(BinaryExpression node)232 {233 if (node.NodeType == ExpressionType.ArrayIndex)234 {235 Visit(node.Left);236 Out("[");237 Visit(node.Right);238 Out("]");239 }240 else241 {242 string operatorString = GetBinaryOperator(node.NodeType);243244 Out("(");245 Visit(node.Left);246 Out(' ');247 Out(operatorString);248 Out(' ');249 Visit(node.Right);250 Out(")");251 }252253 return node;254 }255256 protected virtual string GetBinaryOperator(ExpressionType expressionType)257 {258 switch (expressionType)259 {260 case ExpressionType.AndAlso:261 return "&&";262 case ExpressionType.OrElse:263 return "||";264 case ExpressionType.Assign:265 return "=";266 case ExpressionType.Equal:267 return "==";268 case ExpressionType.NotEqual:269 return "!=";270 case ExpressionType.GreaterThan:271 return ">";272 case ExpressionType.LessThan:273 return "<";274 case ExpressionType.GreaterThanOrEqual:275 return ">=";276 case ExpressionType.LessThanOrEqual:277 return "<=";278 case ExpressionType.Add:279 case ExpressionType.AddChecked:280 return "+";281 case ExpressionType.AddAssign:282 case ExpressionType.AddAssignChecked:283 return "+=";284 case ExpressionType.Subtract:285 case ExpressionType.SubtractChecked:286 return "-";287 case ExpressionType.SubtractAssign:288 case ExpressionType.SubtractAssignChecked:289 return "-=";290 case ExpressionType.Divide:291 return "/";292 case ExpressionType.DivideAssign:293 return "/=";294 case ExpressionType.Modulo:295 return "%";296 case ExpressionType.ModuloAssign:297 return "%=";298 case ExpressionType.Multiply:299 case ExpressionType.MultiplyChecked:300 return "*";301 case ExpressionType.MultiplyAssign:302 case ExpressionType.MultiplyAssignChecked:303 return "*=";304 case ExpressionType.LeftShift:305 return "<<";306 case ExpressionType.LeftShiftAssign:307 return "<<=";308 case ExpressionType.RightShift:309 return ">>";310 case ExpressionType.RightShiftAssign:311 return ">>=";312 case ExpressionType.And:313 return "&";314 case ExpressionType.AndAssign:315 return "&=";316 case ExpressionType.Or:317 return "|";318 case ExpressionType.OrAssign:319 return "|=";320 case ExpressionType.ExclusiveOr:321 case ExpressionType.Power:322 return "^";323 case ExpressionType.ExclusiveOrAssign:324 case ExpressionType.PowerAssign:325 return "^=";326 case ExpressionType.Coalesce:327 return "??";328 default:329 throw new InvalidOperationException();330 }331 }332333 protected override Expression VisitParameter(ParameterExpression node)334 {335 if (node.IsByRef)336 {337 Out("ref ");338 }339340 string name = node.Name;341342 if (string.IsNullOrEmpty(name))343 Out("Param_" + GetParamId(node));344 else345 Out(name);346347 return node;348 }349350 protected override Expression VisitLambda<T>(Expression<T> node)351 {352 if (node.Parameters.Count == 1)353 {354 // p => body355 Visit(node.Parameters[0]);356 }357 else358 {359 // (p1, p2, ..., pn) => body360 VisitExpressions('(', node.Parameters, ')');361 }362363 Out(" => ");364 Visit(node.Body);365 return node;366 }367368 protected override Expression VisitListInit(ListInitExpression node)369 {370 Visit(node.NewExpression);371 Out(" {");372373 for (int i = 0, n = node.Initializers.Count; i < n; i++)374 {375 if (i > 0)376 Out(", ");377378 Out(node.Initializers[i].ToString());379 }380381 Out("}");382 return node;383 }384385 protected override Expression VisitConditional(ConditionalExpression node)386 {387 Out("IIF(");388 Visit(node.Test);389390 Out(", ");391 Visit(node.IfTrue);392393 Out(", ");394 Visit(node.IfFalse);395396 Out(")");397 return node;398 }399400 protected override Expression VisitConstant(ConstantExpression node)401 {402 if (node.Value != null)403 {404 string valueAsString = node.Value.ToString();405 if (node.Value is string)406 {407 Out("\"");408 Out(valueAsString);409 Out("\"");410 }411 else if (valueAsString == node.Value.GetType().ToString())412 {413 Out("value(");414 Out(valueAsString);415 Out(")");416 }417 else418 {419 Out(valueAsString);420 }421 }422 else423 {424 Out("null");425 }426427 return node;428 }429430 protected override Expression VisitDebugInfo(DebugInfoExpression node)431 {432 string s = string.Format(433 CultureInfo.CurrentCulture,434 "<DebugInfo({0}: {1}, {2}, {3}, {4})>",435 node.Document.FileName,436 node.StartLine,437 node.StartColumn,438 node.EndLine,439 node.EndColumn);440441 Out(s);442443 return node;444 }445446 protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node)447 {448 VisitExpressions('(', node.Variables, ')');449 return node;450 }451452 // Prints ".instanceField" or "declaringType.staticField"453 protected virtual void OutMember(Expression instance, MemberInfo member)454 {455 if (instance != null)456 {457 Visit(instance);458 Out("." + member.Name);459 }460 else461 {462 // For static members, include the type name463 Out(member.DeclaringType.Name + "." + member.Name);464 }465 }466467 protected override Expression VisitMember(MemberExpression node)468 {469 OutMember(node.Expression, node.Member);470 return node;471 }472473 protected override Expression VisitMemberInit(MemberInitExpression node)474 {475 if (node.NewExpression.Arguments.Count == 0 &&476 node.NewExpression.Type.Name.Contains("<"))477 {478 // anonymous type constructor479 Out("new");480 }481 else482 {483 Visit(node.NewExpression);484 }485486 Out(" {");487488 for (int i = 0, n = node.Bindings.Count; i < n; i++)489 {490 MemberBinding b = node.Bindings[i];491 if (i > 0)492 {493 Out(", ");494 }495496 VisitMemberBinding(b);497 }498499 Out("}");500 return node;501 }502503 protected override MemberAssignment VisitMemberAssignment(MemberAssignment node)504 {505 Out(node.Member.Name);506 Out(" = ");507 Visit(node.Expression);508 return node;509 }510511 protected override MemberListBinding VisitMemberListBinding(MemberListBinding node)512 {513 Out(node.Member.Name);514 Out(" = {");515516 for (int i = 0, n = node.Initializers.Count; i < n; i++)517 {518 if (i > 0)519 {520 Out(", ");521 }522523 VisitElementInit(node.Initializers[i]);524 }525526 Out("}");527 return node;528 }529530 protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node)531 {532 Out(node.Member.Name);533 Out(" = {");534 for (int i = 0, n = node.Bindings.Count; i < n; i++)535 {536 if (i > 0)537 Out(", ");538539 VisitMemberBinding(node.Bindings[i]);540 }541542 Out("}");543 return node;544 }545546 protected override ElementInit VisitElementInit(ElementInit node)547 {548 Out(node.AddMethod.ToString());549 string sep = ", ";550551 VisitExpressions('(', node.Arguments, ')', sep);552 return node;553 }554555 protected override Expression VisitInvocation(InvocationExpression node)556 {557 Out("Invoke(");558 Visit(node.Expression);559 string sep = ", ";560561 for (int i = 0, n = node.Arguments.Count; i < n; i++)562 {563 Out(sep);564 Visit(node.Arguments[i]);565 }566567 Out(")");568 return node;569 }570571 protected override Expression VisitMethodCall(MethodCallExpression node)572 {573 int start = 0;574 Expression objectExpression = node.Object;575576 if (Attribute.GetCustomAttribute(node.Method, typeof(ExtensionAttribute)) != null)577 {578 start = 1;579 objectExpression = node.Arguments[0];580 }581582 if (objectExpression != null)583 {584 Visit(objectExpression);585 Out(".");586 }587588 Out(node.Method.Name);589 Out("(");590591 VisitMethodParameters(node, start);592593 Out(")");594 return node;595 }596597 protected virtual Expression VisitMethodParameters(MethodCallExpression node, int startArgumentIndex)598 {599 for (int i = startArgumentIndex, n = node.Arguments.Count; i < n; i++)600 {601 if (i > startArgumentIndex)602 Out(", ");603604 Visit(node.Arguments[i]);605 }606607 return node;608 }609610 protected override Expression VisitNewArray(NewArrayExpression node)611 {612 if (node.NodeType == ExpressionType.NewArrayBounds)613 {614 Out("new " + node.Type);615 VisitExpressions('(', node.Expressions, ')');616 }617 else if (node.NodeType == ExpressionType.NewArrayInit)618 {619 Out("new [] ");620 VisitExpressions('{', node.Expressions, '}');621 }622623 return node;624 }625626 protected override Expression VisitNew(NewExpression node)627 {628 Out("new " + node.Type.Name);629 Out("(");630 var members = node.Members;631 for (int i = 0; i < node.Arguments.Count; i++)632 {633 if (i > 0)634 {635 Out(", ");636 }637638 if (members != null)639 {640 string name = members[i].Name;641642 Out(name);643 Out(" = ");644 }645646 Visit(node.Arguments[i]);647 }648649 Out(")");650 return node;651 }652653 protected override Expression VisitTypeBinary(TypeBinaryExpression node)654 {655 Out("(");656 Visit(node.Expression);657658 if (node.NodeType == ExpressionType.TypeIs)659 Out(" is ");660 else if (node.NodeType == ExpressionType.TypeEqual)661 Out(" TypeEqual ");662663 Out(node.TypeOperand.Name);664 Out(")");665 return node;666 }667668 protected override Expression VisitUnary(UnaryExpression node)669 {670 switch (node.NodeType)671 {672 case ExpressionType.TypeAs:673 Out("(");674 break;675 case ExpressionType.Not:676 if (node.Type == typeof(bool) || node.Type == typeof(bool?))677 Out("!");678 else679 Out("~");680 break;681 case ExpressionType.Negate:682 case ExpressionType.NegateChecked:683 Out("-");684 break;685 case ExpressionType.UnaryPlus:686 Out("+");687 break;688 case ExpressionType.Quote:689 break;690 case ExpressionType.Throw:691 Out("throw(");692 break;693 case ExpressionType.Increment:694 Out("Increment(");695 break;696 case ExpressionType.Decrement:697 Out("Decrement(");698 break;699 case ExpressionType.PreIncrementAssign:700 Out("++");701 break;702 case ExpressionType.PreDecrementAssign:703 Out("--");704 break;705 case ExpressionType.OnesComplement:706 Out("~(");707 break;708 default:709 Out(node.NodeType.ToString());710 Out("(");711 break;712 }713714 Visit(node.Operand);715716 switch (node.NodeType)717 {718 case ExpressionType.Not:719 case ExpressionType.Negate:720 case ExpressionType.NegateChecked:721 case ExpressionType.UnaryPlus:722 case ExpressionType.PreDecrementAssign:723 case ExpressionType.PreIncrementAssign:724 case ExpressionType.Quote:725 break;726 case ExpressionType.TypeAs:727 Out(" as ");728 Out(node.Type.Name);729 Out(")");730 break;731 case ExpressionType.PostIncrementAssign:732 Out("++");733 break;734 case ExpressionType.PostDecrementAssign:735 Out("--");736 break;737 default:738 Out(")");739 break;740 }741742 return node;743 }744745 protected override Expression VisitBlock(BlockExpression node)746 {747 Out("{");748749 foreach (var v in node.Variables)750 {751 Out("var ");752 Visit(v);753 Out(";");754 }755756 Out(" ... }");757 return node;758 }759760 protected override Expression VisitDefault(DefaultExpression node)761 {762 Out("default(");763 Out(node.Type.Name);764 Out(")");765 return node;766 }767768 protected override Expression VisitLabel(LabelExpression node)769 {770 Out("{ ... } ");771 DumpLabel(node.Target);772 Out(":");773 return node;774 }775776 protected override Expression VisitGoto(GotoExpression node)777 {778 Out(node.Kind.ToString().ToLower(CultureInfo.CurrentCulture));779 DumpLabel(node.Target);780781 if (node.Value != null)782 {783 Out(" (");784 Visit(node.Value);785 Out(") ");786 }787788 return node;789 }790791 protected override Expression VisitLoop(LoopExpression node)792 {793 Out("loop { ... }");794 return node;795 }796797 protected override SwitchCase VisitSwitchCase(SwitchCase node)798 {799 Out("case ");800 VisitExpressions('(', node.TestValues, ')');801 Out(": ...");802 return node;803 }804805 protected override Expression VisitSwitch(SwitchExpression node)806 {807 Out("switch ");808 Out("(");809 Visit(node.SwitchValue);810 Out(") { ... }");811 return node;812 }813814 protected override CatchBlock VisitCatchBlock(CatchBlock node)815 {816 Out("catch (" + node.Test.Name);817818 if (node.Variable != null)819 Out(node.Variable.Name ?? string.Empty);820821 Out(") { ... }");822 return node;823 }824825 protected override Expression VisitTry(TryExpression node)826 {827 Out("try { ... }");828 return node;829 }830831 protected override Expression VisitIndex(IndexExpression node)832 {833 if (node.Object != null)834 {835 Visit(node.Object);836 }837 else838 {839 Debug.Assert(node.Indexer != null, "'node.Indexer' should not be null.");840 Out(node.Indexer.DeclaringType.Name);841 }842843 if (node.Indexer != null)844 {845 Out(".");846 Out(node.Indexer.Name);847 }848849 VisitExpressions('[', node.Arguments, ']');850 return node;851 }852853 protected override Expression VisitExtension(Expression node)854 {855 // Prefer an overriden ToString, if available.856 var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.ExactBinding;857 var toString = node.GetType().GetMethod("ToString", flags, null, Type.EmptyTypes, null);858 if (toString.DeclaringType != typeof(Expression))859 {860 Out(node.ToString());861 return node;862 }863864 Out("[");865866 // For 3.5 subclasses, print the NodeType.867 // For Extension nodes, print the class name.868 if (node.NodeType == ExpressionType.Extension)869 {870 Out(node.GetType().FullName);871 }872 else873 {874 Out(node.NodeType.ToString());875 }876877 Out("]");878 return node;879 }880881 private void DumpLabel(LabelTarget target)882 {883 if (!string.IsNullOrEmpty(target.Name))884 {885 Out(target.Name);886 }887 else888 {
...
ImprovedExpressionStringBuilder.cs
Source:ImprovedExpressionStringBuilder.cs
...38 /// Outputs a given expression tree to a string.39 /// </summary>40 /// <param name="node">The expression node.</param>41 /// <returns>The string representing the expression.</returns>42 public static new string ExpressionToString(Expression node)43 {44 node.CheckNotNull(nameof(node));45 var expressionStringBuilder = new ImprovedExpressionStringBuilder(node is LambdaExpression);46 try47 {48 expressionStringBuilder.Visit(node);49 return expressionStringBuilder.ToString();50 }51 catch52 {53 return node.ToString();54 }55 }56 protected override void Out(string s)57 {58 CurrentLiteral.Append(s);59 }60 protected override void Out(char c)61 {62 CurrentLiteral.Append(c);63 }64 private static bool CanStringifyValue(Type valueType)65 {66 Type underlyingType = Nullable.GetUnderlyingType(valueType) ?? valueType;67 return s_expressionValueStringifiers.Any(x => x.CanHandle(underlyingType));68 }69 private static bool TryStringifyValue(object value, Type valueType, out string result)70 {71 if (value is null)72 {73 result = "null";74 return true;75 }76 Type underlyingType = Nullable.GetUnderlyingType(valueType) ?? valueType;77 var stringifier = s_expressionValueStringifiers.FirstOrDefault(x => x.CanHandle(underlyingType));78 if (stringifier != null)79 {80 try81 {82 result = stringifier.Handle(value);83 return true;84 }85 catch86 {87 // Do nothing here, just return false.88 }89 }90 result = null;91 return false;92 }93 protected override Expression VisitLambda<T>(Expression<T> node)94 {95 if (_expectLambdaVisit)96 {97 _expectLambdaVisit = false;98 }99 else100 {101 LambdaExpressionPart newLambda = new LambdaExpressionPart(CurrentLambda);102 CurrentLambda.Body.StartLambda(newLambda);103 CurrentLiteral = newLambda.Parameters;104 CurrentLambda = newLambda;105 }106 if (node.Parameters.Count == 1)107 Visit(node.Parameters[0]);108 else109 VisitExpressions('(', node.Parameters, ')');110 CurrentLiteral = CurrentLambda.Body.StartNewLiteral();111 Visit(node.Body);112 if (CurrentLambda.Parent != null)113 {114 CurrentLambda = CurrentLambda.Parent;115 CurrentLiteral = CurrentLambda.Body.StartNewLiteral();116 }117 return node;118 }119 protected override Expression VisitMember(MemberExpression node)120 {121 if (node.Member is FieldInfo)122 {123 if (CanStringifyValue(node.Type))124 {125 object value = Expression.Lambda(node).Compile().DynamicInvoke();126 if (TryStringifyValue(value, node.Type, out string valueAsString))127 {128 Out(valueAsString);129 return node;130 }131 }132 Out(node.Member.Name);133 return node;134 }135 return base.VisitMember(node);136 }137 private bool IsParameterExpression(Expression expression)138 {139 if (expression is ParameterExpression)140 return true;141 else if (expression is MemberExpression memberExpression)142 return IsParameterExpression(memberExpression.Expression);143 else144 return false;145 }146 protected override Expression VisitMemberInit(MemberInitExpression node)147 {148 VisitNewKnownType(node.NewExpression, alwaysAddParentheses: false);149 Out(" { ");150 for (int i = 0, n = node.Bindings.Count; i < n; i++)151 {152 if (i > 0)153 Out(", ");154 VisitMemberBinding(node.Bindings[i]);155 }156 Out(" }");157 return node;158 }159 protected override Expression VisitMethodCall(MethodCallExpression node)160 {161 bool isExtensionMethod = Attribute.GetCustomAttribute(node.Method, typeof(ExtensionAttribute)) != null;162 if (node.Method.IsStatic && !isExtensionMethod && node.Method.DeclaringType != typeof(object))163 {164 OutStaticClass(node.Method.DeclaringType);165 }166 else if (IsIndexer(node))167 {168 if (node.Object != null)169 Visit(node.Object);170 return VisitIndexerAsMethodCall(node);171 }172 return base.VisitMethodCall(node);173 }174 protected static bool IsIndexer(MethodCallExpression node) =>175 node.Method.IsSpecialName && (node.Method.Name == "get_Item" || node.Method.Name == "get_Chars") && node.Arguments.Any();176 protected Expression VisitIndexerAsMethodCall(MethodCallExpression node)177 {178 Out("[");179 for (int i = 0; i < node.Arguments.Count; i++)180 {181 if (i > 0)182 Out(", ");183 Visit(node.Arguments[i]);184 }185 Out("]");186 return node;187 }188 private void OutStaticClass(Type type)189 {190 if (type.DeclaringType != null)191 OutStaticClass(type.DeclaringType);192 Out(type.Name);193 Out(".");194 }195 protected override Expression VisitMethodParameters(MethodCallExpression node, int startArgumentIndex)196 {197 ParameterInfo[] methodParameters = node.Method.GetParameters();198 for (int i = startArgumentIndex; i < node.Arguments.Count; i++)199 {200 if (i > startArgumentIndex)201 Out(", ");202 ParameterInfo parameter = methodParameters[i];203 VisitMethodParameter(parameter, node.Arguments[i]);204 }205 return node;206 }207 private void VisitMethodParameter(ParameterInfo parameter, Expression argumentExpression)208 {209 if (argumentExpression is MemberExpression memberExpression && memberExpression.Member is FieldInfo)210 {211 if (parameter.IsOut)212 {213 Out($"out {memberExpression.Member.Name}");214 return;215 }216 else if (parameter.ParameterType.IsByRef)217 {218 Out($"ref {memberExpression.Member.Name}");219 return;220 }221 }222 Visit(argumentExpression);223 }224 protected override Expression VisitNewArray(NewArrayExpression node)225 {226 if (node.NodeType == ExpressionType.NewArrayInit)227 {228 Out("new[] ");229 VisitExpressions('{', node.Expressions, '}');230 return node;231 }232 return base.VisitNewArray(node);233 }234 protected override Expression VisitNew(NewExpression node)235 {236 return node.Type.Name.StartsWith("<>", StringComparison.Ordinal)237 ? VisitNewAnonymousType(node)238 : VisitNewKnownType(node);239 }240 private Expression VisitNewKnownType(NewExpression node, bool alwaysAddParentheses = true)241 {242 Out("new " + node.Type.Name);243 bool addParentheses = alwaysAddParentheses || node.Arguments.Count > 0;244 if (addParentheses)245 Out("(");246 OutArguments(node.Arguments, node.Members);247 if (addParentheses)248 Out(")");249 return node;250 }251 private Expression VisitNewAnonymousType(NewExpression node)252 {253 Out("new { ");254 if (node.Arguments.Count > 0)255 {256 OutArguments(node.Arguments, node.Members);257 Out(" ");258 }259 Out("}");260 return node;261 }262 private void OutArguments(ReadOnlyCollection<Expression> argumentExpressions, ReadOnlyCollection<MemberInfo> members)263 {264 for (int i = 0; i < argumentExpressions.Count; i++)265 {266 if (i > 0)267 Out(", ");268 if (members != null)269 {270 Out(members[i].Name);271 Out(" = ");272 }273 Visit(argumentExpressions[i]);274 }275 }276 protected override Expression VisitBinary(BinaryExpression node)277 {278 if (node.NodeType == ExpressionType.AndAlso)279 CurrentLambda.Body.OperatorAndCount++;280 if (node.NodeType == ExpressionType.OrElse)281 CurrentLambda.Body.OperatorElseCount++;282 if (IsEnumComparison(node))283 return VisitEnumComparison(node);284 if (IsCharComparison(node))285 return VisitComparisonWithConvert(node, x => $"'{Convert.ToChar(x)}'");286 return base.VisitBinary(node);287 }288 private static bool IsCharComparison(BinaryExpression node) =>289 node.NodeType != ExpressionType.ArrayIndex && (IsCharComparison(node.Left, node.Right) || IsCharComparison(node.Right, node.Left));290 private static bool IsCharComparison(Expression left, Expression right) =>291 left.NodeType == ExpressionType.Convert292 && left.Type == typeof(int)293 && (left as UnaryExpression)?.Operand?.Type == typeof(char)294 && right.NodeType == ExpressionType.Constant295 && right.Type == typeof(int);296 private static bool IsEnumComparison(BinaryExpression node) =>297 node.NodeType != ExpressionType.ArrayIndex && (IsEnumComparison(node.Left, node.Right) || IsEnumComparison(node.Right, node.Left));298 private static bool IsEnumComparison(Expression left, Expression right) =>299 left.NodeType == ExpressionType.Convert300 && left.Type.IsPrimitive301 && left.Type == right.Type302 && ((left as UnaryExpression)?.Operand.Type.IsEnum ?? false)303 && right.NodeType == ExpressionType.Constant;304 private Expression VisitEnumComparison(BinaryExpression node)305 {306 Type enumType = ((node.Left as UnaryExpression) ?? (node.Right as UnaryExpression))?.Operand.Type;307 return VisitComparisonWithConvert(308 node,309 x => ((Enum)Enum.ToObject(enumType, x)).ToExpressionValueString(wrapCombinationalValueWithParentheses: true));310 }311 private Expression VisitComparisonWithConvert(BinaryExpression node, Func<object, string> valueConverter)312 {313 void OutPart(Expression part)314 {315 if (part is ConstantExpression constantExpression)316 Out(valueConverter.Invoke(constantExpression.Value));317 else318 Visit(part);319 }320 Out('(');321 OutPart(node.Left);322 Out(' ');323 Out(GetBinaryOperator(node.NodeType));324 Out(' ');325 OutPart(node.Right);326 Out(')');327 return node;328 }329 protected override Expression VisitUnary(UnaryExpression node)330 {331 switch (node.NodeType)332 {333 case ExpressionType.Convert:334 case ExpressionType.ConvertChecked:335 Visit(node.Operand);336 return node;337 default:338 return base.VisitUnary(node);339 }340 }341 protected override Expression VisitConstant(ConstantExpression node)342 {343 if (TryStringifyValue(node.Value, node.Type, out string valueAsString))344 {345 Out(valueAsString);346 return node;347 }348 return base.VisitConstant(node);349 }350 public override string ToString()351 {352 return CurrentLambda.ToString();353 }354 }355}...
ObjectExpressionStringBuilder.cs
Source:ObjectExpressionStringBuilder.cs
...17 /// Outputs a given expression tree to a string.18 /// </summary>19 /// <param name="node">The expression node.</param>20 /// <returns>The string representing the expression.</returns>21 public static new string ExpressionToString(Expression node)22 {23 node.CheckNotNull(nameof(node));24 var expressionStringBuilder = new ObjectExpressionStringBuilder(node is LambdaExpression);25 try26 {27 expressionStringBuilder.Visit(node);28 return expressionStringBuilder.CurrentLambda.Body.ToString();29 }30 catch31 {32 return node.ToString();33 }34 }35 protected override Expression VisitMember(MemberExpression node)36 {37 if (node.NodeType == ExpressionType.MemberAccess && node.Expression?.NodeType == ExpressionType.Parameter)38 {39 Out(node.Member.Name);40 return node;41 }42 else43 {44 return base.VisitMember(node);45 }46 }...
ToString
Using AI Code Generation
1using Atata;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8 {9 static void Main(string[] args)10 {11 string expression = new Atata.ExpressionStringBuilder().Append(x => x.FirstName).ToString();12 Console.WriteLine(expression);13 Console.ReadLine();14 }15 }16}
ToString
Using AI Code Generation
1using System;2using System.Linq.Expressions;3{4 {5 public static string ToString<T>(Expression<Func<T>> expression)6 {7 return expression.Body.ToString();8 }9 }10}11using System;12using System.Linq.Expressions;13{14 {15 public static string ToString<T>(Expression<Func<T>> expression)16 {17 return expression.Body.ToString();18 }19 }20}21using System;22using System.Linq.Expressions;23{24 {25 public static string ToString<T>(Expression<Func<T>> expression)26 {27 return expression.Body.ToString();28 }29 }30}31using System;32using System.Linq.Expressions;33{34 {35 public static string ToString<T>(Expression<Func<T>> expression)36 {37 return expression.Body.ToString();38 }39 }40}41using System;42using System.Linq.Expressions;43{44 {45 public static string ToString<T>(Expression<Func<T>> expression)46 {47 return expression.Body.ToString();48 }49 }50}51using System;52using System.Linq.Expressions;53{54 {55 public static string ToString<T>(Expression<Func<T>> expression)56 {57 return expression.Body.ToString();58 }59 }60}61using System;62using System.Linq.Expressions;63{64 {65 public static string ToString<T>(Expression<Func<T>> expression)66 {67 return expression.Body.ToString();68 }69 }70}71using System;72using System.Linq.Expressions;73{74 {
ToString
Using AI Code Generation
1{2 public static void Main()3 {4 Atata.ExpressionStringBuilder builder = new Atata.ExpressionStringBuilder();5 builder.Append("Hello");6 builder.Append("World");7 Console.WriteLine(builder.ToString());8 }9}10{11 public static void Main()12 {13 Atata.ExpressionStringBuilder builder = new Atata.ExpressionStringBuilder();14 builder.Append("Hello");15 builder.Append("World");16 builder.Append("Bye");17 Console.WriteLine(builder.ToString());18 }19}20{21 public static void Main()22 {23 Atata.ExpressionStringBuilder builder = new Atata.ExpressionStringBuilder();24 builder.Append("Hello");25 builder.Append("World");26 builder.Append("Bye");27 builder.Append("Bye");28 Console.WriteLine(builder.ToString());29 }30}31{32 public static void Main()33 {34 Atata.ExpressionStringBuilder builder = new Atata.ExpressionStringBuilder();35 builder.Append("Hello");36 builder.Append("World");37 builder.Append("Bye");38 builder.Append("Bye");39 builder.Append("Bye");40 Console.WriteLine(builder.ToString());41 }42}43{44 public static void Main()45 {46 Atata.ExpressionStringBuilder builder = new Atata.ExpressionStringBuilder();47 builder.Append("Hello");48 builder.Append("World");49 builder.Append("Bye");50 builder.Append("Bye");51 builder.Append("Bye");52 builder.Append("Bye");53 Console.WriteLine(builder.ToString());54 }55}56{57 public static void Main()58 {59 Atata.ExpressionStringBuilder builder = new Atata.ExpressionStringBuilder();60 builder.Append("Hello");61 builder.Append("World");62 builder.Append("Bye");63 builder.Append("Bye");64 builder.Append("Bye");65 builder.Append("Bye");66 builder.Append("Bye");67 Console.WriteLine(builder.ToString());68 }69}
ToString
Using AI Code Generation
1using Atata;2using NUnit.Framework;3{4 {5 public void TestMethod()6 {7 var expression = new Atata.ExpressionStringBuilder();8 expression.Append("Hello");9 expression.Append("World");10 Assert.That(expression.ToString(), Is.EqualTo("HelloWorld"));11 }12 }13}14using Atata;15using NUnit.Framework;16{17 {18 public void TestMethod()19 {20 var expression = new Atata.ExpressionStringBuilder();21 expression.Append("Hello");22 expression.Append("World");23 Assert.That(expression.ToString(), Is.EqualTo("HelloWorld"));24 }25 }26}27using Atata;28using NUnit.Framework;29{30 {31 public void TestMethod()32 {33 var expression = new Atata.ExpressionStringBuilder();34 expression.Append("Hello");35 expression.Append("World");36 Assert.That(expression.ToString(), Is.EqualTo("HelloWorld"));37 }38 }39}40using Atata;41using NUnit.Framework;42{43 {44 public void TestMethod()45 {46 var expression = new Atata.ExpressionStringBuilder();47 expression.Append("Hello");48 expression.Append("World");49 Assert.That(expression.ToString(), Is.EqualTo("HelloWorld"));50 }51 }52}53using Atata;54using NUnit.Framework;55{56 {57 public void TestMethod()58 {59 var expression = new Atata.ExpressionStringBuilder();60 expression.Append("Hello");61 expression.Append("World");62 Assert.That(expression.ToString(), Is.EqualTo("HelloWorld"));63 }64 }65}66using Atata;67using NUnit.Framework;68{69 {70 public void TestMethod()
ToString
Using AI Code Generation
1using Atata;2using NUnit.Framework;3{4 {5 public void _2()6 {7 var expression = new Atata.ExpressionStringBuilder().Append(x => x.Header.Text.Contains("Example"));8 Assert.That(expression.ToString(), Is.EqualTo("Header.Text.Contains(\"Example\")"));9 }10 }11}12using Atata;13using NUnit.Framework;14{15 {16 public void _3()17 {18 var expression = new Atata.ExpressionStringBuilder().Append(x => x.Header.Text.Contains("Example"));19 Assert.That(expression.ToString(), Is.EqualTo("Header.Text.Contains(\"Example\")"));20 }21 }22}23using Atata;24using NUnit.Framework;25{26 {27 public void _4()28 {29 var expression = new Atata.ExpressionStringBuilder().Append(x => x.Header.Text.Contains("Example"));30 Assert.That(expression.ToString(), Is.EqualTo("Header.Text.Contains(\"Example\")"));31 }32 }33}34using Atata;35using NUnit.Framework;36{37 {38 public void _5()39 {40 var expression = new Atata.ExpressionStringBuilder().Append(x => x.Header.Text.Contains("Example"));41 Assert.That(expression.ToString(), Is.EqualTo("Header.Text.Contains(\"Example\")"));42 }43 }44}45using Atata;46using NUnit.Framework;47{48 {49 public void _6()50 {51 var expression = new Atata.ExpressionStringBuilder().Append(x => x.Header.Text.Contains("Example"));52 Assert.That(expression.ToString(), Is.EqualTo("Header.Text.Contains(\"Example\")"));53 }54 }55}56using Atata;57using NUnit.Framework;58{59 {
ToString
Using AI Code Generation
1using System;2using System.Linq.Expressions;3using Atata;4{5 {6 public static string ToString<T>(this Expression<Func<T>> expression)7 {8 return new ExpressionStringBuilder().Append(expression).ToString();9 }10 }11}12using System;13using System.Linq.Expressions;14using Atata;15using AtataSamples;16{17 {18 public static ControlList<Control<_>, _> Items { get; private set; }19 }20}21using System;22using System.Linq.Expressions;23using Atata;24using AtataSamples;25{26 {27 public static ControlList<Control<_>, _> Items { get; private set; }28 }29}30using System;31using System.Linq.Expressions;32using Atata;33using AtataSamples;34{35 {36 public static ControlList<Control<_>, _> Items { get; private set; }37 }38}39using System;40using System.Linq.Expressions;41using Atata;42using AtataSamples;43{44 {45 public static ControlList<Control<_>, _> Items { get; private set; }46 }47}48using System;49using System.Linq.Expressions;50using Atata;51using AtataSamples;52{53 {54 public static ControlList<Control<_>, _> Items { get; private set; }55 }56}57using System;58using System.Linq.Expressions;59using Atata;60using AtataSamples;61{62 {63 public static ControlList<Control<_>, _> Items { get; private set; }64 }65}66using System;67using System.Linq.Expressions;68using Atata;69using AtataSamples;70{71 {72 public static ControlList<Control<_>, _> Items { get;
ToString
Using AI Code Generation
1var builder = new Atata.ExpressionStringBuilder();2var expression = builder.Build(x => x.Content.Contains("text"));3Console.WriteLine(expression);4var builder = new Atata.ExpressionStringBuilder();5var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2"));6Console.WriteLine(expression);7var builder = new Atata.ExpressionStringBuilder();8var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2").Or.Contains("text3"));9Console.WriteLine(expression);10var builder = new Atata.ExpressionStringBuilder();11var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2").Or.Contains("text3").And.Contains("text4"));12Console.WriteLine(expression);13var builder = new Atata.ExpressionStringBuilder();14var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2").Or.Contains("text3").And.Contains("text4").Or.Contains("text5"));15Console.WriteLine(expression);16var builder = new Atata.ExpressionStringBuilder();17var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2").Or.Contains("text3").And.Contains("text4").Or.Contains("text5").And.Contains("text6"));18Console.WriteLine(expression);
ToString
Using AI Code Generation
1using System;2using System.Linq.Expressions;3using Atata;4{5 {6 static void Main()7 {8 ParameterExpression x = Expression.Parameter(typeof(int), "x");9 ParameterExpression y = Expression.Parameter(typeof(int), "y");10 BinaryExpression add = Expression.Add(x, y);11 BinaryExpression sub = Expression.Subtract(x, y);12 BinaryExpression mul = Expression.Multiply(x, y);13 BinaryExpression div = Expression.Divide(x, y);14 Expression<Func<int, int, string>> expr = Expression.Lambda<Func<int, int, string>>(15 Expression.Block(16 new[] { x, y },17 Expression.Assign(x, Expression.Constant(1)),18 Expression.Assign(y, Expression.Constant(2)),19 Expression.Call(20 typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }),21 Expression.Add(22 Expression.Add(23 Expression.Add(24 Expression.Call(25 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),26 Expression.Constant(" + ")),27 Expression.Call(28 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),29 Expression.Constant(" = "))),30 Expression.Call(31 typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }),32 Expression.Add(33 Expression.Add(34 Expression.Add(35 Expression.Call(36 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),37 Expression.Constant(" * ")),38 Expression.Call(39 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),40 Expression.Constant(" = "))),41 Expression.Call(42 typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }),43 Expression.Constant("Press any key to continue...")),44 Expression.Call(45 typeof(Console).GetMethod("ReadLine")),46 Expression.Constant("Done")));47 string str = Atata.ExpressionStringBuilder.ToString(expr);48 Console.WriteLine(str);
ToString
Using AI Code Generation
1using Atata;2var xpath = new Atata.ExpressionStringBuilder()3 .Add("div")4 .Add("span", x => x.Content == "Some text")5 .ToString();6using Atata;7var xpath = new Atata.ExpressionStringBuilder()8 .Add("div")9 .Add("span", x => x.Content == "Some text")10 .Add("div", x => x.Attribute("class") == "some-class")11 .Add("input", x => x.Attribute("type") == "text")12 .ToString();13using Atata;14var xpath = new Atata.ExpressionStringBuilder()15 .Add("div")16 .Add("span", x => x.Content == "Some text")17 .Add("div", x => x.Attribute("class") == "some-class")18 .Add("input", x => x.Attribute("type") == "text")19 .Add("div", x => x.Attribute("class") == "some-class")20 .ToString();21using Atata;22var xpath = new Atata.ExpressionStringBuilder()23 .Add("div")24 .Add("span", x => x.Content == "Some text")25 .Add("div", x => x.Attribute("class") == "some-class")26 .Add("input", x => x.Attribute("type") == "text")27 .Add("div", x => x.Attribute("class") == "some-class")28 .Add("div", x => x.Attribute("class") == "some-class")29 .ToString();30using Atata;31var xpath = new Atata.ExpressionStringBuilder()32 .Add("div")33 .Add("span", x => x.Content == "Some text")34 .Add("div", x => x.Attribute35Console.WriteLine(expression);36var builder = new Atata.ExpressionStringBuilder();37var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2").Or.Contains("text3").And.Contains("text4"));38Console.WriteLine(expression);39var builder = new Atata.ExpressionStringBuilder();40var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2").Or.Contains("text3").And.Contains("text4").Or.Contains("text5"));41Console.WriteLine(expression);42var builder = new Atata.ExpressionStringBuilder();43var expression = builder.Build(x => x.Content.Contains("text").And.Contains("text2").Or.Contains("text3").And.Contains("text4").Or.Contains("text5").And.Contains("text6"));44Console.WriteLine(expression);
ToString
Using AI Code Generation
1using System;2using System.Linq.Expressions;3using Atata;4{5 {6 static void Main()7 {8 ParameterExpression x = Expression.Parameter(typeof(int), "x");9 ParameterExpression y = Expression.Parameter(typeof(int), "y");10 BinaryExpression add = Expression.Add(x, y);11 BinaryExpression sub = Expression.Subtract(x, y);12 BinaryExpression mul = Expression.Multiply(x, y);13 BinaryExpression div = Expression.Divide(x, y);14 Expression<Func<int, int, string>> expr = Expression.Lambda<Func<int, int, string>>(15 Expression.Block(16 new[] { x, y },17 Expression.Assign(x, Expression.Constant(1)),18 Expression.Assign(y, Expression.Constant(2)),19 Expression.Call(20 typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }),21 Expression.Add(22 Expression.Add(23 Expression.Add(24 Expression.Call(25 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),26 Expression.Constant(" + ")),27 Expression.Call(28 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),29 Expression.Constant(" = "))),30 Expression.Call(31 typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }),32 Expression.Add(33 Expression.Add(34 Expression.Add(35 Expression.Call(36 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),37 Expression.Constant(" * ")),38 Expression.Call(39 typeof(Convert).GetMethod("ToString", new[] { typeof(int) }),40 Expression.Constant(" = "))),41 Expression.Call(42 typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }),43 Expression.Constant("Press any key to continue...")),44 Expression.Call(45 typeof(Console).GetMethod("ReadLine")),46 Expression.Constant("Done")));47 string str = Atata.ExpressionStringBuilder.ToString(expr);48 Console.WriteLine(str);
ToString
Using AI Code Generation
1using Atata;2var xpath = new Atata.ExpressionStringBuilder()3 .Add("div")4 .Add("span", x => x.Content == "Some text")5 .ToString();6using Atata;7var xpath = new Atata.ExpressionStringBuilder()8 .Add("div")9 .Add("span", x => x.Content == "Some text")10 .Add("div", x => x.Attribute("class") == "some-class")11 .Add("input", x => x.Attribute("type") == "text")12 .ToString();13using Atata;14var xpath = new Atata.ExpressionStringBuilder()15 .Add("div")16 .Add("span", x => x.Content == "Some text")17 .Add("div", x => x.Attribute("class") == "some-class")18 .Add("input", x => x.Attribute("type") == "text")19 .Add("div", x => x.Attribute("class") == "some-class")20 .ToString();21using Atata;22var xpath = new Atata.ExpressionStringBuilder()23 .Add("div")24 .Add("span", x => x.Content == "Some text")25 .Add("div", x => x.Attribute("class") == "some-class")26 .Add("input", x => x.Attribute("type") == "text")27 .Add("div", x => x.Attribute("class") == "some-class")28 .Add("div", x => x.Attribute("class") == "some-class")29 .ToString();30using Atata;31var xpath = new Atata.ExpressionStringBuilder()32 .Add("div")33 .Add("span", x => x.Content == "Some text")34 .Add("div", x => x.Attribute
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!