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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
|
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Workflow.ComponentModel;
namespace System.Workflow.Activities.Rules
{
internal static class RuleDecompiler
{
#region Decompile literals
internal static void DecompileObjectLiteral(StringBuilder decompilation, object primitiveValue)
{
if (primitiveValue == null)
{
decompilation.Append("null");
}
else
{
Type primitiveType = primitiveValue.GetType();
if (primitiveType == typeof(string))
DecompileStringLiteral(decompilation, (string)primitiveValue);
else if (primitiveType == typeof(char))
DecompileCharacterLiteral(decompilation, (char)primitiveValue);
else if (primitiveType == typeof(long))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "L");
else if (primitiveType == typeof(uint))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "U");
else if (primitiveType == typeof(ulong))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "UL");
else if (primitiveType == typeof(float))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'f');
else if (primitiveType == typeof(double))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'd');
else if (primitiveType == typeof(decimal))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'm');
else
decompilation.Append(primitiveValue.ToString());
}
}
private static void DecompileFloatingPointLiteral(StringBuilder decompilation, object value, char suffix)
{
// Make sure decimal point isn't converted to a comma in European locales.
string svalue = Convert.ToString(value, CultureInfo.InvariantCulture);
decompilation.Append(svalue);
if (suffix == 'd')
{
// Don't append 'd' suffixes, they're ugly. Only if the string-ified value contains
// no decimal and no exponent do we need to append a ".0" to make it a double (as
// opposed to an integer).
bool hasDecimal = svalue.IndexOf('.') >= 0;
bool hasExponent = svalue.IndexOfAny(new char[] { 'e', 'E' }) >= 0;
if (!hasDecimal && !hasExponent)
decompilation.Append(".0");
}
else
{
decompilation.Append(suffix);
}
}
private static void DecompileSuffixedIntegerLiteral(StringBuilder decompilation, object value, string suffix)
{
decompilation.Append(value.ToString());
decompilation.Append(suffix);
}
private static void DecompileStringLiteral(StringBuilder decompilation, string strValue)
{
decompilation.Append("\"");
for (int i = 0; i < strValue.Length; ++i)
{
char c = strValue[i];
// is this character a surrogate pair?
if ((char.IsHighSurrogate(c)) && (i + 1 < strValue.Length) && (char.IsLowSurrogate(strValue[i + 1])))
{
// yes, so leave the two characters unchanged
decompilation.Append(c);
++i;
decompilation.Append(strValue[i]);
}
else
AppendCharacter(decompilation, c, '"');
}
decompilation.Append("\"");
}
private static void DecompileCharacterLiteral(StringBuilder decompilation, char charValue)
{
decompilation.Append("'");
AppendCharacter(decompilation, charValue, '\'');
decompilation.Append("'");
}
private static void AppendCharacter(StringBuilder decompilation, char charValue, char quoteCharacter)
{
if (charValue == quoteCharacter)
{
decompilation.Append("\\");
decompilation.Append(quoteCharacter);
}
else if (charValue == '\\')
{
decompilation.Append("\\\\");
}
else if ((charValue >= ' ' && charValue < '\u007f') || char.IsLetterOrDigit(charValue) || char.IsPunctuation(charValue))
{
decompilation.Append(charValue);
}
else
{
string escapeSequence = null;
switch (charValue)
{
case '\0':
escapeSequence = "\\0";
break;
case '\n':
escapeSequence = "\\n";
break;
case '\r':
escapeSequence = "\\r";
break;
case '\b':
escapeSequence = "\\b";
break;
case '\a':
escapeSequence = "\\a";
break;
case '\t':
escapeSequence = "\\t";
break;
case '\f':
escapeSequence = "\\f";
break;
case '\v':
escapeSequence = "\\v";
break;
}
if (escapeSequence != null)
{
decompilation.Append(escapeSequence);
}
else
{
decompilation.Append("\\u");
UInt16 cv = (UInt16)charValue;
for (int i = 12; i >= 0; i -= 4)
{
int mask = 0xF << i;
byte c = (byte)((cv & mask) >> i);
decompilation.Append("0123456789ABCDEF"[c]);
}
}
}
}
#endregion
#region Type decompilation
internal static string DecompileType(Type type)
{
if (type == null)
return string.Empty;
StringBuilder sb = new StringBuilder();
DecompileType_Helper(sb, type);
return sb.ToString();
}
private static void DecompileType_Helper(StringBuilder decompilation, Type type)
{
int i;
if (type.HasElementType)
{
DecompileType_Helper(decompilation, type.GetElementType());
if (type.IsArray)
{
decompilation.Append("[");
decompilation.Append(',', type.GetArrayRank() - 1);
decompilation.Append("]");
}
else if (type.IsByRef)
{
decompilation.Append('&');
}
else if (type.IsPointer)
{
decompilation.Append('*');
}
}
else
{
string typeName = type.FullName;
if (typeName == null) // Full name may be null for an unbound generic.
typeName = type.Name;
typeName = UnmangleTypeName(typeName);
decompilation.Append(typeName);
if (type.IsGenericType)
{
decompilation.Append("<");
Type[] typeArgs = type.GetGenericArguments();
DecompileType_Helper(decompilation, typeArgs[0]); // decompile the first type arg
for (i = 1; i < typeArgs.Length; ++i)
{
decompilation.Append(", ");
DecompileType_Helper(decompilation, typeArgs[i]);
}
decompilation.Append(">");
}
}
}
internal static void DecompileType(StringBuilder decompilation, CodeTypeReference typeRef)
{
// Remove any back-tick decorations on generic types, if present.
string baseType = UnmangleTypeName(typeRef.BaseType);
decompilation.Append(baseType);
if (typeRef.TypeArguments != null && typeRef.TypeArguments.Count > 0)
{
decompilation.Append("<");
bool first = true;
foreach (CodeTypeReference argTypeRef in typeRef.TypeArguments)
{
if (!first)
decompilation.Append(", ");
first = false;
DecompileType(decompilation, argTypeRef);
}
decompilation.Append(">");
}
if (typeRef.ArrayRank > 0)
{
do
{
decompilation.Append("[");
for (int i = 1; i < typeRef.ArrayRank; ++i)
decompilation.Append(",");
decompilation.Append("]");
typeRef = typeRef.ArrayElementType;
} while (typeRef.ArrayRank > 0);
}
}
private static Dictionary<string, string> knownTypeMap = InitializeKnownTypeMap();
private static Dictionary<string, string> InitializeKnownTypeMap()
{
Dictionary<string, string> map = new Dictionary<string, string>();
map.Add("System.Char", "char");
map.Add("System.Byte", "byte");
map.Add("System.SByte", "sbyte");
map.Add("System.Int16", "short");
map.Add("System.UInt16", "ushort");
map.Add("System.Int32", "int");
map.Add("System.UInt32", "uint");
map.Add("System.Int64", "long");
map.Add("System.UInt64", "ulong");
map.Add("System.Single", "float");
map.Add("System.Double", "double");
map.Add("System.Decimal", "decimal");
map.Add("System.Boolean", "bool");
map.Add("System.String", "string");
map.Add("System.Object", "object");
map.Add("System.Void", "void");
return map;
}
private static string TryReplaceKnownTypes(string typeName)
{
string newTypeName = null;
if (!knownTypeMap.TryGetValue(typeName, out newTypeName))
newTypeName = typeName;
return newTypeName;
}
private static string UnmangleTypeName(string typeName)
{
int tickIndex = typeName.IndexOf('`');
if (tickIndex > 0)
typeName = typeName.Substring(0, tickIndex);
// Replace the '+' for a nested type with a '.'
typeName = typeName.Replace('+', '.');
typeName = TryReplaceKnownTypes(typeName);
return typeName;
}
#endregion
#region Method decompilation
internal static string DecompileMethod(MethodInfo method)
{
if (method == null)
return string.Empty;
StringBuilder sb = new StringBuilder();
string operatorName;
DecompileType_Helper(sb, method.DeclaringType);
sb.Append('.');
if (knownOperatorMap.TryGetValue(method.Name, out operatorName))
sb.Append(operatorName);
else
sb.Append(method.Name);
sb.Append('(');
ParameterInfo[] parms = method.GetParameters();
for (int i = 0; i < parms.Length; ++i)
{
DecompileType_Helper(sb, parms[i].ParameterType);
if (i != parms.Length - 1)
sb.Append(", ");
}
sb.Append(')');
return sb.ToString();
}
private static Dictionary<string, string> knownOperatorMap = InitializeKnownOperatorMap();
private static Dictionary<string, string> InitializeKnownOperatorMap()
{
Dictionary<string, string> map = new Dictionary<string, string>(27);
// unary operators
map.Add("op_UnaryPlus", "operator +");
map.Add("op_UnaryNegation", "operator -");
map.Add("op_OnesComplement", "operator ~");
map.Add("op_LogicalNot", "operator !");
map.Add("op_Increment", "operator ++");
map.Add("op_Decrement", "operator --");
map.Add("op_True", "operator true");
map.Add("op_False", "operator false");
map.Add("op_Implicit", "implicit operator");
map.Add("op_Explicit", "explicit operator");
// binary operators
map.Add("op_Equality", "operator ==");
map.Add("op_Inequality", "operator !=");
map.Add("op_GreaterThan", "operator >");
map.Add("op_GreaterThanOrEqual", "operator >=");
map.Add("op_LessThan", "operator <");
map.Add("op_LessThanOrEqual", "operator <=");
map.Add("op_Addition", "operator +");
map.Add("op_Subtraction", "operator -");
map.Add("op_Multiply", "operator *");
map.Add("op_Division", "operator /");
map.Add("op_IntegerDivision", "operator \\");
map.Add("op_Modulus", "operator %");
map.Add("op_LeftShift", "operator <<");
map.Add("op_RightShift", "operator >>");
map.Add("op_BitwiseAnd", "operator &");
map.Add("op_BitwiseOr", "operator |");
map.Add("op_ExclusiveOr", "operator ^");
return map;
}
#endregion
#region Operator Precedence
// These operations are sorted in order of precedence, lowest-to-highest
private enum Operation
{
RootExpression,
LogicalOr, // ||
LogicalAnd, // &&
BitwiseOr, // |
BitwiseAnd, // &
Equality, // == !=
Comparitive, // < <= > >=
Additive, // + -
Multiplicative, // * / %
Unary, // - ! (cast)
Postfix, // field/property ref and method call
NoParentheses // Highest
}
private delegate Operation ComputePrecedence(CodeExpression expresssion);
private static Dictionary<Type, ComputePrecedence> precedenceMap = InitializePrecedenceMap();
private static Dictionary<Type, ComputePrecedence> InitializePrecedenceMap()
{
Dictionary<Type, ComputePrecedence> map = new Dictionary<Type, ComputePrecedence>(7);
map.Add(typeof(CodeBinaryOperatorExpression), GetBinaryPrecedence);
map.Add(typeof(CodeCastExpression), GetCastPrecedence);
map.Add(typeof(CodeFieldReferenceExpression), GetPostfixPrecedence);
map.Add(typeof(CodePropertyReferenceExpression), GetPostfixPrecedence);
map.Add(typeof(CodeMethodInvokeExpression), GetPostfixPrecedence);
map.Add(typeof(CodeObjectCreateExpression), GetPostfixPrecedence);
map.Add(typeof(CodeArrayCreateExpression), GetPostfixPrecedence);
return map;
}
private static Operation GetPostfixPrecedence(CodeExpression expression)
{
return Operation.Postfix;
}
private static Operation GetCastPrecedence(CodeExpression expression)
{
return Operation.Unary;
}
private static Operation GetBinaryPrecedence(CodeExpression expression)
{
CodeBinaryOperatorExpression binaryExpr = (CodeBinaryOperatorExpression)expression;
Operation operation = Operation.NoParentheses;
switch (binaryExpr.Operator)
{
case CodeBinaryOperatorType.Multiply:
case CodeBinaryOperatorType.Divide:
case CodeBinaryOperatorType.Modulus:
operation = Operation.Multiplicative;
break;
case CodeBinaryOperatorType.Subtract:
case CodeBinaryOperatorType.Add:
operation = Operation.Additive;
break;
case CodeBinaryOperatorType.LessThan:
case CodeBinaryOperatorType.LessThanOrEqual:
case CodeBinaryOperatorType.GreaterThan:
case CodeBinaryOperatorType.GreaterThanOrEqual:
operation = Operation.Comparitive;
break;
case CodeBinaryOperatorType.IdentityEquality:
case CodeBinaryOperatorType.ValueEquality:
case CodeBinaryOperatorType.IdentityInequality:
operation = Operation.Equality;
break;
case CodeBinaryOperatorType.BitwiseAnd:
operation = Operation.BitwiseAnd;
break;
case CodeBinaryOperatorType.BitwiseOr:
operation = Operation.BitwiseOr;
break;
case CodeBinaryOperatorType.BooleanAnd:
operation = Operation.LogicalAnd;
break;
case CodeBinaryOperatorType.BooleanOr:
operation = Operation.LogicalOr;
break;
default:
string message = string.Format(CultureInfo.CurrentCulture, Messages.BinaryOpNotSupported, binaryExpr.Operator.ToString());
NotSupportedException exception = new NotSupportedException(message);
exception.Data[RuleUserDataKeys.ErrorObject] = binaryExpr;
throw exception;
}
return operation;
}
private static Operation GetPrecedence(CodeExpression expression)
{
// Assume the operation needs no parentheses.
Operation operation = Operation.NoParentheses;
ComputePrecedence computePrecedence;
if (precedenceMap.TryGetValue(expression.GetType(), out computePrecedence))
operation = computePrecedence(expression);
return operation;
}
internal static bool MustParenthesize(CodeExpression childExpr, CodeExpression parentExpr)
{
// No parent... we're at the root, so no need to parenthesize the root.
if (parentExpr == null)
return false;
Operation childOperation = GetPrecedence(childExpr);
Operation parentOperation = GetPrecedence(parentExpr);
if (parentOperation == childOperation)
{
CodeBinaryOperatorExpression parentBinary = parentExpr as CodeBinaryOperatorExpression;
if (parentBinary != null)
{
if (childExpr == parentBinary.Right)
{
// Something like 2 - (3 - 4) needs parentheses.
return true;
}
else
{
// Something like (2 - 3) - 4 doesn't need parentheses.
return false;
}
}
else
{
return false;
}
}
else if (parentOperation > childOperation)
{
return true;
}
else
{
return false;
}
}
#endregion
}
}
|