Permalink
Browse files

ExpressionSample - do type checking for operators

  • Loading branch information...
bobbymcr committed Apr 17, 2018
1 parent e5df3f2 commit 694ffe958d384d38cf12bd02bdcca485491272b4
@@ -17,6 +17,26 @@ public void Numeric(string input, string output)
Test.Good(input, output);
}
[InlineData("1 AND \"X\"")]
[InlineData("\"X\" AND 1")]
[InlineData("1 AND X$")]
[InlineData("X$ AND 1")]
[InlineData("X AND X$")]
[InlineData("X$ AND X")]
[InlineData("X(1) AND X$")]
[InlineData("X$ AND X(1)")]
[InlineData("X(1) AND X$(1)")]
[InlineData("X$(1) AND X(1)")]
[InlineData("X+1 AND X$")]
[InlineData("X$ AND X+1")]
[InlineData("X$+\"x\" AND X+1")]
[InlineData("X+1 AND X$+\"x\"")]
[Theory]
public void TypeMismatch(string input)
{
Test.Bad(input);
}
[InlineData("1 AND 2", "And(NumL(1), NumL(2))")]
[InlineData("X AND 234", "And(NumV(X), NumL(234))")]
[InlineData("X(234)AND YZ1234", "And(NumA(X, NumL(234)), NumV(YZ1234))")]
@@ -17,6 +17,26 @@ public void Numeric(string input, string output)
Test.Good(input, output);
}
[InlineData("1 OR \"X\"")]
[InlineData("\"X\" OR 1")]
[InlineData("1 OR X$")]
[InlineData("X$ OR 1")]
[InlineData("X OR X$")]
[InlineData("X$ OR X")]
[InlineData("X(1) OR X$")]
[InlineData("X$ OR X(1)")]
[InlineData("X(1) OR X$(1)")]
[InlineData("X$(1) OR X(1)")]
[InlineData("X+1 OR X$")]
[InlineData("X$ OR X+1")]
[InlineData("X$+\"x\" OR X+1")]
[InlineData("X+1 OR X$+\"x\"")]
[Theory]
public void TypeMismatch(string input)
{
Test.Bad(input);
}
[InlineData("1 OR 2", "Or(NumL(1), NumL(2))")]
[InlineData("X OR 234", "Or(NumV(X), NumL(234))")]
[InlineData("X(234)OR YZ1234", "Or(NumA(X, NumL(234)), NumV(YZ1234))")]
@@ -6,6 +6,7 @@ namespace GWParse.Expressions
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Sprache;
@@ -390,7 +391,32 @@ private Binary(string name, BasicType type = BasicType.Num)
public BasicExpression Apply(BasicExpression x, BasicExpression y)
{
return BasicOperator.Binary(this.name, this.type, x, y);
BasicType result = this.CheckType(x, y);
return BasicOperator.Binary(this.name, result, x, y);
}
private BasicType CheckType(BasicExpression x, BasicExpression y)
{
if (x.Type != y.Type)
{
string error = string.Format(
CultureInfo.InvariantCulture,
"Type mismatch for operator '{0}'; Type of [{1}] is {2} while type of [{3}] is {4}.",
this.name,
x,
x.Type,
y,
y.Type);
throw new ParseException(error);
}
BasicType result = this.type;
if (result == BasicType.None)
{
result = x.Type;
}
return result;
}
}
}

0 comments on commit 694ffe9

Please sign in to comment.