diff --git a/src/DynamicExpresso.Core/Detector.cs b/src/DynamicExpresso.Core/Detector.cs index 756df976..240c9758 100644 --- a/src/DynamicExpresso.Core/Detector.cs +++ b/src/DynamicExpresso.Core/Detector.cs @@ -9,11 +9,11 @@ namespace DynamicExpresso { internal class Detector { - readonly ParserSettings _settings; - static readonly Regex IDENTIFIERS_DETECTION_REGEX = new Regex(@"([^\.]|^)\b(?[a-zA-Z_]\w*)\b", RegexOptions.Compiled); + private readonly ParserSettings _settings; + private static readonly Regex IDENTIFIERS_DETECTION_REGEX = new Regex(@"([^\.]|^)\b(?[a-zA-Z_]\w*)\b", RegexOptions.Compiled); - static readonly Regex STRING_DETECTION_REGEX = new Regex(@"(? public class Interpreter { - readonly ParserSettings _settings; - readonly ISet _visitors = new HashSet(); + private readonly ParserSettings _settings; + private readonly ISet _visitors = new HashSet(); #region Constructors /// @@ -403,7 +403,8 @@ public IdentifiersInfo DetectIdentifiers(string expression) #endregion #region Private methods - Lambda ParseAsLambda(string expressionText, Type expressionType, Parameter[] parameters) + + private Lambda ParseAsLambda(string expressionText, Type expressionType, Parameter[] parameters) { var arguments = new ParserArguments( expressionText, @@ -426,7 +427,7 @@ Lambda ParseAsLambda(string expressionText, Type expressionType, Parameter[] par } #if TEST_DetectIdentifiers - void AssertDetectIdentifiers(Lambda lambda) + private void AssertDetectIdentifiers(Lambda lambda) { var info = DetectIdentifiers(lambda.ExpressionText); diff --git a/src/DynamicExpresso.Core/Lambda.cs b/src/DynamicExpresso.Core/Lambda.cs index 68569fa2..61a6a4e3 100644 --- a/src/DynamicExpresso.Core/Lambda.cs +++ b/src/DynamicExpresso.Core/Lambda.cs @@ -12,10 +12,10 @@ namespace DynamicExpresso /// public class Lambda { - readonly Expression _expression; - readonly ParserArguments _parserArguments; + private readonly Expression _expression; + private readonly ParserArguments _parserArguments; - readonly Delegate _delegate; + private readonly Delegate _delegate; internal Lambda(Expression expression, ParserArguments parserArguments) { diff --git a/src/DynamicExpresso.Core/LanguageConstants.cs b/src/DynamicExpresso.Core/LanguageConstants.cs index 380a8ccf..9c40c192 100644 --- a/src/DynamicExpresso.Core/LanguageConstants.cs +++ b/src/DynamicExpresso.Core/LanguageConstants.cs @@ -7,21 +7,21 @@ namespace DynamicExpresso public static class LanguageConstants { public static readonly ReferenceType[] PrimitiveTypes = { - new ReferenceType(typeof(Object)), - new ReferenceType(typeof(Boolean)), - new ReferenceType(typeof(Char)), - new ReferenceType(typeof(String)), - new ReferenceType(typeof(SByte)), - new ReferenceType(typeof(Byte)), - new ReferenceType(typeof(Int16)), - new ReferenceType(typeof(UInt16)), - new ReferenceType(typeof(Int32)), - new ReferenceType(typeof(UInt32)), - new ReferenceType(typeof(Int64)), - new ReferenceType(typeof(UInt64)), - new ReferenceType(typeof(Single)), - new ReferenceType(typeof(Double)), - new ReferenceType(typeof(Decimal)), + new ReferenceType(typeof(object)), + new ReferenceType(typeof(bool)), + new ReferenceType(typeof(char)), + new ReferenceType(typeof(string)), + new ReferenceType(typeof(sbyte)), + new ReferenceType(typeof(byte)), + new ReferenceType(typeof(short)), + new ReferenceType(typeof(ushort)), + new ReferenceType(typeof(int)), + new ReferenceType(typeof(uint)), + new ReferenceType(typeof(long)), + new ReferenceType(typeof(ulong)), + new ReferenceType(typeof(float)), + new ReferenceType(typeof(double)), + new ReferenceType(typeof(decimal)), new ReferenceType(typeof(DateTime)), new ReferenceType(typeof(TimeSpan)), new ReferenceType(typeof(Guid)) diff --git a/src/DynamicExpresso.Core/ParserArguments.cs b/src/DynamicExpresso.Core/ParserArguments.cs index c17eb614..26dd0657 100644 --- a/src/DynamicExpresso.Core/ParserArguments.cs +++ b/src/DynamicExpresso.Core/ParserArguments.cs @@ -9,11 +9,11 @@ namespace DynamicExpresso { internal class ParserArguments { - readonly Dictionary _declaredParameters; + private readonly Dictionary _declaredParameters; - readonly HashSet _usedParameters = new HashSet(); - readonly HashSet _usedTypes = new HashSet(); - readonly HashSet _usedIdentifiers = new HashSet(); + private readonly HashSet _usedParameters = new HashSet(); + private readonly HashSet _usedTypes = new HashSet(); + private readonly HashSet _usedIdentifiers = new HashSet(); public ParserArguments( string expressionText, diff --git a/src/DynamicExpresso.Core/Parsing/Parser.cs b/src/DynamicExpresso.Core/Parsing/Parser.cs index 6beffd69..3b81551f 100644 --- a/src/DynamicExpresso.Core/Parsing/Parser.cs +++ b/src/DynamicExpresso.Core/Parsing/Parser.cs @@ -24,26 +24,26 @@ public static Expression Parse(ParserArguments arguments) return new Parser(arguments).Parse(); } - const NumberStyles ParseLiteralNumberStyle = NumberStyles.AllowLeadingSign; - const NumberStyles ParseLiteralUnsignedNumberStyle = NumberStyles.AllowLeadingSign; - const NumberStyles ParseLiteralDecimalNumberStyle = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint; - static CultureInfo ParseCulture = CultureInfo.InvariantCulture; + private const NumberStyles ParseLiteralNumberStyle = NumberStyles.AllowLeadingSign; + private const NumberStyles ParseLiteralUnsignedNumberStyle = NumberStyles.AllowLeadingSign; + private const NumberStyles ParseLiteralDecimalNumberStyle = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint; + private static readonly CultureInfo ParseCulture = CultureInfo.InvariantCulture; - ParserArguments _arguments; + private readonly ParserArguments _arguments; // Working context implementation //ParameterExpression it; - int _parsePosition; - string _expressionText; - int _expressionTextLength; - char _parseChar; - Token _token; + private int _parsePosition; + private readonly string _expressionText; + private readonly int _expressionTextLength; + private char _parseChar; + private Token _token; - BindingFlags _bindingCase; - MemberFilter _memberFilterCase; + private readonly BindingFlags _bindingCase; + private readonly MemberFilter _memberFilterCase; - Parser(ParserArguments arguments) + private Parser(ParserArguments arguments) { _arguments = arguments; @@ -56,7 +56,7 @@ public static Expression Parse(ParserArguments arguments) NextToken(); } - Expression Parse() + private Expression Parse() { Expression expr = ParseExpressionSegment(_arguments.ExpressionReturnType); @@ -64,7 +64,7 @@ Expression Parse() return expr; } - Expression ParseExpressionSegment(Type returnType) + private Expression ParseExpressionSegment(Type returnType) { int errorPos = _token.pos; var expression = ParseExpressionSegment(); @@ -77,7 +77,7 @@ Expression ParseExpressionSegment(Type returnType) return expression; } - Expression ParseExpressionSegment() + private Expression ParseExpressionSegment() { // The following methods respect the operator precedence as defined in // MSDN C# "Operator precedence and associativity" @@ -87,7 +87,7 @@ Expression ParseExpressionSegment() } // = operator - Expression ParseAssignement() + private Expression ParseAssignement() { var left = ParseConditional(); if (_token.id == TokenId.Equal) @@ -105,7 +105,7 @@ Expression ParseAssignement() } // ?: operator - Expression ParseConditional() + private Expression ParseConditional() { var errorPos = _token.pos; var expr = ParseLogicalOr(); @@ -122,7 +122,7 @@ Expression ParseConditional() } // || operator - Expression ParseLogicalOr() + private Expression ParseLogicalOr() { var left = ParseLogicalAnd(); while (_token.id == TokenId.DoubleBar) @@ -137,7 +137,7 @@ Expression ParseLogicalOr() } // && operator - Expression ParseLogicalAnd() + private Expression ParseLogicalAnd() { var left = ParseComparison(); while (_token.id == TokenId.DoubleAmphersand) @@ -152,7 +152,7 @@ Expression ParseLogicalAnd() } // ==, !=, >, >=, <, <= operators - Expression ParseComparison() + private Expression ParseComparison() { var left = ParseTypeTesting(); while (_token.id == TokenId.DoubleEqual || _token.id == TokenId.ExclamationEqual || @@ -238,7 +238,7 @@ Expression ParseComparison() } // is, as operators - Expression ParseTypeTesting() + private Expression ParseTypeTesting() { var left = ParseAdditive(); while (_token.text == ParserConstants.KEYWORD_IS @@ -267,7 +267,7 @@ Expression ParseTypeTesting() } // +, -, & operators - Expression ParseAdditive() + private Expression ParseAdditive() { var left = ParseMultiplicative(); while (_token.id == TokenId.Plus || _token.id == TokenId.Minus) @@ -298,7 +298,7 @@ Expression ParseAdditive() } // *, /, % operators - Expression ParseMultiplicative() + private Expression ParseMultiplicative() { var left = ParseUnary(); while (_token.id == TokenId.Asterisk || _token.id == TokenId.Slash || @@ -327,7 +327,7 @@ Expression ParseMultiplicative() } // +,-, ! unary operators - Expression ParseUnary() + private Expression ParseUnary() { if (_token.id == TokenId.Minus || _token.id == TokenId.Exclamation || _token.id == TokenId.Plus) { @@ -370,7 +370,7 @@ Expression ParseUnary() return ParsePrimary(); } - Expression ParsePrimary() + private Expression ParsePrimary() { var tokenPos = _token.pos; var expr = ParsePrimaryStart(); @@ -403,7 +403,7 @@ Expression ParsePrimary() return expr; } - Expression ParsePrimaryStart() + private Expression ParsePrimaryStart() { switch (_token.id) { @@ -426,7 +426,7 @@ Expression ParsePrimaryStart() } } - Expression ParseCharLiteral() + private Expression ParseCharLiteral() { ValidateToken(TokenId.CharLiteral); var s = _token.text.Substring(1, _token.text.Length - 2); @@ -440,7 +440,7 @@ Expression ParseCharLiteral() return CreateLiteral(s[0], s); } - Expression ParseStringLiteral() + private Expression ParseStringLiteral() { ValidateToken(TokenId.StringLiteral); var s = _token.text.Substring(1, _token.text.Length - 2); @@ -461,7 +461,7 @@ Expression ParseStringLiteral() return CreateLiteral(s, s); } - string EvalEscapeStringLiteral(string source) + private string EvalEscapeStringLiteral(string source) { var builder = new StringBuilder(); @@ -482,7 +482,7 @@ string EvalEscapeStringLiteral(string source) return builder.ToString(); } - char EvalEscapeChar(char source) + private char EvalEscapeChar(char source) { switch (source) { @@ -513,23 +513,23 @@ char EvalEscapeChar(char source) } } - Expression ParseIntegerLiteral() + private Expression ParseIntegerLiteral() { ValidateToken(TokenId.IntegerLiteral); - string text = _token.text; + var text = _token.text; if (text[0] != '-') { ulong value; - if (!UInt64.TryParse(text, ParseLiteralUnsignedNumberStyle, ParseCulture, out value)) + if (!ulong.TryParse(text, ParseLiteralUnsignedNumberStyle, ParseCulture, out value)) throw CreateParseException(_token.pos, ErrorMessages.InvalidIntegerLiteral, text); NextToken(); - if (value <= (ulong)Int32.MaxValue) + if (value <= int.MaxValue) return CreateLiteral((int)value, text); - if (value <= (ulong)UInt32.MaxValue) + if (value <= uint.MaxValue) return CreateLiteral((uint)value, text); - if (value <= (ulong)Int64.MaxValue) + if (value <= long.MaxValue) return CreateLiteral((long)value, text); return CreateLiteral(value, text); @@ -537,19 +537,19 @@ Expression ParseIntegerLiteral() else { long value; - if (!Int64.TryParse(text, ParseLiteralNumberStyle, ParseCulture, out value)) + if (!long.TryParse(text, ParseLiteralNumberStyle, ParseCulture, out value)) throw CreateParseException(_token.pos, ErrorMessages.InvalidIntegerLiteral, text); NextToken(); - if (value >= Int32.MinValue && value <= Int32.MaxValue) + if (value >= int.MinValue && value <= int.MaxValue) return CreateLiteral((int)value, text); return CreateLiteral(value, text); } } - Expression ParseRealLiteral() + private Expression ParseRealLiteral() { ValidateToken(TokenId.RealLiteral); string text = _token.text; @@ -582,14 +582,14 @@ Expression ParseRealLiteral() return CreateLiteral(value, text); } - Expression CreateLiteral(object value, string text) + private static Expression CreateLiteral(object value, string text) { - ConstantExpression expr = Expression.Constant(value); + var expr = Expression.Constant(value); return expr; } - Expression ParseParenExpression() + private Expression ParseParenExpression() { ValidateToken(TokenId.OpenParen, ErrorMessages.OpenParenExpected); NextToken(); @@ -610,7 +610,7 @@ Expression ParseParenExpression() return innerParenthesesExpression; } - Expression ParseIdentifier() + private Expression ParseIdentifier() { ValidateToken(TokenId.Identifier); @@ -669,7 +669,7 @@ Expression ParseIdentifier() // return GenerateConditional(args[0], args[1], args[2], errorPos); //} - Expression ParseTypeof() + private Expression ParseTypeof() { var errorPos = _token.pos; NextToken(); @@ -684,7 +684,7 @@ Expression ParseTypeof() return constExp; } - Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos) + private Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos) { if (test.Type != typeof(bool)) throw CreateParseException(errorPos, ErrorMessages.FirstExprMustBeBool); @@ -713,7 +713,7 @@ Expression GenerateConditional(Expression test, Expression expr1, Expression exp return Expression.Condition(test, expr1, expr2); } - Expression ParseNew() + private Expression ParseNew() { NextToken(); ValidateToken(TokenId.Identifier, ErrorMessages.IdentifierExpected); @@ -732,7 +732,7 @@ Expression ParseNew() return Expression.MemberInit(Expression.New(constructor, args)); } - Expression ParseLambdaInvocation(LambdaExpression lambda, int errorPos) + private Expression ParseLambdaInvocation(LambdaExpression lambda, int errorPos) { var args = ParseArgumentList(); @@ -742,7 +742,7 @@ Expression ParseLambdaInvocation(LambdaExpression lambda, int errorPos) return Expression.Invoke(lambda, args); } - Expression ParseDelegateInvocation(Expression delegateExp, int errorPos) + private Expression ParseDelegateInvocation(Expression delegateExp, int errorPos) { var args = ParseArgumentList(); @@ -752,7 +752,7 @@ Expression ParseDelegateInvocation(Expression delegateExp, int errorPos) return Expression.Invoke(delegateExp, args); } - bool PrepareDelegateInvoke(Type type, ref Expression[] args) + private bool PrepareDelegateInvoke(Type type, ref Expression[] args) { var applicableMethods = FindMethods(type, "Invoke", false, args); if (applicableMethods.Length != 1) @@ -763,7 +763,7 @@ bool PrepareDelegateInvoke(Type type, ref Expression[] args) return true; } - Expression ParseTypeKeyword(Type type) + private Expression ParseTypeKeyword(Type type) { var errorPos = _token.pos; NextToken(); @@ -807,7 +807,7 @@ Expression ParseTypeKeyword(Type type) // } //} - Expression GenerateConversion(Expression expr, Type type, int errorPos) + private Expression GenerateConversion(Expression expr, Type type, int errorPos) { var exprType = expr.Type; if (exprType == type) @@ -842,7 +842,7 @@ Expression GenerateConversion(Expression expr, Type type, int errorPos) } } - Expression ParseMemberAccess(Type type, Expression instance) + private Expression ParseMemberAccess(Type type, Expression instance) { if (instance != null) type = instance.Type; var errorPos = _token.pos; @@ -854,7 +854,7 @@ Expression ParseMemberAccess(Type type, Expression instance) return GeneratePropertyOrFieldExpression(type, instance, errorPos, id); } - Expression GeneratePropertyOrFieldExpression(Type type, Expression instance, int errorPos, string propertyOrFieldName) + private Expression GeneratePropertyOrFieldExpression(Type type, Expression instance, int errorPos, string propertyOrFieldName) { var member = FindPropertyOrField(type, propertyOrFieldName, instance == null); if (member != null) @@ -870,7 +870,7 @@ Expression GeneratePropertyOrFieldExpression(Type type, Expression instance, int throw CreateParseException(errorPos, ErrorMessages.UnknownPropertyOrField, propertyOrFieldName, GetTypeName(type)); } - Expression ParseMethodInvocation(Type type, Expression instance, int errorPos, string methodName) + private Expression ParseMethodInvocation(Type type, Expression instance, int errorPos, string methodName) { var args = ParseArgumentList(); @@ -889,7 +889,7 @@ Expression ParseMethodInvocation(Type type, Expression instance, int errorPos, s throw new NoApplicableMethodException(methodName, GetTypeName(type), errorPos); } - Expression ParseExtensionMethodInvocation(Type type, Expression instance, int errorPos, string id, Expression[] args) + private Expression ParseExtensionMethodInvocation(Type type, Expression instance, int errorPos, string id, Expression[] args) { var extensionMethodsArguments = new Expression[args.Length + 1]; extensionMethodsArguments[0] = instance; @@ -911,7 +911,7 @@ Expression ParseExtensionMethodInvocation(Type type, Expression instance, int er return null; } - Expression ParseNormalMethodInvocation(Type type, Expression instance, int errorPos, string id, Expression[] args) + private Expression ParseNormalMethodInvocation(Type type, Expression instance, int errorPos, string id, Expression[] args) { var applicableMethods = FindMethods(type, id, instance == null, args); if (applicableMethods.Length > 1) @@ -1002,7 +1002,7 @@ private static Expression ParseDynamicMethodInvocation(Type type, Expression ins return Expression.Dynamic(binderM, typeof(object), argsDynamic); } - Expression[] ParseArgumentList() + private Expression[] ParseArgumentList() { ValidateToken(TokenId.OpenParen, ErrorMessages.OpenParenExpected); NextToken(); @@ -1012,7 +1012,7 @@ Expression[] ParseArgumentList() return args; } - Expression[] ParseArguments() + private Expression[] ParseArguments() { var argList = new List(); while (true) @@ -1024,7 +1024,7 @@ Expression[] ParseArguments() return argList.ToArray(); } - Expression ParseElementAccess(Expression expr) + private Expression ParseElementAccess(Expression expr) { var errorPos = _token.pos; ValidateToken(TokenId.OpenBracket, ErrorMessages.OpenParenExpected); @@ -1041,48 +1041,46 @@ Expression ParseElementAccess(Expression expr) throw CreateParseException(errorPos, ErrorMessages.InvalidIndex); return Expression.ArrayIndex(expr, index); } - else + + var applicableMethods = FindIndexer(expr.Type, args); + if (applicableMethods.Length == 0) { - var applicableMethods = FindIndexer(expr.Type, args); - if (applicableMethods.Length == 0) - { - throw CreateParseException(errorPos, ErrorMessages.NoApplicableIndexer, - GetTypeName(expr.Type)); - } + throw CreateParseException(errorPos, ErrorMessages.NoApplicableIndexer, + GetTypeName(expr.Type)); + } - if (applicableMethods.Length > 1) - { - throw CreateParseException(errorPos, ErrorMessages.AmbiguousIndexerInvocation, - GetTypeName(expr.Type)); - } + if (applicableMethods.Length > 1) + { + throw CreateParseException(errorPos, ErrorMessages.AmbiguousIndexerInvocation, + GetTypeName(expr.Type)); + } - var method = applicableMethods[0]; + var method = applicableMethods[0]; - return Expression.Call(expr, (MethodInfo)method.MethodBase, method.PromotedParameters); - } + return Expression.Call(expr, (MethodInfo)method.MethodBase, method.PromotedParameters); } - static bool IsNullableType(Type type) + private static bool IsNullableType(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } - static bool IsDynamicType(Type type) + private static bool IsDynamicType(Type type) { return typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type); } - static bool IsDynamicExpression(Expression instance) + private static bool IsDynamicExpression(Expression instance) { return instance != null && instance.NodeType == ExpressionType.Dynamic; } - static Type GetNonNullableType(Type type) + private static Type GetNonNullableType(Type type) { return IsNullableType(type) ? type.GetGenericArguments()[0] : type; } - static string GetTypeName(Type type) + private static string GetTypeName(Type type) { var baseType = GetNonNullableType(type); var s = baseType.Name; @@ -1095,17 +1093,17 @@ static string GetTypeName(Type type) // return GetNumericTypeKind(type) != 0; //} - static bool IsSignedIntegralType(Type type) + private static bool IsSignedIntegralType(Type type) { return GetNumericTypeKind(type) == 2; } - static bool IsUnsignedIntegralType(Type type) + private static bool IsUnsignedIntegralType(Type type) { return GetNumericTypeKind(type) == 3; } - static int GetNumericTypeKind(Type type) + private static int GetNumericTypeKind(Type type) { type = GetNonNullableType(type); if (type.IsEnum) return 0; @@ -1136,18 +1134,18 @@ static int GetNumericTypeKind(Type type) // return GetNonNullableType(type).IsEnum; //} - void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos) + private void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos) { - var args = new [] { expr }; + var args = new[] { expr }; args = PrepareOperandArguments(signatures, args); expr = args[0]; } - void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos) + private void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos) { - var args = new [] { left, right }; + var args = new[] { left, right }; args = PrepareOperandArguments(signatures, args); @@ -1155,7 +1153,7 @@ void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left right = args[1]; } - Expression[] PrepareOperandArguments(Type signatures, Expression[] args) + private Expression[] PrepareOperandArguments(Type signatures, Expression[] args) { var applicableMethods = FindMethods(signatures, "F", false, args); if (applicableMethods.Length == 1) @@ -1164,7 +1162,7 @@ Expression[] PrepareOperandArguments(Type signatures, Expression[] args) return args; } - MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess) + private MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess) { var flags = BindingFlags.Public | BindingFlags.DeclaredOnly | (staticAccess ? BindingFlags.Static : BindingFlags.Instance) | _bindingCase; @@ -1178,7 +1176,7 @@ MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess) return null; } - MethodData[] FindMethods(Type type, string methodName, bool staticAccess, Expression[] args) + private MethodData[] FindMethods(Type type, string methodName, bool staticAccess, Expression[] args) { //var exactMethod = type.GetMethod(methodName, args.Select(p => p.Type).ToArray()); //if (exactMethod != null) @@ -1200,14 +1198,14 @@ MethodData[] FindMethods(Type type, string methodName, bool staticAccess, Expres return new MethodData[0]; } - MethodData[] FindExtensionMethods(Type type, string methodName, Expression[] args) + private MethodData[] FindExtensionMethods(Type type, string methodName, Expression[] args) { var matchMethods = _arguments.GetExtensionMethods(methodName); return FindBestMethod(matchMethods, args); } - MethodData[] FindIndexer(Type type, Expression[] args) + private MethodData[] FindIndexer(Type type, Expression[] args) { foreach (var t in SelfAndBaseTypes(type)) { @@ -1228,7 +1226,7 @@ MethodData[] FindIndexer(Type type, Expression[] args) return new MethodData[0]; } - static IEnumerable SelfAndBaseTypes(Type type) + private static IEnumerable SelfAndBaseTypes(Type type) { if (type.IsInterface) { @@ -1242,7 +1240,7 @@ static IEnumerable SelfAndBaseTypes(Type type) return SelfAndBaseClasses(type); } - static IEnumerable SelfAndBaseClasses(Type type) + private static IEnumerable SelfAndBaseClasses(Type type) { while (type != null) { @@ -1251,7 +1249,7 @@ static IEnumerable SelfAndBaseClasses(Type type) } } - static void AddInterface(List types, Type type) + private static void AddInterface(List types, Type type) { if (!types.Contains(type)) { @@ -1263,7 +1261,7 @@ static void AddInterface(List types, Type type) } } - class MethodData + private class MethodData { public MethodBase MethodBase; public ParameterInfo[] Parameters; @@ -1271,7 +1269,7 @@ class MethodData public bool HasParamsArray; } - MethodData[] FindBestMethod(IEnumerable methods, Expression[] args) + private MethodData[] FindBestMethod(IEnumerable methods, Expression[] args) { var applicable = methods. Select(m => new MethodData { MethodBase = m, Parameters = m.GetParameters() }). @@ -1287,7 +1285,7 @@ MethodData[] FindBestMethod(IEnumerable methods, Expression[] args) return applicable; } - bool CheckIfMethodIsApplicableAndPrepareIt(MethodData method, Expression[] args) + private bool CheckIfMethodIsApplicableAndPrepareIt(MethodData method, Expression[] args) { if (method.Parameters.Length > args.Length) return false; @@ -1384,7 +1382,7 @@ bool CheckIfMethodIsApplicableAndPrepareIt(MethodData method, Expression[] args) return true; } - List ExtractActualGenericArguments(Type[] requestedParameters, Type[] actualParameters) + private List ExtractActualGenericArguments(Type[] requestedParameters, Type[] actualParameters) { var extractedGenericTypes = new List(); @@ -1408,7 +1406,7 @@ List ExtractActualGenericArguments(Type[] requestedParameters, Type[] actu return extractedGenericTypes; } - Expression PromoteExpression(Expression expr, Type type, bool exact) + private Expression PromoteExpression(Expression expr, Type type, bool exact) { if (expr.Type == type) return expr; if (expr is ConstantExpression) @@ -1504,7 +1502,7 @@ Expression PromoteExpression(Expression expr, Type type, bool exact) // return null; //} - static bool IsCompatibleWith(Type source, Type target) + private static bool IsCompatibleWith(Type source, Type target) { if (source == target) { @@ -1636,7 +1634,7 @@ static bool IsCompatibleWith(Type source, Type target) } // from http://stackoverflow.com/a/1075059/209727 - static Type FindAssignableGenericType(Type givenType, Type genericTypeDefinition) + private static Type FindAssignableGenericType(Type givenType, Type genericTypeDefinition) { var interfaceTypes = givenType.GetInterfaces(); @@ -1649,29 +1647,30 @@ static Type FindAssignableGenericType(Type givenType, Type genericTypeDefinition } if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericTypeDefinition) - { return givenType; - } - Type baseType = givenType.BaseType; - if (baseType == null) return null; + var baseType = givenType.BaseType; + if (baseType == null) + return null; return FindAssignableGenericType(baseType, genericTypeDefinition); } - static bool HasParamsArrayType(ParameterInfo parameterInfo) + private static bool HasParamsArrayType(ParameterInfo parameterInfo) { return parameterInfo.IsDefined(typeof(ParamArrayAttribute), false); } - static Type GetParameterType(ParameterInfo parameterInfo) + private static Type GetParameterType(ParameterInfo parameterInfo) { - bool isParamsArray = HasParamsArrayType(parameterInfo); - Type type = isParamsArray ? parameterInfo.ParameterType.GetElementType() : parameterInfo.ParameterType; + var isParamsArray = HasParamsArrayType(parameterInfo); + var type = isParamsArray + ? parameterInfo.ParameterType.GetElementType() + : parameterInfo.ParameterType; return type; } - static bool MethodHasPriority(Expression[] args, MethodData method, MethodData otherMethod) + private static bool MethodHasPriority(Expression[] args, MethodData method, MethodData otherMethod) { if (method.HasParamsArray == false && otherMethod.HasParamsArray) return true; @@ -1683,20 +1682,20 @@ static bool MethodHasPriority(Expression[] args, MethodData method, MethodData o //else if (m1.Parameters.Length < m2.Parameters.Length) // return false; - bool better = false; - for (int i = 0; i < args.Length; i++) + var better = false; + for (var i = 0; i < args.Length; i++) { - ParameterInfo methodParam = method.Parameters[i]; - ParameterInfo otherMethodParam = otherMethod.Parameters[i]; - Type methodParamType = GetParameterType(methodParam); - Type otherMethodParamType = GetParameterType(otherMethodParam); - int c = CompareConversions(args[i].Type, methodParamType, otherMethodParamType); - if (c < 0) return false; - if (c > 0) better = true; + var methodParam = method.Parameters[i]; + var otherMethodParam = otherMethod.Parameters[i]; + var methodParamType = GetParameterType(methodParam); + var otherMethodParamType = GetParameterType(otherMethodParam); + var c = CompareConversions(args[i].Type, methodParamType, otherMethodParamType); + if (c < 0) + return false; + if (c > 0) + better = true; if (HasParamsArrayType(methodParam) || HasParamsArrayType(otherMethodParam)) - { break; - } } return better; } @@ -1704,19 +1703,19 @@ static bool MethodHasPriority(Expression[] args, MethodData method, MethodData o // Return 1 if s -> t1 is a better conversion than s -> t2 // Return -1 if s -> t2 is a better conversion than s -> t1 // Return 0 if neither conversion is better - static int CompareConversions(Type s, Type t1, Type t2) + private static int CompareConversions(Type s, Type t1, Type t2) { if (t1 == t2) return 0; if (s == t1) return 1; if (s == t2) return -1; - bool assignableT1 = t1.IsAssignableFrom(s); - bool assignableT2 = t2.IsAssignableFrom(s); + var assignableT1 = t1.IsAssignableFrom(s); + var assignableT2 = t2.IsAssignableFrom(s); if (assignableT1 && !assignableT2) return 1; if (assignableT2 && !assignableT1) return -1; - bool compatibleT1t2 = IsCompatibleWith(t1, t2); - bool compatibleT2t1 = IsCompatibleWith(t2, t1); + var compatibleT1t2 = IsCompatibleWith(t1, t2); + var compatibleT2t1 = IsCompatibleWith(t2, t1); if (compatibleT1t2 && !compatibleT2t1) return 1; if (compatibleT2t1 && !compatibleT1t2) return -1; @@ -1726,17 +1725,17 @@ static int CompareConversions(Type s, Type t1, Type t2) return 0; } - Expression GenerateEqual(Expression left, Expression right) + private Expression GenerateEqual(Expression left, Expression right) { return Expression.Equal(left, right); } - Expression GenerateNotEqual(Expression left, Expression right) + private Expression GenerateNotEqual(Expression left, Expression right) { return Expression.NotEqual(left, right); } - Expression GenerateGreaterThan(Expression left, Expression right) + private Expression GenerateGreaterThan(Expression left, Expression right) { if (left.Type == typeof(string)) { @@ -1748,7 +1747,7 @@ Expression GenerateGreaterThan(Expression left, Expression right) return Expression.GreaterThan(left, right); } - Expression GenerateGreaterThanEqual(Expression left, Expression right) + private Expression GenerateGreaterThanEqual(Expression left, Expression right) { if (left.Type == typeof(string)) { @@ -1760,7 +1759,7 @@ Expression GenerateGreaterThanEqual(Expression left, Expression right) return Expression.GreaterThanOrEqual(left, right); } - Expression GenerateLessThan(Expression left, Expression right) + private Expression GenerateLessThan(Expression left, Expression right) { if (left.Type == typeof(string)) { @@ -1772,7 +1771,7 @@ Expression GenerateLessThan(Expression left, Expression right) return Expression.LessThan(left, right); } - Expression GenerateLessThanEqual(Expression left, Expression right) + private Expression GenerateLessThanEqual(Expression left, Expression right) { if (left.Type == typeof(string)) { @@ -1784,7 +1783,7 @@ Expression GenerateLessThanEqual(Expression left, Expression right) return Expression.LessThanOrEqual(left, right); } - Expression GenerateAdd(Expression left, Expression right) + private Expression GenerateAdd(Expression left, Expression right) { if (left.Type == typeof(string) && right.Type == typeof(string)) { @@ -1793,36 +1792,40 @@ Expression GenerateAdd(Expression left, Expression right) return Expression.Add(left, right); } - Expression GenerateSubtract(Expression left, Expression right) + private Expression GenerateSubtract(Expression left, Expression right) { return Expression.Subtract(left, right); } - Expression GenerateStringConcat(Expression left, Expression right) + private Expression GenerateStringConcat(Expression left, Expression right) { + var concatMethod = typeof(string).GetMethod("Concat", new[] {typeof(object), typeof(object)}); + if (concatMethod == null) + throw new Exception("String concat not found"); + return Expression.Call( null, - typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }), + concatMethod, new[] { left, right }); } - MethodInfo GetStaticMethod(string methodName, Expression left, Expression right) + private MethodInfo GetStaticMethod(string methodName, Expression left, Expression right) { return left.Type.GetMethod(methodName, new[] { left.Type, right.Type }); } - Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right) + private Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right) { return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] { left, right }); } - void SetTextPos(int pos) + private void SetTextPos(int pos) { _parsePosition = pos; _parseChar = _parsePosition < _expressionTextLength ? _expressionText[_parsePosition] : '\0'; } - void NextChar() + private void NextChar() { if (_parsePosition < _expressionTextLength) _parsePosition++; @@ -1830,19 +1833,19 @@ void NextChar() _parseChar = _parsePosition < _expressionTextLength ? _expressionText[_parsePosition] : '\0'; } - void PreviousChar() + private void PreviousChar() { SetTextPos(_parsePosition - 1); } - void NextToken() + private void NextToken() { while (char.IsWhiteSpace(_parseChar)) NextChar(); - TokenId t = TokenId.Unknown; - var tokenPos = _parsePosition; - switch (_parseChar) + TokenId t; + var tokenPos = _parsePosition; + switch (_parseChar) { case '!': NextChar(); @@ -1898,30 +1901,32 @@ void NextToken() break; case '.': NextChar(); - if (Char.IsDigit(_parseChar)) - { - t = TokenId.RealLiteral; - do - { - NextChar(); - } while (Char.IsDigit(_parseChar)); - if (_parseChar == 'E' || _parseChar == 'e') - { - t = TokenId.RealLiteral; - NextChar(); - if (_parseChar == '+' || _parseChar == '-') - NextChar(); - ValidateDigit(); - do - { - NextChar(); - } while (Char.IsDigit(_parseChar)); - } - if (_parseChar == 'F' || _parseChar == 'f' || _parseChar == 'M' || _parseChar == 'm') - NextChar(); - break; - } - t = TokenId.Dot; + + if (char.IsDigit(_parseChar)) + { + t = TokenId.RealLiteral; + do + { + NextChar(); + } while (char.IsDigit(_parseChar)); + if (_parseChar == 'E' || _parseChar == 'e') + { + t = TokenId.RealLiteral; + NextChar(); + if (_parseChar == '+' || _parseChar == '-') + NextChar(); + ValidateDigit(); + do + { + NextChar(); + } while (char.IsDigit(_parseChar)); + } + if (_parseChar == 'F' || _parseChar == 'f' || _parseChar == 'M' || _parseChar == 'm') + NextChar(); + break; + } + + t = TokenId.Dot; break; case '/': NextChar(); @@ -2029,34 +2034,34 @@ void NextToken() break; default: - if (Char.IsLetter(_parseChar) || _parseChar == '@' || _parseChar == '_') + if (char.IsLetter(_parseChar) || _parseChar == '@' || _parseChar == '_') { do { NextChar(); - } while (Char.IsLetterOrDigit(_parseChar) || _parseChar == '_'); + } while (char.IsLetterOrDigit(_parseChar) || _parseChar == '_'); t = TokenId.Identifier; break; } - if (Char.IsDigit(_parseChar)) + if (char.IsDigit(_parseChar)) { t = TokenId.IntegerLiteral; do { NextChar(); - } while (Char.IsDigit(_parseChar)); + } while (char.IsDigit(_parseChar)); if (_parseChar == '.') { NextChar(); - if (Char.IsDigit(_parseChar)) + if (char.IsDigit(_parseChar)) { t = TokenId.RealLiteral; do { NextChar(); - } while (Char.IsDigit(_parseChar)); + } while (char.IsDigit(_parseChar)); } else { @@ -2075,7 +2080,7 @@ void NextToken() do { NextChar(); - } while (Char.IsDigit(_parseChar)); + } while (char.IsDigit(_parseChar)); } if (_parseChar == 'F' || _parseChar == 'f' || _parseChar == 'M' || _parseChar == 'm') NextChar(); @@ -2088,17 +2093,12 @@ void NextToken() } throw CreateParseException(_parsePosition, ErrorMessages.InvalidCharacter, _parseChar); } - _token.id = t; + _token.id = t; _token.text = _expressionText.Substring(tokenPos, _parsePosition - tokenPos); _token.pos = tokenPos; } - //bool TokenIdentifierIs(string id) - //{ - // return _token.id == TokenId.Identifier && String.Equals(id, _token.text, StringComparison.OrdinalIgnoreCase); - //} - - string GetIdentifier() + private string GetIdentifier() { ValidateToken(TokenId.Identifier, ErrorMessages.IdentifierExpected); string id = _token.text; @@ -2107,25 +2107,25 @@ string GetIdentifier() return id; } - void ValidateDigit() + private void ValidateDigit() { if (!char.IsDigit(_parseChar)) throw CreateParseException(_parsePosition, ErrorMessages.DigitExpected); } - void ValidateToken(TokenId t, string errorMessage) + private void ValidateToken(TokenId t, string errorMessage) { if (_token.id != t) throw CreateParseException(_token.pos, errorMessage); } - void ValidateToken(TokenId t) + private void ValidateToken(TokenId t) { if (_token.id != t) throw CreateParseException(_token.pos, ErrorMessages.SyntaxError); } - Exception CreateParseException(int pos, string format, params object[] args) + private Exception CreateParseException(int pos, string format, params object[] args) { return new ParseException(string.Format(format, args), pos); } diff --git a/src/DynamicExpresso.Core/Parsing/ParserSettings.cs b/src/DynamicExpresso.Core/Parsing/ParserSettings.cs index cb6d4380..913dad40 100644 --- a/src/DynamicExpresso.Core/Parsing/ParserSettings.cs +++ b/src/DynamicExpresso.Core/Parsing/ParserSettings.cs @@ -6,9 +6,9 @@ namespace DynamicExpresso.Parsing { internal class ParserSettings { - readonly Dictionary _identifiers; - readonly Dictionary _knownTypes; - readonly HashSet _extensionMethods; + private readonly Dictionary _identifiers; + private readonly Dictionary _knownTypes; + private readonly HashSet _extensionMethods; public ParserSettings(bool caseInsensitive) { diff --git a/test/DynamicExpresso.UnitTest/CollectionHelperTests.cs b/test/DynamicExpresso.UnitTest/CollectionHelperTests.cs index 31ef05ab..24f9b79c 100644 --- a/test/DynamicExpresso.UnitTest/CollectionHelperTests.cs +++ b/test/DynamicExpresso.UnitTest/CollectionHelperTests.cs @@ -28,7 +28,7 @@ public void Where() public class CollectionHelper { - readonly Interpreter _interpreter; + private readonly Interpreter _interpreter; public CollectionHelper() { diff --git a/test/DynamicExpresso.UnitTest/DynamicTest.cs b/test/DynamicExpresso.UnitTest/DynamicTest.cs index 02ad23ad..7fd96006 100644 --- a/test/DynamicExpresso.UnitTest/DynamicTest.cs +++ b/test/DynamicExpresso.UnitTest/DynamicTest.cs @@ -21,18 +21,18 @@ public void Get_Property_of_an_ExpandoObject() Assert.AreEqual(dyn.Foo, interpreter.Eval("dyn.Foo")); } - [Test] - public void Get_Property_of_a_nested_ExpandoObject() - { - dynamic dyn = new ExpandoObject(); - dyn.Sub = new ExpandoObject(); - dyn.Sub.Foo = "bar"; + [Test] + public void Get_Property_of_a_nested_ExpandoObject() + { + dynamic dyn = new ExpandoObject(); + dyn.Sub = new ExpandoObject(); + dyn.Sub.Foo = "bar"; - var interpreter = new Interpreter() - .SetVariable("dyn", dyn); + var interpreter = new Interpreter() + .SetVariable("dyn", dyn); - Assert.AreEqual(dyn.Sub.Foo, interpreter.Eval("dyn.Sub.Foo")); - } + Assert.AreEqual(dyn.Sub.Foo, interpreter.Eval("dyn.Sub.Foo")); + } //[Test] //public void Set_Property_of_an_ExpandoObject() @@ -72,18 +72,18 @@ public void Invoke_Method_of_an_ExpandoObject() } - [Test] - public void Invoke_Method_of_a_nested_ExpandoObject() - { - dynamic dyn = new ExpandoObject(); - dyn.Sub = new ExpandoObject(); - dyn.Sub.Foo = new Func(() => "bar"); + [Test] + public void Invoke_Method_of_a_nested_ExpandoObject() + { + dynamic dyn = new ExpandoObject(); + dyn.Sub = new ExpandoObject(); + dyn.Sub.Foo = new Func(() => "bar"); - var interpreter = new Interpreter() - .SetVariable("dyn", dyn); + var interpreter = new Interpreter() + .SetVariable("dyn", dyn); - Assert.AreEqual(dyn.Sub.Foo(), interpreter.Eval("dyn.Sub.Foo()")); - } + Assert.AreEqual(dyn.Sub.Foo(), interpreter.Eval("dyn.Sub.Foo()")); + } [Test] public void Standard_methods_have_precedence_over_dynamic_methods() diff --git a/test/DynamicExpresso.UnitTest/ExpressionTypeTest.cs b/test/DynamicExpresso.UnitTest/ExpressionTypeTest.cs index b2912a99..82bf097e 100644 --- a/test/DynamicExpresso.UnitTest/ExpressionTypeTest.cs +++ b/test/DynamicExpresso.UnitTest/ExpressionTypeTest.cs @@ -95,6 +95,6 @@ public void Typed_eval() Assert.AreEqual(Math.Pow(10, 2) + 5, result); } - class TestReferenceType { }; + private class TestReferenceType { }; } } diff --git a/test/DynamicExpresso.UnitTest/GenerateDelegatesTest.cs b/test/DynamicExpresso.UnitTest/GenerateDelegatesTest.cs index 002589fe..75a98cc7 100644 --- a/test/DynamicExpresso.UnitTest/GenerateDelegatesTest.cs +++ b/test/DynamicExpresso.UnitTest/GenerateDelegatesTest.cs @@ -87,7 +87,7 @@ public void Parse_To_a_Custom_Delegate() Assert.AreEqual(10, func(5, "mondo")); } - delegate int MyCustomDelegate(int x, string y); + private delegate int MyCustomDelegate(int x, string y); [ExpectedException(typeof(ParseException))] [Test] diff --git a/test/DynamicExpresso.UnitTest/GenerateLambdaTest.cs b/test/DynamicExpresso.UnitTest/GenerateLambdaTest.cs index c11e1953..18375368 100644 --- a/test/DynamicExpresso.UnitTest/GenerateLambdaTest.cs +++ b/test/DynamicExpresso.UnitTest/GenerateLambdaTest.cs @@ -27,11 +27,11 @@ public void Parse_as_LambdaExpression_with_parameter() Assert.AreEqual(15, lambdaExpression.Compile()(10)); - lambdaExpression = target.ParseAsExpression>("arg + .5"); - Assert.AreEqual(10.5, lambdaExpression.Compile()(10)); - } + lambdaExpression = target.ParseAsExpression>("arg + .5"); + Assert.AreEqual(10.5, lambdaExpression.Compile()(10)); + } - [Test] + [Test] public void Parse_To_a_Delegate_With_Two_Parameters() { var target = new Interpreter(); @@ -59,12 +59,12 @@ public void Generate_a_LambdaExpression_From_Lambda() { var target = new Interpreter(); - var lambda = target.Parse("Math.Pow(x, y) + 5", + var lambda = target.Parse("Math.Pow(x, y) + 5", new Parameter("x", typeof(double)), new Parameter("y", typeof(double)) ); - Expression> lambdaExpression = lambda.LambdaExpression> (); + Expression> lambdaExpression = lambda.LambdaExpression>(); Assert.AreEqual(Math.Pow(10, 2) + 5, lambdaExpression.Compile()(10, 2)); } @@ -76,11 +76,11 @@ public void Cannot_Generate_a_LambdaExpression_From_Lambda_with_parameters_count // Func delegate has 2 inputs, I just use one - var lambda = target.Parse("x + 5", + var lambda = target.Parse("x + 5", new Parameter("x", typeof(double)) ); - Assert.Throws(() => lambda.LambdaExpression> ()); + Assert.Throws(() => lambda.LambdaExpression>()); } [Test] @@ -90,11 +90,11 @@ public void Cannot_Generate_a_LambdaExpression_From_Lambda_with_parameters_type_ // Func delegate takes a string, I pass a double - var lambda = target.Parse("x + 5", + var lambda = target.Parse("x + 5", new Parameter("x", typeof(double)) ); - Assert.Throws(() => lambda.LambdaExpression> ()); + Assert.Throws(() => lambda.LambdaExpression>()); } [Test] @@ -104,11 +104,11 @@ public void Cannot_generate_a_Lambda_with_return_type_mismatch() // Func delegate returns a string, I return a double - var lambda = target.Parse("x + 5", + var lambda = target.Parse("x + 5", new Parameter("x", typeof(double)) ); - Assert.Throws(() => lambda.LambdaExpression> ()); + Assert.Throws(() => lambda.LambdaExpression>()); } } diff --git a/test/DynamicExpresso.UnitTest/GithubIssues.cs b/test/DynamicExpresso.UnitTest/GithubIssues.cs index 9030b66f..228cbf90 100644 --- a/test/DynamicExpresso.UnitTest/GithubIssues.cs +++ b/test/DynamicExpresso.UnitTest/GithubIssues.cs @@ -1,8 +1,7 @@ using System; using NUnit.Framework; -using System.Linq; -using System.Linq.Expressions; using System.Collections.Generic; +// ReSharper disable SpecifyACultureInStringConversionExplicitly namespace DynamicExpresso.UnitTest { @@ -20,56 +19,59 @@ public void GitHub_Issue_19() Assert.AreEqual(5.ToString(), interpreter.Eval("5.ToString()")); } - [Test] - public void GitHub_Issue_43() - { - var interpreter = new Interpreter(); + [Test] + public void GitHub_Issue_43() + { + var interpreter = new Interpreter(); - Assert.AreEqual((-0.5).ToString(), interpreter.Eval("-.5.ToString()")); - Assert.AreEqual((0.1).ToString(), interpreter.Eval(".1.ToString()")); - Assert.AreEqual((-1 - .1 - 0.1).ToString(), interpreter.Eval("(-1-.1-0.1).ToString()")); - } + Assert.AreEqual((-.5).ToString(), interpreter.Eval("-.5.ToString()")); + Assert.AreEqual((.1).ToString(), interpreter.Eval(".1.ToString()")); + Assert.AreEqual((-1-.1-0.1).ToString(), interpreter.Eval("(-1-.1-0.1).ToString()")); + } - /** - * Once the bug is fixed, this test should fail. - **/ - [Test] - [ExpectedException(typeof(ArgumentException))] - public void GitHub_Issue_39_Simple_Reassignment() - { - var target = new Interpreter().SetVariable("x", 3); - Assert.AreEqual(3, target.Eval("x")); - target.Eval("x = 23"); - Assert.AreEqual(23, target.Eval("x")); - } + /** + * Once the bug is fixed, this test should fail. + **/ + [Test] + [ExpectedException(typeof(ArgumentException))] + public void GitHub_Issue_39_Simple_Reassignment() + { + var target = new Interpreter().SetVariable("x", 3); + Assert.AreEqual(3, target.Eval("x")); + target.Eval("x = 23"); + Assert.AreEqual(23, target.Eval("x")); + } - /** - * Once the bug is fixed, this test should fail. - **/ - [Test] - [ExpectedException(typeof(ArgumentException))] - public void GitHub_Issue_39_Array_Reassignment() - { - var arr = new[] { 1 }; - arr[0] = 2; - var target = new Interpreter().SetVariable("arr", arr); - Assert.AreEqual(2, target.Eval("arr[0]")); - target.Eval("arr[0] = 3"); - Assert.AreNotEqual(2, target.Eval("arr[0]")); - Assert.AreEqual(3, target.Eval("arr[0]")); - } + /** + * Once the bug is fixed, this test should fail. + **/ + [Test] + [ExpectedException(typeof(ArgumentException))] + public void GitHub_Issue_39_Array_Reassignment() + { + var arr = new[] { 1 }; + arr[0] = 2; + var target = new Interpreter().SetVariable("arr", arr); + Assert.AreEqual(2, target.Eval("arr[0]")); + target.Eval("arr[0] = 3"); + Assert.AreNotEqual(2, target.Eval("arr[0]")); + Assert.AreEqual(3, target.Eval("arr[0]")); + } - [Test] - [ExpectedException(typeof(ArgumentException))] - public void GitHub_Issue_39_List_Reassignment() - { - var list = new List(new[] { 1 }); - list[0] = 2; - var target = new Interpreter().SetVariable("list", list); - Assert.AreEqual(2, target.Eval("list[0]")); - target.Eval("list[0] = 3"); - Assert.AreNotEqual(2, target.Eval("list[0]")); - Assert.AreEqual(3, target.Eval("list[0]")); - } - } + /** + * Once the bug is fixed, this test should fail. + **/ + [Test] + [ExpectedException(typeof(ArgumentException))] + public void GitHub_Issue_39_List_Reassignment() + { + var list = new List(new[] { 1 }); + list[0] = 2; + var target = new Interpreter().SetVariable("list", list); + Assert.AreEqual(2, target.Eval("list[0]")); + target.Eval("list[0] = 3"); + Assert.AreNotEqual(2, target.Eval("list[0]")); + Assert.AreEqual(3, target.Eval("list[0]")); + } + } } diff --git a/test/DynamicExpresso.UnitTest/InvalidExpressionTest.cs b/test/DynamicExpresso.UnitTest/InvalidExpressionTest.cs index 49a65a55..c338cf3b 100644 --- a/test/DynamicExpresso.UnitTest/InvalidExpressionTest.cs +++ b/test/DynamicExpresso.UnitTest/InvalidExpressionTest.cs @@ -177,7 +177,7 @@ public class MyException : Exception public MyException(string message) : base(message) { } } - class MyTestService + private class MyTestService { public string ThrowException() { diff --git a/test/DynamicExpresso.UnitTest/LiteralsTest.cs b/test/DynamicExpresso.UnitTest/LiteralsTest.cs index fdb4357b..297cac78 100644 --- a/test/DynamicExpresso.UnitTest/LiteralsTest.cs +++ b/test/DynamicExpresso.UnitTest/LiteralsTest.cs @@ -38,21 +38,32 @@ public void Numeric_Literals() Assert.AreEqual(23423423423434, target.Eval("23423423423434")); Assert.AreEqual(45.5, target.Eval("45.5")); Assert.AreEqual(-0.5, target.Eval("-0.5")); - Assert.AreEqual(.2, target.Eval(".2")); - Assert.AreEqual(-.2, target.Eval("-.2")); - Assert.AreEqual(45.8f, target.Eval("45.8f")); + Assert.AreEqual(.2, target.Eval(".2")); + Assert.AreEqual(-.2, target.Eval("-.2")); + Assert.AreEqual(+.2, target.Eval("+.2")); + Assert.AreEqual(.02, target.Eval(".02")); + Assert.AreEqual(-.02, target.Eval("-.02")); + Assert.AreEqual(+.02, target.Eval("+.02")); + Assert.AreEqual(.20, target.Eval(".20")); + Assert.AreEqual(-.20, target.Eval("-.20")); + Assert.AreEqual(+.20, target.Eval("+.20")); + Assert.AreEqual(.201, target.Eval(".201")); + Assert.AreEqual(-.201, target.Eval("-.201")); + Assert.AreEqual(+.201, target.Eval("+.201")); + Assert.AreEqual(45.8f, target.Eval("45.8f")); Assert.AreEqual(45.8F, target.Eval("45.8F")); - Assert.AreEqual(.2f, target.Eval(".2f")); - Assert.AreEqual(.2F, target.Eval(".2F")); - Assert.AreEqual(-.2f, target.Eval("-.2f")); - Assert.AreEqual(-.2F, target.Eval("-.2F")); - Assert.AreEqual(45.232M, target.Eval("45.232M")); + Assert.AreEqual(45.8F, target.Eval(" 45.8F ")); + Assert.AreEqual(.2f, target.Eval(".2f")); + Assert.AreEqual(.2F, target.Eval(".2F")); + Assert.AreEqual(-.2f, target.Eval("-.2f")); + Assert.AreEqual(-.2F, target.Eval("-.2F")); + Assert.AreEqual(45.232M, target.Eval("45.232M")); Assert.AreEqual(45.232m, target.Eval("45.232m")); - Assert.AreEqual(.022M, target.Eval(".022M")); - Assert.AreEqual(.022m, target.Eval(".022m")); - Assert.AreEqual(-.022m, target.Eval("-.022m")); - Assert.AreEqual(-.022M, target.Eval("-.022M")); - } + Assert.AreEqual(.022M, target.Eval(".022M")); + Assert.AreEqual(.022m, target.Eval(".022m")); + Assert.AreEqual(-.022m, target.Eval("-.022m")); + Assert.AreEqual(-.022M, target.Eval("-.022M")); + } [Test] [ExpectedException(typeof(ParseException))] @@ -63,6 +74,33 @@ public void Invalid_Numeric_Literals_multiple_dots() target.Eval("45.5.456"); } + [Test] + [ExpectedException(typeof(ParseException))] + public void Invalid_Numeric_Literals_wrong_space() + { + var target = new Interpreter(); + + target.Eval(".2 F"); + } + + [Test] + [ExpectedException(typeof(ParseException))] + public void Invalid_Numeric_Literals_wrong_space_before_point() + { + var target = new Interpreter(); + + target.Eval(". 2"); + } + + [Test] + [ExpectedException(typeof(ParseException))] + public void Invalid_Numeric_Literals_multiple_suffix() + { + var target = new Interpreter(); + + target.Eval("45.5M456F"); + } + [Test] [ExpectedException(typeof(ParseException))] public void Invalid_Numeric_Literals_wrong_suffix_x() @@ -92,9 +130,12 @@ public void Calling_System_Method_On_Literals() Assert.AreEqual((-565).GetType(), target.Eval("-565.GetType()")); Assert.AreEqual((-0.5).GetType(), target.Eval("-0.5.GetType()")); - Assert.AreEqual((-.5).GetType(), target.Eval("-.5.GetType()")); - Assert.AreEqual((-.5f).GetType(), target.Eval("-.5f.GetType()")); - } + Assert.AreEqual((-.5).GetType(), target.Eval("-.5.GetType()")); + Assert.AreEqual((-.5f).GetType(), target.Eval("-.5f.GetType()")); + + Assert.AreEqual((+.5).GetType(), target.Eval("+.5.GetType()")); + Assert.AreEqual((+.5f).GetType(), target.Eval("+.5f.GetType()")); + } [Test] public void Long_strings() @@ -255,17 +296,17 @@ public void Should_Understand_ReturnType_Of_Literals() Assert.AreEqual(typeof(string), target.Parse("\"\"").ReturnType); Assert.AreEqual(typeof(int), target.Parse("234").ReturnType); Assert.AreEqual(typeof(double), target.Parse("234.54").ReturnType); - Assert.AreEqual(typeof(double), target.Parse(".9").ReturnType); - Assert.AreEqual(typeof(double), target.Parse("-.9").ReturnType); - Assert.AreEqual(typeof(float), target.Parse("4.5f").ReturnType); + Assert.AreEqual(typeof(double), target.Parse(".9").ReturnType); + Assert.AreEqual(typeof(double), target.Parse("-.9").ReturnType); + Assert.AreEqual(typeof(float), target.Parse("4.5f").ReturnType); Assert.AreEqual(typeof(float), target.Parse("4.5F").ReturnType); - Assert.AreEqual(typeof(float), target.Parse(".5f").ReturnType); - Assert.AreEqual(typeof(float), target.Parse(".5F").ReturnType); - Assert.AreEqual(typeof(decimal), target.Parse("234.48m").ReturnType); + Assert.AreEqual(typeof(float), target.Parse(".5f").ReturnType); + Assert.AreEqual(typeof(float), target.Parse(".5F").ReturnType); + Assert.AreEqual(typeof(decimal), target.Parse("234.48m").ReturnType); Assert.AreEqual(typeof(decimal), target.Parse("234.48M").ReturnType); - Assert.AreEqual(typeof(decimal), target.Parse(".48m").ReturnType); - Assert.AreEqual(typeof(decimal), target.Parse(".48M").ReturnType); - Assert.AreEqual(typeof(object), target.Parse("null").ReturnType); + Assert.AreEqual(typeof(decimal), target.Parse(".48m").ReturnType); + Assert.AreEqual(typeof(decimal), target.Parse(".48M").ReturnType); + Assert.AreEqual(typeof(object), target.Parse("null").ReturnType); Assert.AreEqual((45.5).GetType(), target.Eval("45.5").GetType()); Assert.AreEqual((45.8f).GetType(), target.Eval("45.8f").GetType()); diff --git a/test/DynamicExpresso.UnitTest/MemberInvocationTest.cs b/test/DynamicExpresso.UnitTest/MemberInvocationTest.cs index de8397a3..91057fea 100644 --- a/test/DynamicExpresso.UnitTest/MemberInvocationTest.cs +++ b/test/DynamicExpresso.UnitTest/MemberInvocationTest.cs @@ -271,15 +271,16 @@ public void Overload_paramsArray_methods_with_compatible_type_params() Assert.AreEqual(3, target.Eval("x.OverloadMethodWithParamsArray(2, 3, 1)")); } - interface MyTestInterface + private interface MyTestInterface { } - class MyTestInterfaceImp : MyTestInterface + + private class MyTestInterfaceImp : MyTestInterface { } - class MyTestService + private class MyTestService { public DateTime AField = DateTime.Now; public DateTime AFIELD = DateTime.UtcNow; @@ -360,7 +361,7 @@ public long OverloadMethodWithParamsArray(params long[] paramsArray) } } - class MyTestServiceCaseInsensitive + private class MyTestServiceCaseInsensitive { public DateTime AField = DateTime.Now; diff --git a/test/DynamicExpresso.UnitTest/OperatorsTest.cs b/test/DynamicExpresso.UnitTest/OperatorsTest.cs index 1260ceba..3fd1b89f 100644 --- a/test/DynamicExpresso.UnitTest/OperatorsTest.cs +++ b/test/DynamicExpresso.UnitTest/OperatorsTest.cs @@ -185,7 +185,8 @@ public void Assignment_Operator_Equal() Assert.AreEqual(20, x.Property1); Assert.AreEqual(2, x.Property2); } - class TypeWithProperty { public int Property1 { get; set; } public int Property2 { get; set; } } + + private class TypeWithProperty { public int Property1 { get; set; } public int Property2 { get; set; } } [Test] public void Can_assign_a_parameter() @@ -290,7 +291,7 @@ public void Implicit_conversion_operator_for_lambda() Assert.AreEqual(10, val); } - struct TypeWithImplicitConversion + private struct TypeWithImplicitConversion { private int _value; @@ -332,7 +333,7 @@ public void Can_use_overloaded_operators_on_struct() Assert.IsTrue(target.Eval("(x + z) == \"13\"", new Parameter("z", z))); } - struct StructWithOverloadedBinaryOperators + private struct StructWithOverloadedBinaryOperators { private int _value; @@ -405,7 +406,7 @@ public void Can_use_overloaded_operators_on_class() Assert.IsTrue(target.Eval("(x + z) == \"13\"", new Parameter("z", z))); } - class ClassWithOverloadedBinaryOperators + private class ClassWithOverloadedBinaryOperators { private int _value; @@ -489,7 +490,7 @@ public void Throw_an_exception_if_a_custom_type_doesnt_define_not_operator() target.Parse("!x"); } - struct TypeWithoutOverloadedBinaryOperators + private struct TypeWithoutOverloadedBinaryOperators { public TypeWithoutOverloadedBinaryOperators(int value) { diff --git a/test/DynamicExpresso.UnitTest/OtherTests.cs b/test/DynamicExpresso.UnitTest/OtherTests.cs index 7a9b1cf4..15e2a06f 100644 --- a/test/DynamicExpresso.UnitTest/OtherTests.cs +++ b/test/DynamicExpresso.UnitTest/OtherTests.cs @@ -177,7 +177,7 @@ public void Multiple_Parentheses_Cast_Expression() Assert.AreEqual(((double)5).GetType().Name, interpreter.Eval("((double)5).GetType().Name")); } - class MyTestService + private class MyTestService { public DateTime AField = DateTime.Now; public DateTime AFIELD = DateTime.UtcNow; @@ -217,7 +217,7 @@ public void VoidMethod2() } } - class Customer + private class Customer { public string Name { get; set; } public int Age { get; set; } diff --git a/test/DynamicExpresso.UnitTest/ParametersTest.cs b/test/DynamicExpresso.UnitTest/ParametersTest.cs index 4ea11668..121366ce 100644 --- a/test/DynamicExpresso.UnitTest/ParametersTest.cs +++ b/test/DynamicExpresso.UnitTest/ParametersTest.cs @@ -362,7 +362,7 @@ public void When_parsing_an_expression_to_a_delegate_the_delegate_parameters_are public delegate int TestDelegate(int x, int y, int z); - class MyTestService + private class MyTestService { public DateTime AField = DateTime.Now; @@ -382,7 +382,7 @@ public string CallMethod(string param1, int param2, DateTime param3) } } - delegate int MyDelegate(string s); + private delegate int MyDelegate(string s); } } diff --git a/test/DynamicExpresso.UnitTest/StaticTest.cs b/test/DynamicExpresso.UnitTest/StaticTest.cs index b8f1abaf..807789e5 100644 --- a/test/DynamicExpresso.UnitTest/StaticTest.cs +++ b/test/DynamicExpresso.UnitTest/StaticTest.cs @@ -11,12 +11,12 @@ public void Static_Properties_of_Base_Types() { var target = new Interpreter(); - Assert.AreEqual(Int32.MaxValue, target.Eval("Int32.MaxValue")); - Assert.AreEqual(Double.MaxValue, target.Eval("Double.MaxValue")); + Assert.AreEqual(int.MaxValue, target.Eval("Int32.MaxValue")); + Assert.AreEqual(double.MaxValue, target.Eval("Double.MaxValue")); Assert.AreEqual(DateTime.MaxValue, target.Eval("DateTime.MaxValue")); Assert.AreEqual(DateTime.Today, target.Eval("DateTime.Today")); - Assert.AreEqual(String.Empty, target.Eval("String.Empty")); - Assert.AreEqual(Boolean.FalseString, target.Eval("Boolean.FalseString")); + Assert.AreEqual(string.Empty, target.Eval("String.Empty")); + Assert.AreEqual(bool.FalseString, target.Eval("Boolean.FalseString")); Assert.AreEqual(TimeSpan.TicksPerMillisecond, target.Eval("TimeSpan.TicksPerMillisecond")); Assert.AreEqual(Guid.Empty, target.Eval("Guid.Empty")); } @@ -82,7 +82,7 @@ public void Type_Related_Static_Methods() Assert.AreEqual(DateTime.Now.GetType(), target.Eval("DateTime.Now.GetType()")); } - class MyTestService + private class MyTestService { public static int MyStaticMethod() { diff --git a/test/DynamicExpresso.UnitTest/TypesTest.cs b/test/DynamicExpresso.UnitTest/TypesTest.cs index ebf3de79..3e4f36cc 100644 --- a/test/DynamicExpresso.UnitTest/TypesTest.cs +++ b/test/DynamicExpresso.UnitTest/TypesTest.cs @@ -15,30 +15,30 @@ public void Default_Types() var target = new Interpreter(); var predefinedTypes = new Dictionary{ - {"Object", typeof(Object)}, - {"object", typeof(Object)}, - {"Boolean", typeof(Boolean)}, - {"bool", typeof(Boolean)}, - {"Char", typeof(Char)}, - {"char", typeof(Char)}, - {"String", typeof(String)}, - {"string", typeof(String)}, - {"SByte", typeof(SByte)}, - {"Byte", typeof(Byte)}, - {"byte", typeof(Byte)}, - {"Int16", typeof(Int16)}, - {"UInt16", typeof(UInt16)}, - {"Int32", typeof(Int32)}, - {"int", typeof(Int32)}, - {"UInt32", typeof(UInt32)}, - {"Int64", typeof(Int64)}, - {"long", typeof(Int64)}, - {"UInt64", typeof(UInt64)}, - {"Single", typeof(Single)}, - {"Double", typeof(Double)}, - {"double", typeof(Double)}, - {"Decimal", typeof(Decimal)}, - {"decimal", typeof(Decimal)}, + {"Object", typeof(object)}, + {"object", typeof(object)}, + {"Boolean", typeof(bool)}, + {"bool", typeof(bool)}, + {"Char", typeof(char)}, + {"char", typeof(char)}, + {"String", typeof(string)}, + {"string", typeof(string)}, + {"SByte", typeof(sbyte)}, + {"Byte", typeof(byte)}, + {"byte", typeof(byte)}, + {"Int16", typeof(short)}, + {"UInt16", typeof(ushort)}, + {"Int32", typeof(int)}, + {"int", typeof(int)}, + {"UInt32", typeof(uint)}, + {"Int64", typeof(long)}, + {"long", typeof(long)}, + {"UInt64", typeof(ulong)}, + {"Single", typeof(float)}, + {"Double", typeof(double)}, + {"double", typeof(double)}, + {"Decimal", typeof(decimal)}, + {"decimal", typeof(decimal)}, {"DateTime", typeof(DateTime)}, {"TimeSpan", typeof(TimeSpan)}, {"Guid", typeof(Guid)}, @@ -153,7 +153,7 @@ public enum EnumCaseSensitive TEST = 2 } - class MyDataContract + private class MyDataContract { public MyDataContract(string name) { @@ -170,7 +170,7 @@ public MyDataContract(int x, int y) public class MyTestClass { - T _val; + private T _val; public MyTestClass(T val) { _val = val;