├── .gitignore ├── AssemblyInfo.cs ├── BracketedExpressionToken.cs ├── CommaExpressionToken.cs ├── CompositeExpressionToken.cs ├── ExpressionFormatter.csproj ├── ExpressionFormatter.sln ├── ExpressionToken.cs ├── Extensions.cs ├── LICENSE ├── LeafExpressionToken.cs ├── license.txt └── readme.txt /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | *.dll 5 | *.exe 6 | thumbs.db 7 | 8 | # User-specific files 9 | *.suo 10 | *.user 11 | *.userosscache 12 | *.sln.docstates 13 | 14 | # User-specific files (MonoDevelop/Xamarin Studio) 15 | *.userprefs 16 | 17 | # Build results 18 | [Dd]ebug/ 19 | [Dd]ebugPublic/ 20 | [Rr]elease/ 21 | [Rr]eleases/ 22 | x64/ 23 | x86/ 24 | build/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | 29 | # Visual Studio 2015 cache/options directory 30 | .vs/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # DNX 46 | project.lock.json 47 | artifacts/ 48 | 49 | *_i.c 50 | *_p.c 51 | *_i.h 52 | *.ilk 53 | *.meta 54 | *.obj 55 | *.pch 56 | *.pdb 57 | *.pgc 58 | *.pgd 59 | *.rsp 60 | *.sbr 61 | *.tlb 62 | *.tli 63 | *.tlh 64 | *.tmp 65 | *.tmp_proj 66 | *.log 67 | *.vspscc 68 | *.vssscc 69 | .builds 70 | *.pidb 71 | *.svclog 72 | *.scc 73 | 74 | # Chutzpah Test files 75 | _Chutzpah* 76 | 77 | # Visual C++ cache files 78 | ipch/ 79 | *.aps 80 | *.ncb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | 90 | # TFS 2012 Local Workspace 91 | $tf/ 92 | 93 | # Guidance Automation Toolkit 94 | *.gpState 95 | 96 | # ReSharper is a .NET coding add-in 97 | _ReSharper*/ 98 | *.[Rr]e[Ss]harper 99 | *.DotSettings.user 100 | 101 | # JustCode is a .NET coding add-in 102 | .JustCode 103 | 104 | # TeamCity is a build add-in 105 | _TeamCity* 106 | 107 | # DotCover is a Code Coverage Tool 108 | *.dotCover 109 | 110 | # NCrunch 111 | _NCrunch_* 112 | .*crunch*.local.xml 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | ## TODO: Comment the next line if you want to checkin your 141 | ## web deploy settings but do note that will include unencrypted 142 | ## passwords 143 | #*.pubxml 144 | 145 | *.publishproj 146 | 147 | # NuGet Packages 148 | *.nupkg 149 | # The packages folder can be ignored because of Package Restore 150 | **/packages/* 151 | # except build/, which is used as an MSBuild target. 152 | !**/packages/build/ 153 | # Uncomment if necessary however generally it will be regenerated when needed 154 | #!**/packages/repositories.config 155 | 156 | # Windows Azure Build Output 157 | csx/ 158 | *.build.csdef 159 | 160 | # Windows Store app package directory 161 | AppPackages/ 162 | 163 | # Visual Studio cache files 164 | # files ending in .cache can be ignored 165 | *.[Cc]ache 166 | # but keep track of directories ending in .cache 167 | !*.[Cc]ache/ 168 | 169 | # Others 170 | ClientBin/ 171 | [Ss]tyle[Cc]op.* 172 | ~$* 173 | *~ 174 | *.dbmdl 175 | *.dbproj.schemaview 176 | *.pfx 177 | *.publishsettings 178 | node_modules/ 179 | orleans.codegen.cs 180 | 181 | # RIA/Silverlight projects 182 | Generated_Code/ 183 | 184 | # Backup & report files from converting an old project file 185 | # to a newer Visual Studio version. Backup files are not needed, 186 | # because we have git ;-) 187 | _UpgradeReport_Files/ 188 | Backup*/ 189 | UpgradeLog*.XML 190 | UpgradeLog*.htm 191 | 192 | # SQL Server files 193 | *.mdf 194 | *.ldf 195 | 196 | # Business Intelligence projects 197 | *.rdl.data 198 | *.bim.layout 199 | *.bim_*.settings 200 | 201 | # Microsoft Fakes 202 | FakesAssemblies/ 203 | 204 | # Node.js Tools for Visual Studio 205 | .ntvs_analysis.dat 206 | 207 | # Visual Studio 6 build log 208 | *.plg 209 | 210 | # Visual Studio 6 workspace options file 211 | *.opt 212 | 213 | # LightSwitch generated files 214 | GeneratedArtifacts/ 215 | _Pvt_Extensions/ 216 | ModelManifest.xml 217 | -------------------------------------------------------------------------------- /AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("ExpressionFormatter")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("ExpressionFormatter")] 13 | [assembly: AssemblyCopyright("Copyright © Joseph Albahari 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("9c9a899c-88f9-4d4a-9732-00b403aee35f")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /BracketedExpressionToken.cs: -------------------------------------------------------------------------------- 1 | // Written by Joseph Albahari, LINQPad. See license.txt 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace ExpressionFormatter 9 | { 10 | /// 11 | /// An ExpressionToken, that when formatted, is surrounded in brackets. 12 | /// 13 | class BracketedExpressionToken : ExpressionToken 14 | { 15 | public readonly string OpenBracket, CloseBracket; 16 | public readonly ExpressionToken Body; 17 | public bool NewLineBefore; 18 | public bool OmitBracketsForSingle; 19 | 20 | public BracketedExpressionToken (string openBracket, string closeBracket, ExpressionToken body) 21 | : this (openBracket, closeBracket, false, body) 22 | { 23 | } 24 | 25 | public BracketedExpressionToken (string openBracket, string closeBracket, bool omitBracketsForSingle, ExpressionToken body) 26 | { 27 | OpenBracket = openBracket; 28 | CloseBracket = closeBracket; 29 | OmitBracketsForSingle = omitBracketsForSingle; 30 | Body = body; 31 | } 32 | 33 | public override void Write (StringBuilder sb, int indent) 34 | { 35 | bool single = !(Body is CompositeExpressionToken) || ((CompositeExpressionToken)Body).Tokens.Count () == 1; 36 | if (!OmitBracketsForSingle || NewLineBefore) single = false; 37 | int openIndent = indent; 38 | if (NewLineBefore) 39 | { 40 | WriteNewLine (sb, indent); 41 | openIndent = indent; 42 | sb.Append (OpenBracket); 43 | } 44 | bool alreadyIndented = sb.Length > 2 && char.IsWhiteSpace (sb[sb.Length - 1]) && char.IsWhiteSpace (sb[sb.Length - 2]); 45 | if (Body.MultiLine) indent++; 46 | if (NewLineBefore || alreadyIndented) 47 | WriteNewLine (sb, indent); 48 | if (!NewLineBefore && !single) 49 | { 50 | sb.Append (OpenBracket); 51 | openIndent = indent; 52 | } 53 | Body.Write (sb, indent + Body.SplitIndent); 54 | if (Body.MultiLine) WriteNewLine (sb, openIndent); 55 | if (!single) sb.Append (CloseBracket); 56 | } 57 | 58 | public override int Length 59 | { 60 | get { return Body.Length + OpenBracket.Length + CloseBracket.Length; } 61 | } 62 | 63 | public override bool MultiLine 64 | { 65 | get { return Body.MultiLine || NewLineBefore; } 66 | set { } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /CommaExpressionToken.cs: -------------------------------------------------------------------------------- 1 | // Written by Joseph Albahari, LINQPad. See license.txt 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace ExpressionFormatter 9 | { 10 | class CommaExpressionToken : LeafExpressionToken 11 | { 12 | public CommaExpressionToken () : base (", ") { } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CompositeExpressionToken.cs: -------------------------------------------------------------------------------- 1 | // Written by Joseph Albahari, LINQPad. See license.txt 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace ExpressionFormatter 9 | { 10 | /// 11 | /// An ExpressionToken that comprises other ExpressionTokens. 12 | /// 13 | class CompositeExpressionToken : ExpressionToken 14 | { 15 | public readonly List Tokens = new List (); 16 | public bool AddCommas; 17 | int? _length; 18 | bool? _multiLine; 19 | 20 | public CompositeExpressionToken () { } 21 | 22 | public CompositeExpressionToken (IEnumerable tokens, bool addCommas) 23 | { 24 | Tokens.AddRange (tokens.Where (t => t != null)); 25 | AddCommas = addCommas; 26 | if (addCommas) 27 | foreach (ExpressionToken t in Tokens) 28 | if (t != null) 29 | t.Splittable = true; 30 | } 31 | 32 | public void AddStringToken (string s) 33 | { 34 | AddStringToken (s, false); 35 | } 36 | 37 | public void AddStringToken (string s, bool splittable) 38 | { 39 | Tokens.Add (new LeafExpressionToken (s) { Splittable = splittable }); 40 | } 41 | 42 | public override void Write (StringBuilder sb, int indent) 43 | { 44 | bool first = true; 45 | foreach (ExpressionToken t in Tokens) 46 | if (t != null) 47 | { 48 | if (first) 49 | first = false; 50 | else if (AddCommas) 51 | sb.Append (", "); 52 | 53 | if (MultiLine && t.Splittable) 54 | WriteNewLine (sb, indent + t.SplitIndent); 55 | 56 | t.Write (sb, indent + t.SplitIndent); 57 | } 58 | } 59 | 60 | public override int Length 61 | { 62 | get 63 | { 64 | if (!_length.HasValue) _length = Tokens.Sum (t => t.Length); 65 | return _length.Value; 66 | } 67 | } 68 | 69 | public override bool MultiLine 70 | { 71 | get 72 | { 73 | if (!_multiLine.HasValue) 74 | _multiLine = Length > 90 || Tokens.Count () > 5 || Tokens.Any (t => t.MultiLine); 75 | return _multiLine.Value; 76 | } 77 | set { _multiLine = value; } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /ExpressionFormatter.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9C9A899C-88F9-4D4A-9732-00B403AEE35F} 8 | Library 9 | Properties 10 | ExpressionFormatter 11 | ExpressionFormatter 12 | v4.6 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 67 | -------------------------------------------------------------------------------- /ExpressionFormatter.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.24720.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExpressionFormatter", "ExpressionFormatter.csproj", "{9C9A899C-88F9-4D4A-9732-00B403AEE35F}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {9C9A899C-88F9-4D4A-9732-00B403AEE35F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {9C9A899C-88F9-4D4A-9732-00B403AEE35F}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {9C9A899C-88F9-4D4A-9732-00B403AEE35F}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {9C9A899C-88F9-4D4A-9732-00B403AEE35F}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /ExpressionToken.cs: -------------------------------------------------------------------------------- 1 | // Written by Joseph Albahari, LINQPad. See license.txt 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Linq.Expressions; 8 | using System.Reflection; 9 | using System.Runtime.CompilerServices; 10 | using System.Data.Linq; 11 | 12 | namespace ExpressionFormatter 13 | { 14 | /// 15 | /// Describes an expression node with formatting info. This is used to generate a nicely formatted lambda expression 16 | /// string (i.e., with line breaks). 17 | /// 18 | abstract class ExpressionToken 19 | { 20 | #region Static fields & constructor 21 | 22 | static Dictionary _binaryExpressionStrings = new Dictionary (); 23 | static Dictionary _visitMethods; 24 | 25 | static ExpressionToken () 26 | { 27 | ExpressionType [] binExprTypes = 28 | { 29 | ExpressionType.Add, 30 | ExpressionType.AddChecked, 31 | ExpressionType.And, 32 | ExpressionType.AndAlso, 33 | ExpressionType.Coalesce, 34 | ExpressionType.Divide, 35 | ExpressionType.Equal, 36 | ExpressionType.ExclusiveOr, 37 | ExpressionType.GreaterThan, 38 | ExpressionType.GreaterThanOrEqual, 39 | ExpressionType.LeftShift, 40 | ExpressionType.LessThan, 41 | ExpressionType.LessThanOrEqual, 42 | ExpressionType.Modulo, 43 | ExpressionType.Multiply, 44 | ExpressionType.MultiplyChecked, 45 | ExpressionType.NotEqual, 46 | ExpressionType.Or, 47 | ExpressionType.OrElse, 48 | ExpressionType.Power, 49 | ExpressionType.RightShift, 50 | ExpressionType.Subtract, 51 | ExpressionType.SubtractChecked 52 | }; 53 | 54 | string [] binExprStrings = "+ + & && ?? . == ^ > >= << < <= % * * != | || ^ >> - -".Split (); 55 | 56 | int i = 0; 57 | foreach (ExpressionType t in binExprTypes) 58 | _binaryExpressionStrings [t] = binExprStrings [i++]; 59 | 60 | _visitMethods = 61 | ( 62 | from exType in typeof (Expression).Assembly.GetTypes () 63 | where exType.IsSubclassOf (typeof (Expression)) || exType.IsSubclassOf (typeof (MemberBinding)) 64 | join method in (typeof (ExpressionToken).GetMethods (BindingFlags.Static | BindingFlags.NonPublic)) 65 | .Where (m => m.Name == "Visit") 66 | on exType equals method.GetParameters () [0].ParameterType 67 | select new 68 | { 69 | exType, 70 | method 71 | } 72 | ) 73 | .ToDictionary (t => t.exType, t => t.method); 74 | } 75 | 76 | #endregion 77 | 78 | #region Static Visitor Methods 79 | 80 | public static ExpressionToken Visit (Expression expr) 81 | { 82 | return Visit ((object)expr); 83 | } 84 | 85 | static ExpressionToken Visit (object expr) 86 | { 87 | if (expr == null) return new LeafExpressionToken ("null"); 88 | MethodInfo toCall; 89 | Type t = expr.GetType (); 90 | Type originalType = t; 91 | while (!t.IsPublic) t = t.BaseType; 92 | if (_visitMethods.TryGetValue (t, out toCall) || t.BaseType != null && _visitMethods.TryGetValue (t.BaseType, out toCall)) 93 | { 94 | ExpressionToken et = (ExpressionToken)toCall.Invoke (null, new object [] { expr }); 95 | return et; 96 | } 97 | 98 | if (t.FullName == "System.Data.Services.Client.ResourceSetExpression") 99 | { 100 | var prop = t.GetProperty ("MemberExpression", BindingFlags.Instance | BindingFlags.NonPublic); 101 | if (prop != null) 102 | { 103 | var memberExpr = prop.GetValue (expr, null) as ConstantExpression; 104 | if (memberExpr != null && memberExpr.Value != null) 105 | return new LeafExpressionToken (memberExpr.Value.ToString ()); 106 | } 107 | } 108 | if (originalType.FullName == "System.Data.Services.Client.ResourceSetExpression") 109 | { 110 | var prop = originalType.GetProperty ("MemberExpression", BindingFlags.Instance | BindingFlags.NonPublic); 111 | if (prop != null) 112 | { 113 | var memberExpr = prop.GetValue (expr, null) as ConstantExpression; 114 | if (memberExpr != null && memberExpr.Value != null) 115 | return new LeafExpressionToken (memberExpr.Value.ToString ()); 116 | } 117 | } 118 | 119 | return null; 120 | } 121 | 122 | static ExpressionToken Visit (BinaryExpression exp) 123 | { 124 | CompositeExpressionToken t = new CompositeExpressionToken (); 125 | 126 | ExpressionToken left = Visit (exp.Left); 127 | ExpressionToken right = Visit (exp.Right); 128 | 129 | if (exp.NodeType == ExpressionType.ArrayIndex) 130 | { 131 | t.Tokens.Add (left); 132 | t.Tokens.Add (new BracketedExpressionToken ("[", "]", right)); 133 | return t; 134 | } 135 | 136 | string symbol; 137 | if (_binaryExpressionStrings.TryGetValue (exp.NodeType, out symbol)) 138 | { 139 | t.Tokens.Add (left); 140 | t.AddStringToken (" " + symbol + " "); 141 | t.Tokens.Add (right); 142 | right.Splittable = true; 143 | right.SplitIndent = 1; 144 | return new BracketedExpressionToken ("(", ")", true, t); 145 | } 146 | 147 | return t; 148 | } 149 | 150 | static ExpressionToken Visit (ConditionalExpression exp) 151 | { 152 | var t = new CompositeExpressionToken (); 153 | t.Tokens.Add (Visit (exp.Test)); 154 | t.AddStringToken (" ? ", true); 155 | t.Tokens.Add (Visit (exp.IfTrue)); 156 | t.AddStringToken (" : ", true); 157 | t.Tokens.Add (Visit (exp.IfFalse)); 158 | return t; 159 | } 160 | 161 | static ExpressionToken Visit (ConstantExpression exp) 162 | { 163 | if (exp.Value != null && exp.Type.IsGenericType && exp.Type.GetGenericTypeDefinition () == typeof (Table<>)) 164 | { 165 | PropertyInfo contextProp = exp.Value.GetType ().GetProperty ("Context"); 166 | if (contextProp != null) 167 | { 168 | object dc = contextProp.GetValue (exp.Value, null); 169 | if (dc != null) 170 | { 171 | PropertyInfo tableProp = dc.GetType ().GetProperties ().First (p => p.PropertyType == exp.Type); 172 | if (tableProp != null) return new LeafExpressionToken (tableProp.Name); 173 | } 174 | } 175 | } 176 | else if (exp.Value != null && exp.Type.IsGenericType && 177 | (exp.Type.FullName.StartsWith ("System.Data.Objects.ObjectQuery`1", StringComparison.Ordinal) || 178 | exp.Type.FullName.StartsWith ("System.Data.Objects.ObjectSet`1", StringComparison.Ordinal) || 179 | exp.Type.FullName.StartsWith ("System.Data.Services.Client.DataServiceQuery`1"))) 180 | { 181 | return new LeafExpressionToken (exp.Type.GetGenericArguments ()[0].Name); 182 | } 183 | string value = exp.Value == null ? "null" : exp.Value is string ? ('"' + (string)exp.Value + '"') : exp.Value.ToString (); 184 | return new LeafExpressionToken (value); 185 | } 186 | 187 | static ExpressionToken Visit (InvocationExpression exp) 188 | { 189 | var t = new CompositeExpressionToken (); 190 | t.AddStringToken ("Invoke" + (exp.Arguments.Count == 0 ? "" : " "), true); 191 | t.Tokens.Add ( 192 | new BracketedExpressionToken ( 193 | "(", ")", new CompositeExpressionToken (exp.Arguments.Select (a => Visit (a)), true)) 194 | ); 195 | return t; 196 | } 197 | 198 | static ExpressionToken Visit (LambdaExpression exp) 199 | { 200 | var t = new CompositeExpressionToken (); 201 | string s = ""; 202 | if (exp.Parameters.Count != 1) s = "("; 203 | s += string.Join (", ", exp.Parameters.Select (p => CleanIdentifier (p.Name)).ToArray ()); 204 | if (exp.Parameters.Count != 1) s += ")"; 205 | s += " => "; 206 | t.AddStringToken (s); 207 | ExpressionToken body = Visit (exp.Body); 208 | if (body != null) 209 | { 210 | body.Splittable = true; 211 | body.SplitIndent = 1; 212 | t.Tokens.Add (body); 213 | } 214 | return t; 215 | } 216 | 217 | static ExpressionToken Visit (ListInitExpression exp) 218 | { 219 | var t = new CompositeExpressionToken (); 220 | t.Tokens.Add (Visit (exp.NewExpression)); 221 | var outer = new CompositeExpressionToken (); 222 | outer.AddCommas = true; 223 | foreach (var init in exp.Initializers) 224 | outer.Tokens.Add ( 225 | new BracketedExpressionToken ( 226 | "(", ")", true, new CompositeExpressionToken (init.Arguments.Select (a => Visit (a)), true)) 227 | ); 228 | t.Tokens.Add (new BracketedExpressionToken (" { ", " } ", outer)); 229 | return t; 230 | } 231 | 232 | static ExpressionToken Visit (MemberExpression exp) 233 | { 234 | CompositeExpressionToken t = new CompositeExpressionToken (); 235 | var constExp = exp.Expression as ConstantExpression; 236 | // Strip out captured variables: 237 | if (constExp != null && constExp.Value != null && constExp.Value.GetType ().IsNested && constExp.Value.GetType ().Name.StartsWith ("<", StringComparison.Ordinal) 238 | || constExp != null && constExp.Value is DataContext) 239 | return new LeafExpressionToken (exp.Member.Name); 240 | else if (exp.Expression != null) 241 | t.Tokens.Add (Visit (exp.Expression)); 242 | else 243 | t.AddStringToken (exp.Member.DeclaringType.Name); 244 | t.AddStringToken ("." + CleanIdentifier (exp.Member.Name)); 245 | return t; 246 | } 247 | 248 | static ExpressionToken Visit (MemberInitExpression exp) 249 | { 250 | CompositeExpressionToken t = new CompositeExpressionToken (); 251 | if (exp.NewExpression.Type.IsAnonymous()) 252 | t.AddStringToken ("new "); 253 | else 254 | t.Tokens.Add (Visit (exp.NewExpression)); 255 | t.Tokens.Add ( 256 | new BracketedExpressionToken ( 257 | "{", "}", new CompositeExpressionToken (exp.Bindings.Select (b => Visit (b)), true) { MultiLine = true }) 258 | { 259 | NewLineBefore = true 260 | } 261 | ); 262 | return t; 263 | } 264 | 265 | static ExpressionToken Visit (MethodCallExpression exp) 266 | { 267 | bool extensionMethod = Attribute.IsDefined (exp.Method, typeof (ExtensionAttribute)); 268 | string methodName = exp.Method.Name; 269 | 270 | CompositeExpressionToken t = new CompositeExpressionToken (); 271 | if (extensionMethod) 272 | { 273 | if (exp.Method.DeclaringType == typeof (Queryable)) t.MultiLine = true; 274 | t.Tokens.Add (Visit (exp.Arguments [0])); 275 | t.AddStringToken ("." + methodName + " ", true); 276 | t.Tokens.Last ().SplitIndent = 1; 277 | var args = new CompositeExpressionToken (exp.Arguments.Skip (1).Select (a => Visit (a)), true); 278 | if (exp.Method.DeclaringType == typeof (Queryable) && exp.Arguments.Count () > 2) args.MultiLine = true; 279 | args.SplitIndent = 1; 280 | t.Tokens.Add ( 281 | new BracketedExpressionToken ( 282 | "(", ")", args) 283 | ); 284 | } 285 | else 286 | { 287 | if (exp.Object == null) 288 | t.AddStringToken (exp.Method.DeclaringType.FormatName()); 289 | else 290 | t.Tokens.Add (Visit (exp.Object)); 291 | if (exp.Method.IsSpecialName) 292 | { 293 | var prop = exp.Method.DeclaringType.GetProperties ().Where (p => p.GetAccessors ().Contains (exp.Method)).FirstOrDefault (); 294 | if (prop != null) 295 | { 296 | t.Tokens.Add ( 297 | new BracketedExpressionToken ( 298 | " [", "]", new CompositeExpressionToken (exp.Arguments.Select (a => Visit (a)), true) ) 299 | ); 300 | return t; 301 | } 302 | } 303 | t.AddStringToken ("." + methodName + (exp.Arguments.Count == 0 ? "" : " "), true); 304 | t.Tokens.Last ().SplitIndent = 1; 305 | t.Tokens.Add ( 306 | new BracketedExpressionToken ( 307 | "(", ")", new CompositeExpressionToken (exp.Arguments.Select (a => Visit (a)), true) { SplitIndent = 1 }) 308 | ); 309 | } 310 | return t; 311 | } 312 | 313 | static ExpressionToken Visit (NewArrayExpression exp) 314 | { 315 | bool newArrayInit = exp.NodeType == ExpressionType.NewArrayInit; 316 | CompositeExpressionToken t = new CompositeExpressionToken (); 317 | bool anon = exp.Type.IsAnonymous(); 318 | Type type = exp.Type; 319 | if (type.IsArray) type = type.GetElementType (); 320 | string typeName = anon ? "" : (type.FormatName ()); 321 | string newText = "new " + typeName; 322 | if (newArrayInit && exp.Expressions.Any ()) 323 | newText += "[] "; 324 | else if (newArrayInit) 325 | newText += "[0]"; 326 | t.AddStringToken (newText); 327 | if (!newArrayInit || exp.Expressions.Any ()) 328 | t.Tokens.Add ( 329 | new BracketedExpressionToken ( 330 | newArrayInit ? "{ " : "[", 331 | newArrayInit ? " } " : "]", 332 | new CompositeExpressionToken (exp.Expressions.Select (a => Visit (a)), true)) 333 | ); 334 | return t; 335 | } 336 | 337 | static ExpressionToken Visit (NewExpression exp) 338 | { 339 | CompositeExpressionToken t = new CompositeExpressionToken (); 340 | Type type = exp.Type; 341 | if (exp.Constructor != null) type = exp.Constructor.DeclaringType; 342 | t.AddStringToken ("new " + (type.IsAnonymous() 343 | ? "" 344 | : type.FormatName ()) 345 | + (exp.Arguments.Count == 0 ? "" : " ") 346 | ); 347 | 348 | if (exp.Members == null || exp.Members.Count == 0) 349 | { 350 | CompositeExpressionToken body = new CompositeExpressionToken (exp.Arguments.Select (a => Visit (a)), true); 351 | t.Tokens.Add (new BracketedExpressionToken ("(", ")", body)); 352 | } 353 | else 354 | { 355 | int i = 0; 356 | var multi = new CompositeExpressionToken { MultiLine = true, AddCommas = true }; 357 | foreach (Expression argExpr in exp.Arguments) 358 | { 359 | MemberInfo mi = exp.Members [i++]; 360 | PropertyInfo pi = mi as PropertyInfo; 361 | if (pi == null) pi = mi.DeclaringType 362 | .GetProperties (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) 363 | .FirstOrDefault (p => p.GetAccessors ().Contains (mi)); 364 | if (pi != null) 365 | { 366 | var assignment = new CompositeExpressionToken (); 367 | assignment.AddStringToken (CleanIdentifier (pi.Name) + " = "); 368 | assignment.Tokens.Add (Visit (argExpr)); 369 | assignment.Splittable = true; 370 | multi.Tokens.Add (assignment); 371 | } 372 | } 373 | t.Tokens.Add (new BracketedExpressionToken ("{", "}", multi) { NewLineBefore = true }); 374 | } 375 | return t; 376 | } 377 | 378 | static ExpressionToken Visit (ParameterExpression exp) 379 | { 380 | string name = exp.Name ?? ""; 381 | return new LeafExpressionToken (CleanIdentifier (name)); 382 | } 383 | 384 | static ExpressionToken Visit (TypeBinaryExpression exp) 385 | { 386 | var t = new CompositeExpressionToken (); 387 | t.Tokens.Add (Visit (exp.Expression)); 388 | t.AddStringToken (" is "); 389 | t.AddStringToken (exp.TypeOperand.FormatName ()); 390 | return new BracketedExpressionToken ("(", ")", t); 391 | } 392 | 393 | static ExpressionToken Visit (UnaryExpression exp) 394 | { 395 | if (exp.NodeType == ExpressionType.Quote) return Visit (exp.Operand); 396 | var t = new CompositeExpressionToken (); 397 | 398 | switch (exp.NodeType) 399 | { 400 | case ExpressionType.Convert: 401 | if (exp.Operand.Type.IsSubclassOf (exp.Type)) return Visit (exp.Operand); 402 | t.AddStringToken ("(" + exp.Type.FormatName () + ")"); 403 | break; 404 | case ExpressionType.TypeAs: 405 | t.Tokens.Add (Visit (exp.Operand)); 406 | t.AddStringToken (" as "); 407 | t.AddStringToken (exp.Type.FormatName ()); 408 | return t; 409 | case ExpressionType.Not: 410 | t.AddStringToken ("!"); 411 | break; 412 | case ExpressionType.UnaryPlus: 413 | t.AddStringToken ("+"); 414 | break; 415 | case ExpressionType.Negate: 416 | case ExpressionType.NegateChecked: 417 | t.AddStringToken ("-"); 418 | break; 419 | default: 420 | t.AddStringToken (exp.NodeType.ToString ()); 421 | break; 422 | } 423 | 424 | t.Tokens.Add (new BracketedExpressionToken ("(", ")", true, Visit (exp.Operand))); 425 | return t; 426 | } 427 | 428 | static ExpressionToken Visit (MemberAssignment mb) 429 | { 430 | var t = new CompositeExpressionToken (); 431 | t.AddStringToken (CleanIdentifier (mb.Member.Name) + " = "); 432 | t.Tokens.Add (Visit (mb.Expression)); 433 | t.Splittable = true; 434 | return t; 435 | } 436 | 437 | static ExpressionToken Visit (MemberListBinding mb) 438 | { 439 | return null; 440 | } 441 | 442 | static ExpressionToken Visit (MemberMemberBinding mb) 443 | { 444 | return null; 445 | } 446 | 447 | static string CleanIdentifier (string name) 448 | { 449 | if (name == null) return null; 450 | if (name.StartsWith ("<>h__TransparentIdentifier", StringComparison.Ordinal)) return "temp" + name.Substring (26); 451 | return name; 452 | } 453 | 454 | #endregion 455 | 456 | #region Instance Members 457 | 458 | public abstract int Length { get; } 459 | public abstract bool MultiLine { get; set; } 460 | 461 | public bool Splittable; 462 | public int SplitIndent; 463 | 464 | public abstract void Write (StringBuilder sb, int indent); 465 | 466 | protected void WriteNewLine (StringBuilder sb, int indent) 467 | { 468 | int trailingSpaces = 0; 469 | int last = sb.Length - 1; 470 | while (last > 0 && sb [last] == ' ') { trailingSpaces++; last--; } 471 | if (last > 0 && sb [last] == '\n') 472 | { 473 | int dif = trailingSpaces - indent * 3; 474 | if (dif == 0) return; 475 | if (dif > 0) sb.Remove (sb.Length - dif, dif); 476 | else sb.Append ("".PadRight (-dif)); 477 | } 478 | else 479 | sb.Append ("\r\n".PadRight (2 + indent * 3)); 480 | } 481 | 482 | public override string ToString () 483 | { 484 | StringBuilder sb = new StringBuilder (); 485 | Write (sb, 0); 486 | return sb.ToString (); 487 | } 488 | 489 | #endregion 490 | } 491 | } 492 | -------------------------------------------------------------------------------- /Extensions.cs: -------------------------------------------------------------------------------- 1 | // Written by Joseph Albahari, LINQPad. See license.txt 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace ExpressionFormatter 11 | { 12 | public static class Extensions 13 | { 14 | public static string Format (this Expression expr) 15 | { 16 | var token = ExpressionToken.Visit (expr); 17 | return token == null ? null : token.ToString (); 18 | } 19 | 20 | internal static bool IsAnonymous (this Type type) 21 | { 22 | if (!string.IsNullOrEmpty (type.Namespace) || !type.IsGenericType) return false; 23 | return IsAnonymous (type.Name); 24 | } 25 | 26 | internal static bool IsAnonymous (string typeName) 27 | { 28 | // Optimization to improve perf when called from UserCache 29 | return 30 | typeName.Length > 5 && 31 | (typeName [0] == '<' && typeName [1] == '>' && (typeName [5] == 'A' && typeName [6] == 'n' || typeName.IndexOf ("anon", StringComparison.OrdinalIgnoreCase) > -1) || 32 | typeName [0] == 'V' && typeName [1] == 'B' && typeName [2] == '$' && typeName [3] == 'A' && typeName [4] == 'n'); 33 | } 34 | 35 | internal static string FormatName (this Type t, bool fullname = false) 36 | { 37 | return fullname ? t.FullName : t.Name; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Joseph Albahari 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LeafExpressionToken.cs: -------------------------------------------------------------------------------- 1 | // Written by Joseph Albahari, LINQPad. See license.txt 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace ExpressionFormatter 9 | { 10 | /// 11 | /// An ExpressionToken that's written as a simple text string. 12 | /// 13 | class LeafExpressionToken : ExpressionToken 14 | { 15 | public readonly string Text; 16 | 17 | public LeafExpressionToken (string text) 18 | { 19 | Text = text; 20 | } 21 | 22 | public override void Write (StringBuilder sb, int indent) 23 | { 24 | sb.Append (Text); 25 | } 26 | 27 | public override int Length 28 | { 29 | get { return Text.Length; } 30 | } 31 | 32 | public override bool MultiLine 33 | { 34 | get { return false; } 35 | set { } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 |  2 | 3 | Copyright (c) 2007-2016 Joseph Albahari 4 | 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | Simple Demo: 2 | 3 | 4 | static void Main (string [] args) 5 | { 6 | Expression> expr = x => x % 2 == 0; 7 | Console.WriteLine (expr.Format ()); 8 | 9 | Console.WriteLine (); 10 | 11 | var query = 12 | from c in "The quick brown fox uses LINQPad".AsQueryable () 13 | where c != ' ' 14 | orderby c 15 | select char.ToUpper (c); 16 | 17 | Console.WriteLine (query.Expression.Format ()); 18 | } --------------------------------------------------------------------------------