OptionalParametersParser.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using Clang.Ast;
  5. using ICSharpCode.NRefactory.CSharp;
  6. namespace SharpieBinder
  7. {
  8. public static class OptionalParametersParser
  9. {
  10. static readonly string[] MethodsToIgnore = {
  11. "SetTriangleMesh",
  12. "SetLayout",
  13. "DefineSprite",
  14. "SetConvexHull",
  15. };
  16. public static Expression Parse(ParmVarDecl param, CSharpParser parser)
  17. {
  18. string dump = param.DumpToString();
  19. var lines = dump.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
  20. if (lines.Length < 2 || MethodsToIgnore.Contains(((CXXMethodDecl)param.DeclContext).Name))
  21. return null;
  22. var defaultValueLine = lines.Last().TrimStart(' ', '-', '\t', '`');
  23. var words = defaultValueLine.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
  24. var expressionType = words[0];
  25. string defaultValue;
  26. Expression expression = null;
  27. if (expressionType.Contains("Literal")) //e.g. CXXBoolLiteralExpr, IntegerLiteral, etc
  28. {
  29. defaultValue = words.Last();
  30. if (expressionType.StartsWith("Floating")) //numbers come in a format like '1.000000e-01'
  31. defaultValue = float.Parse(defaultValue, CultureInfo.InvariantCulture).ToString() + "f";
  32. if (defaultValue == "0" && dump.Contains("NullToPointer"))
  33. defaultValue = "null";
  34. if (defaultValue == "0f" && dump.Contains("Urho3D::Color"))
  35. defaultValue = "default(Urho.Color)";
  36. expression = parser.ParseExpression(defaultValue);
  37. }
  38. else if (expressionType == "DeclRefExpr")
  39. {
  40. var items = defaultValueLine
  41. .Split(new[] { "'" }, StringSplitOptions.RemoveEmptyEntries)
  42. .Where(i => !string.IsNullOrWhiteSpace(i))
  43. .ToArray();
  44. defaultValue = $"{items[items.Length - 2]}";
  45. var type = items.Last();
  46. var clearType = type.DropConst().DropClassOrStructPrefix().DropUrhoNamespace();
  47. bool isEnum = type.Contains("enum ");
  48. expression = parser.ParseExpression(RemapValue(clearType, isEnum, defaultValue));
  49. }
  50. return expression;
  51. }
  52. static string RemapValue(string type, bool isEnum, string value)
  53. {
  54. if (value == "M_MAX_UNSIGNED") return "uint.MaxValue";
  55. if (value == "M_MIN_UNSIGNED") return "0";
  56. if (type == "String" && value == "EMPTY") return "\"\"";
  57. if (!isEnum)
  58. return "";
  59. return type + "." + StringUtil.RemapEnumName(type, value);
  60. }
  61. }
  62. }