forked from henon/mongodb-csharp
/
JavascriptFormatter.cs
307 lines (277 loc) · 11.1 KB
/
JavascriptFormatter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using MongoDB.Linq.Expressions;
using MongoDB.Util;
namespace MongoDB.Linq.Translators
{
internal class JavascriptFormatter : MongoExpressionVisitor
{
private StringBuilder _js;
public string FormatJavascript(Expression expression)
{
_js = new StringBuilder();
Visit(expression);
return _js.ToString();
}
protected override Expression VisitBinary(BinaryExpression b)
{
_js.Append("(");
Visit(b.Left);
switch (b.NodeType)
{
case ExpressionType.Equal:
_js.Append(" === ");
break;
case ExpressionType.GreaterThan:
_js.Append(" > ");
break;
case ExpressionType.GreaterThanOrEqual:
_js.Append(" >= ");
break;
case ExpressionType.LessThan:
_js.Append(" < ");
break;
case ExpressionType.LessThanOrEqual:
_js.Append(" <= ");
break;
case ExpressionType.NotEqual:
_js.Append(" != ");
break;
case ExpressionType.Modulo:
_js.Append(" % ");
break;
case ExpressionType.And:
case ExpressionType.AndAlso:
_js.Append(" && ");
break;
case ExpressionType.Or:
case ExpressionType.OrElse:
_js.Append(" || ");
break;
case ExpressionType.Add:
case ExpressionType.AddChecked:
_js.Append(" + ");
break;
case ExpressionType.Coalesce:
_js.Append(" || ");
break;
case ExpressionType.Divide:
_js.Append(" / ");
break;
case ExpressionType.ExclusiveOr:
_js.Append(" ^ ");
break;
case ExpressionType.LeftShift:
_js.Append(" << ");
break;
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
_js.Append(" * ");
break;
case ExpressionType.RightShift:
_js.Append(" >> ");
break;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
_js.Append(" - ");
break;
default:
throw new NotSupportedException(string.Format("The operation {0} is not supported.", b.NodeType));
}
Visit(b.Right);
_js.Append(")");
return b;
}
protected override Expression VisitConstant(ConstantExpression c)
{
_js.Append(GetJavascriptValueForConstant(c));
return c;
}
protected override Expression VisitField(FieldExpression f)
{
//TODO: may need to handle a field that composes other fields.
_js.AppendFormat("this.{0}", f.Name);
return f;
}
protected override Expression VisitMemberAccess(MemberExpression m)
{
if (m.Member.DeclaringType == typeof(Array))
{
if (m.Member.Name == "Length")
{
Visit(m.Expression);
_js.Append(".length");
return m;
}
}
else if (m.Member.DeclaringType == typeof(string))
{
if (m.Member.Name == "Length")
{
Visit(m.Expression);
_js.Append(".length");
return m;
}
}
else if (typeof(ICollection).IsAssignableFrom(m.Member.DeclaringType))
{
if (m.Member.Name == "Count")
{
Visit(m.Expression);
_js.Append(".length");
return m;
}
}
else if (typeof(ICollection<>).IsOpenTypeAssignableFrom(m.Member.DeclaringType))
{
if (m.Member.Name == "Count")
{
Visit(m.Expression);
_js.Append(".length");
return m;
}
}
throw new NotSupportedException(string.Format("The member {0} is not supported.", m.Member.Name));
}
protected override Expression VisitMethodCall(MethodCallExpression m)
{
if (m == null)
return m;
FieldExpression field;
if (m.Method.DeclaringType == typeof(Queryable) || m.Method.DeclaringType == typeof(Enumerable))
{
switch (m.Method.Name)
{
case "Count":
if (m.Arguments.Count == 1)
{
Visit(m.Arguments[0]);
_js.Append(".length");
return m;
}
throw new NotSupportedException("The method Count with a predicate is not supported for field.");
}
}
else if (m.Method.DeclaringType == typeof(string))
{
field = m.Object as FieldExpression;
if (field == null)
throw new InvalidQueryException(string.Format("The mongo field must be the operator for a string operation of type {0}.", m.Method.Name));
Visit(field);
switch (m.Method.Name)
{
case "StartsWith":
_js.AppendFormat("/^{0}/", EvaluateConstant<string>(m.Arguments[0]));
break;
case "EndsWith":
_js.AppendFormat("/{0}$/", EvaluateConstant<string>(m.Arguments[0]));
break;
case "Contains":
_js.AppendFormat("/{0}/", EvaluateConstant<string>(m.Arguments[0]));
break;
case "SubString":
if (m.Arguments.Count == 1)
_js.AppendFormat(".substr({0})", EvaluateConstant<int>(m.Arguments[0]));
else if (m.Arguments.Count == 2)
_js.AppendFormat(".substr({0})", EvaluateConstant<int>(m.Arguments[0]), EvaluateConstant<int>(m.Arguments[1]));
break;
case "ToLower":
_js.Append(".toLowerCase()");
break;
case "ToUpper":
_js.Append(".toUpperCase()");
break;
case "get_Chars":
_js.AppendFormat("[{0}]", EvaluateConstant<int>(m.Arguments[0]));
break;
default:
throw new NotSupportedException(string.Format("The string method {0} is not supported.", m.Method.Name));
}
return m;
}
else if (m.Method.DeclaringType == typeof(Regex))
{
if (m.Method.Name == "IsMatch")
{
field = m.Arguments[0] as FieldExpression;
if (field == null)
throw new InvalidQueryException(string.Format("The mongo field must be the operator for a string operation of type {0}.", m.Method.Name));
Visit(field);
string value = null;
if (m.Object == null)
value = EvaluateConstant<string>(m.Arguments[1]);
else
throw new InvalidQueryException(string.Format("Only the static Regex.IsMatch is supported.", m.Method.Name));
_js.AppendFormat("/{0}/", value);
return m;
}
}
throw new NotSupportedException(string.Format("The method {0} is not supported.", m.Method.Name));
}
protected override NewExpression VisitNew(NewExpression nex)
{
_js.Append(new JavascriptObjectFormatter().FormatObject(nex));
return nex;
}
protected override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
_js.Append("!(");
Visit(u.Operand);
_js.Append(")");
break;
default:
throw new NotSupportedException(string.Format("The unary operator {0} is not supported.", u.NodeType));
}
return u;
}
private static T EvaluateConstant<T>(Expression e)
{
if (e.NodeType != ExpressionType.Constant)
throw new ArgumentException("Expression must be a constant.");
return (T)((ConstantExpression)e).Value;
}
private static string GetJavascriptValueForConstant(ConstantExpression c)
{
if (c.Value == null)
return "null";
if (c.Type == typeof(string) || c.Type == typeof(StringBuilder))
return string.Format(@"""{0}""", c.Value.ToString());
return c.Value.ToString();
}
private class JavascriptObjectFormatter : MongoExpressionVisitor
{
private StringBuilder _js;
private JavascriptFormatter _formatter;
public JavascriptObjectFormatter()
{
_formatter = new JavascriptFormatter();
}
public string FormatObject(NewExpression nex)
{
_js = new StringBuilder("{");
Visit(nex);
return _js.Append("}").ToString();
}
protected override NewExpression VisitNew(NewExpression nex)
{
var parameters = nex.Constructor.GetParameters();
for(int i = 0; i < nex.Arguments.Count; i++)
{
if (i > 0)
_js.Append(", ");
_js.AppendFormat("{0}: {1}", parameters[i].Name, _formatter.FormatJavascript(nex.Arguments[i]));
}
return nex;
}
}
}
}