Permalink
Browse files

ExpressionSample - ensure valid L-value in assignment statement

  • Loading branch information...
bobbymcr committed Apr 15, 2018
1 parent 919a2ef commit 460c53bab4c416a951b471811b7f06e3a8943337
@@ -44,5 +44,21 @@ public void AllowSpaces(string input, string output)
{
Test.Good(input, output);
}
[InlineData("=")]
[InlineData(" = ")]
[InlineData("R=")]
[InlineData("=1")]
[InlineData("R1")]
[InlineData("R(1)")]
[InlineData("1=2")]
[InlineData("\"x\"")]
[InlineData("\"x\"=A$")]
[InlineData("X+1=2")]
[Theory]
public void Invalid(string input)
{
Test.Bad(input);
}
}
}
@@ -4,19 +4,51 @@
namespace GW.Statements
{
using System;
using GW.Expressions;
internal sealed class AssignmentStatement : BasicStatement
{
private static readonly IExpressionVisitor Visitor = new LValueVisitor();
private readonly BasicExpression left;
private readonly BasicExpression right;
public AssignmentStatement(BasicExpression left, BasicExpression right)
{
this.left = left;
this.left = EnsureLValue(left);
this.right = right;
}
public override string ToString() => "Assign(" + this.left + ", " + this.right + ")";
private static BasicExpression EnsureLValue(BasicExpression left)
{
left.Accept(Visitor);
return left;
}
private sealed class LValueVisitor : IExpressionVisitor
{
public void Array(BasicType type, string name, BasicExpression[] subs)
{
// Allowed
}
public void Literal(BasicType type, object o)
{
throw new NotSupportedException("Not an L-value.");
}
public void Operator(string name, BasicExpression[] operands)
{
throw new NotSupportedException("Not an L-value.");
}
public void Variable(BasicType type, string name)
{
// Allowed
}
}
}
}
@@ -29,9 +29,7 @@ internal static class Stmt
from left in Parse.CharExcept('=').AtLeastOnce().Text()
from o in Parse.Char('=')
from right in Parse.AnyChar.AtLeastOnce().Text()
select new AssignmentStatement(
BasicExpression.FromString(left),
BasicExpression.FromString(right));
select Asgn(left, right);
private static readonly Parser<BasicStatement> Any =
Rem.Or(Cls).Or(Assign);
@@ -47,5 +45,19 @@ public static BasicStatement FromString(string input)
throw new FormatException("Bad statement '" + input + "'.", e);
}
}
private static BasicStatement Asgn(string left, string right)
{
try
{
return new AssignmentStatement(
BasicExpression.FromString(left),
BasicExpression.FromString(right));
}
catch (NotSupportedException e)
{
throw new ParseException(e.Message);
}
}
}
}

0 comments on commit 460c53b

Please sign in to comment.