Exemplo n.º 1
0
        public void TestAssignAdd()
        {
            var buildResult = buildParser();

            Assert.False(buildResult.IsError);
            var parser = buildResult.Result;
            ParseResult <WhileToken, WhileAST> result = parser.Parse("(a:=1+1)");

            Assert.False(result.IsError);
            Assert.NotNull(result.Result);

            Assert.IsType <SequenceStatement>(result.Result);
            SequenceStatement seq = result.Result as SequenceStatement;

            Assert.IsType <AssignStatement>(seq.Get(0));
            AssignStatement assign = seq.Get(0) as AssignStatement;

            Assert.Equal("a", assign.VariableName);
            Expression val = assign.Value;

            Assert.IsType <BinaryOperation>(val);
            BinaryOperation bin = val as BinaryOperation;

            Assert.Equal(BinaryOperator.ADD, bin.Operator);
            Assert.Equal(1, (bin.Left as IntegerConstant)?.Value);
            Assert.Equal(1, (bin.Right as IntegerConstant)?.Value);
        }
Exemplo n.º 2
0
 public override void Visit(AssignStatement stmt)
 {
     StartElement("assignStatement");
     Attribute("identifier", stmt.Name);
     stmt.ValueExp.AcceptVisitor(this);
     EndElement();
 }
Exemplo n.º 3
0
        public Void Visit(AssignStatement assignStatement, SortedSet <string> free)
        {
            assignStatement.s.Accept(this, free);
            free.Remove(assignStatement.id);

            return(null);
        }
Exemplo n.º 4
0
        public Type Visit(AssignStatement assignStatement)
        {
            if (!Environment.VariableType.ContainsKey(assignStatement.id))
            {
                var err = new TypeErrorMessage();
                throw new TypeException(err.ErrorOutput(TypeErrorMessage.ErrorCode.ID, assignStatement));
            }
            var type      = Environment.VariableType[assignStatement.id];
            var type_text = type.GetType().Name;

            var result = assignStatement.s.Accept(this);

            if (result == null)
            {
                var err = new TypeErrorMessage();
                throw new TypeException(err.ErrorOutput(TypeErrorMessage.ErrorCode.ASN_1, assignStatement));
            }
            var result_type_text = result.GetType().Name;

            if (IsVoidType(result_type_text))
            {
                var err = new TypeErrorMessage();
                throw new TypeException(err.ErrorOutput(TypeErrorMessage.ErrorCode.ASN_1, assignStatement));
            }
            if (result_type_text != type_text)
            {
                var err = new TypeErrorMessage();
                throw new TypeException(err.ErrorOutput(TypeErrorMessage.ErrorCode.ASN_2, assignStatement));
            }

            return(type);
        }
        public WhileAST assignStmt(Token <WhileTokenGeneric> variable, Token <WhileTokenGeneric> discardAssign,
                                   Expression value)
        {
            var assign = new AssignStatement(variable.StringWithoutQuotes, value);

            return(assign);
        }
Exemplo n.º 6
0
//        public AstPrinterNode Visit(BinOperator node)
//        {
//            var printer = new AstPrinterNode(node.ToString());
//            printer.AddChild(node.Left.Accept(this));
//            printer.AddChild(node.Right.Accept(this));
//            return printer;
//        }

        public AstPrinterNode Visit(AssignStatement node)
        {
            var printer = new AstPrinterNode(node.ToString());

            printer.AddChild(node.Left.Accept(this));
            printer.AddChild(node.Right.Accept(this));
            return(printer);
        }
Exemplo n.º 7
0
        public Statement Visit(AssignStatement assignStatement)
        {
            assignStatement.id = State.UnShadow(assignStatement.id);
            //Console.WriteLine($"**********Assign STATMENT:{assignStatement.id} **********");
            assignStatement.s.Accept(this);

            return(assignStatement);
        }
 private static IEnumerable <UnifiedExpression> CreateAssignStatement(
     AssignStatement statement)
 {
     yield return(UnifiedBinaryExpression.Create(
                      CreatePhrase(statement.Left),
                      UnifiedBinaryOperator.Create("=", UnifiedBinaryOperatorKind.Assign),
                      CreatePhrase(statement.Right)));
 }
Exemplo n.º 9
0
        public static AssignStatement CreateAssignStatement(Variable variable, IExpression expression, Token token)
        {
            AssignStatement result = CreateNode <AssignStatement>(token);

            result.SetVariable(variable);
            result.SetExpression(expression);

            return(result);
        }
Exemplo n.º 10
0
        public static AssignStatement BuildAssignStatement(IEnumerable <IExpression> leftPart,
                                                           IEnumerable <IExpression> rightPart)
        {
            var statement = new AssignStatement(DefaultLineNumber);

            statement.SetLeftExpressions(leftPart);
            statement.SetRightExpressions(rightPart);
            return(statement);
        }
        public void CSharpCodeGenerator_Assign()
        {
            var statement = new AssignStatement(new VariableReference("a"), 10);

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(statement);

            Assert.That.StringEquals(@"a = 10;
", result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Generates the code for a <see cref="AssignStatement"/>.
        /// </summary>
        /// <param name="statement">The statement</param>
        /// <returns>A BaZic code</returns>
        private string GenerateAssignStatement(AssignStatement statement)
        {
            Requires.NotNull(statement.LeftExpression, nameof(statement.LeftExpression));
            Requires.NotNull(statement.RightExpression, nameof(statement.RightExpression));

            var leftExpression  = GenerateExpression(statement.LeftExpression);
            var rightExpression = GenerateExpression(statement.RightExpression);

            return($"{leftExpression} = {rightExpression}");
        }
Exemplo n.º 13
0
        public bool VisitNode(AssignStatement node)
        {
            // reference = expression;
            Write("");
            node.Target.AcceptVisitor(this);
            Append(" = ");
            node.Value.AcceptVisitor(this);

            return(true);
        }
Exemplo n.º 14
0
        private Statement readAS()
        {
            AssignStatement _as = new AssignStatement();

            Console.WriteLine("Input variable name:");
            _as.setVar(Console.ReadLine());
            Console.WriteLine("Input variable value:");
            _as.setE(readExpression());
            return(_as);
        }
Exemplo n.º 15
0
        void ButtonOKClick(object sender, EventArgs e)
        {
            String          variable = textBoxVariable.Text;
            AssignStatement asstm    = new AssignStatement();

            asstm.setVar(variable);
            asstm.setE(this.expression);
            stmt = asstm;
            finished();
        }
Exemplo n.º 16
0
            public override void Visit(AssignStatement stmt)
            {
                cb.WriteIndent();
                cb.Write("{0} = ", stmt.Name);

                stmt.ValueExp.AcceptVisitor(this);

                cb.Write(";");
                cb.WriteLine();
            }
Exemplo n.º 17
0
 public void interpretNextMT()
 {
     for (int i = 1; i <= r.getNumProg(); ++i)
     {
         Statement st = r.getPS(i).es.top();
         r.getPS(i).es.pop();
         if (st is AssignStatement)
         {
             AssignStatement _as = (AssignStatement)st;
             r.getPS(i).vt.set(
                 _as.getVar(),
                 _as.getE().eval(r.getPS(i).vt, r.getPS(i).hp));
             r.getPS(i).vt.printTable();
         }
         else if (st is CompoundStatement)
         {
             CompoundStatement cs = (CompoundStatement)st;
             r.getPS(i).es.push(cs.getS2());
             r.getPS(i).es.push(cs.getS1());
         }
         else if (st is IfStatement)
         {
             IfStatement _is = (IfStatement)st;
             if (_is.getE().eval(r.getPS(i).vt, r.getPS(i).hp) != 0)
             {
                 r.getPS(i).es.push(_is.getS1());
             }
             else
             {
                 r.getPS(i).es.push(_is.getS2());
             }
         }
         else if (st is PrintStatement)
         {
             PrintStatement pr = (PrintStatement)st;
             r.getPS(i).ob.add(pr.getE().eval(r.getPS(i).vt, r.getPS(i).hp).ToString());
         }
         else if (st is ForkStatement)
         {
             r.addPs(r.getPS(i).ob, r.getPS(i).vt, ((ForkStatement)st).getS());
         }
         else if (st is WHStatement)
         {
             WHStatement wh   = (WHStatement)st;
             int         addr = r.getPS(i).vt.get(wh.getVN());
             r.getPS(i).hp.mod(addr, wh.getV().eval(r.getPS(i).vt, r.getPS(i).hp));
         }
         if (r.getPS(i).es.isEmpty())
         {
             r.removePs(i);
             --i;
         }
     }
 }
Exemplo n.º 18
0
        public object Visit_Assign(AssignStatement node)
        {
            TreeViewItem item = new TreeViewItem();

            item.IsExpanded = true;

            item.Header = "Assign (=)";
            item.Items.Add(node.Variable.Visit(this));
            item.Items.Add(node.Expression.Visit(this));

            return(item);
        }
Exemplo n.º 19
0
 public void Analyze(AssignStatement assignment)
 {
     this.assignment = assignment;
     foreach (Expression e in assignment.Left)
     {
         FieldExpression field = e as FieldExpression;
         if (null != field)
         {
             analyzer.SaveFieldExpressionession(field, assignment.Right);
         }
         e.Walk(this);
     }
 }
Exemplo n.º 20
0
        protected override void VisitAssignStatement(AssignStatement tree)
        {
            _TrySetResult(tree);
            if (_result != null)
            {
                return;
            }

            foreach (var exp in tree.var_list)
            {
                VisitAnySyntaxTree(exp);
            }
            VisitAnySyntaxTree(tree.exp_list);
        }
Exemplo n.º 21
0
        private IStatement AssignStatement()
        {
            Var   var   = Variable();
            Token token = currentToken;

            EatToken(TokenType.ASSIGN);
            IExpression right = Expression();

            EatToken(TokenType.SEMICOLON);

            IStatement node = new AssignStatement(var, right, token);

            return(node);
        }
        private FieldReference BuildDelegateToken(ClassEmitter proxy)
        {
            var callback       = proxy.CreateStaticField(namingScope.GetUniqueName("callback_" + method.Method.Name), delegateType);
            var createDelegate = new MethodInvocationExpression(
                null,
                DelegateMethods.CreateDelegate,
                new TypeTokenExpression(delegateType),
                NullExpression.Instance,
                new MethodTokenExpression(method.MethodOnTarget));
            var bindDelegate = new AssignStatement(callback, new ConvertExpression(delegateType, createDelegate));

            proxy.ClassConstructor.CodeBuilder.AddStatement(bindDelegate);
            return(callback);
        }
Exemplo n.º 23
0
        private bool Visit(AssignStatement stmt)
        {
            AssertNotConstant(stmt);

            var value = Visit(stmt.Value);

            if (stmt.Truncate != null)
            {
                value = value.Resize(stmt.Truncate.Value);
            }

            if (stmt.Reference is PortReference port)
            {
                switch (port.PortInfo.Target)
                {
                case MachinePorts.Input:
                    throw new InterpreterException("Cannot write to input", stmt.Span);

                case MachinePorts.Output:
                    if (value.Length > port.BitSize)
                    {
                        throw new InterpreterException("Value is longer than output", stmt.Span);
                    }

                    Machine.WriteOutput(port.StartIndex, value.Bits);
                    break;

                case MachinePorts.Register:
                    Machine.WriteRegister(port.StartIndex, value);
                    break;

                default:
                    throw new InterpreterException("Unknown assignment target", stmt.Span);
                }
            }
            else if (stmt.Reference is LocalReference local)
            {
                Locals[local.Name] = value;
            }
            else
            {
                throw new InterpreterException("Unknown reference type", stmt.Span);
            }

            return(false);
        }
Exemplo n.º 24
0
        public void TestIfThenElse()
        {
            var buildResult = buildParser();

            Assert.False(buildResult.IsError);
            var parser = buildResult.Result;
            ParseResult <WhileToken, WhileAST> result = parser.Parse("if true then (a := \"hello\") else (b := \"world\")");

            Assert.False(result.IsError);
            Assert.NotNull(result.Result);

            Assert.IsType <SequenceStatement>(result.Result);
            SequenceStatement seq = result.Result as SequenceStatement;

            Assert.IsType <IfStatement>(seq.Get(0));
            IfStatement si   = seq.Get(0) as IfStatement;
            Expression  cond = si.Condition;

            Assert.IsType <BoolConstant>(cond);
            Assert.True((cond as BoolConstant).Value);
            Statement s = si.ThenStmt;

            Assert.IsType <SequenceStatement>(si.ThenStmt);
            SequenceStatement thenBlock = si.ThenStmt as SequenceStatement;

            Assert.Equal(1, thenBlock.Count);
            Assert.IsType <AssignStatement>(thenBlock.Get(0));
            AssignStatement thenAssign = thenBlock.Get(0) as AssignStatement;

            Assert.Equal("a", thenAssign.VariableName);
            Assert.IsType <StringConstant>(thenAssign.Value);
            Assert.Equal("hello", (thenAssign.Value as StringConstant).Value);
            ;

            Assert.IsType <SequenceStatement>(si.ElseStmt);
            SequenceStatement elseBlock = si.ElseStmt as SequenceStatement;

            Assert.Equal(1, elseBlock.Count);
            Assert.IsType <AssignStatement>(elseBlock.Get(0));
            AssignStatement elseAssign = elseBlock.Get(0) as AssignStatement;

            Assert.Equal("b", elseAssign.VariableName);
            Assert.IsType <StringConstant>(elseAssign.Value);
            Assert.Equal("world", (elseAssign.Value as StringConstant).Value);
        }
Exemplo n.º 25
0
        private AssignStatement ParseAssignStatement()
        {
            var stmt = new AssignStatement {
                Token = CurToken
            };

            switch (CurToken.Type)
            {
            case TokenType.Ident:
                stmt.Name = new Identifier {
                    Token = CurToken, Value = CurToken.Literal
                };
                break;

            case TokenType.Constant:
                stmt.Name = new Constant {
                    Token = CurToken, Value = CurToken.Literal
                };
                break;

            case TokenType.InstanceVariable:
                stmt.Name = new InstanceVariable {
                    Token = CurToken, Value = CurToken.Literal
                };
                break;
            }

            if (!ExpectPeek(TokenType.Assign))
            {
                return(null);
            }

            NextToken();

            stmt.Value = ParseExpression(LOWEST);

            if (PeekTokenIs(TokenType.Semicolon))
            {
                NextToken();
            }

            return(stmt);
        }
Exemplo n.º 26
0
        private void CompileAssignStmt(InstructionSet instructionSet, AssignStatement statement, Scope scope, LocalTable localTable)
        {
            CompileExpression(instructionSet, statement.Value, scope, localTable);

            if (statement.Name is Identifier)
            {
                var idtfr      = statement.Name as Identifier;
                var indexDepth = localTable.SetLCL(idtfr.Value, localTable.Depth);
                instructionSet.Define(InstructionType.SetLocal, indexDepth.Item1, indexDepth.Item2);
            }
            else if (statement.Name is InstanceVariable)
            {
                var iv = statement.Name as InstanceVariable;
                instructionSet.Define(InstructionType.SetInstanceVariable, iv.Value);
            }
            else if (statement.Name is Constant)
            {
                instructionSet.Define(InstructionType.SetConstant, statement.Name as Constant);
            }
        }
Exemplo n.º 27
0
        private void SemanticCheck(AssignStatement ast, CompilerContext context)
        {
            var valType   = expressionTyper.TypeExpression(ast.Value, context);
            var varExists = context.VariableExists(ast.VariableName);

            //ast.CompilerScope = context.CurrentScope;
            if (varExists)
            {
                var varType = context.GetVariableType(ast.VariableName);
                if (varType != valType)
                {
                    throw new TypingException($"bad assignment : {valType} expecting {varType}");
                }
            }
            else
            {
                var creation = context.SetVariableType(ast.VariableName, valType);
                ast.IsVariableCreation = creation;
                ast.CompilerScope      = context.CurrentScope;
            }
        }
Exemplo n.º 28
0
        public AssignStatement DecompileAssign()
        {
            PopByte();

            var left = DecompileExpression();

            if (left == null || !typeof(SymbolReference).IsAssignableFrom(left.GetType()))
            {
                return(null); //ERROR ?
            }
            var right = DecompileExpression();

            if (right == null)
            {
                return(null); //ERROR ?
            }
            var statement = new AssignStatement(left as SymbolReference, right, null, null);

            StatementLocations.Add(StartPositions.Pop(), statement);
            return(statement);
        }
Exemplo n.º 29
0
        public Type Visit(AssignStatement assignStatement, FunctionGeneratorEnvironment arg)
        {
            var type   = arg.GetIdentifierType(assignStatement.id);
            var offset = arg.GetIdentifierOffset(assignStatement.id);

            Program.Emit(T42Instruction.LVAL(offset));
            assignStatement.s.Accept(this, arg);

            if (type.GetType() == typeof(IntType))
            {
                Program.Emit(T42Instruction.ASSINT);
                Program.Emit(T42Instruction.RVALINT(offset));
            }
            else
            {
                Program.Emit(T42Instruction.ASSBOOL);
                Program.Emit(T42Instruction.RVALBOOL(offset));
            }

            return(type);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Inline an assignment statement in the case of where the right expression is a method invocation.
        /// </summary>
        /// <param name="assignStatement">The assign statement.</param>
        /// <returns>A list of statement that represents the assignment.</returns>
        private List <Statement> InlineAssign(AssignStatement assignStatement)
        {
            var newStatements = new List <Statement>();


            if (assignStatement.RightExpression.IsExactly <InvokeMethodExpression>())
            {
                var stmts = InlineMethodInvocation((InvokeMethodExpression)assignStatement.RightExpression, assignStatement.LeftExpression);
                if (stmts != null)
                {
                    newStatements.AddRange(stmts);
                    return(newStatements);
                }
            }

            assignStatement.LeftExpression  = OptimizeExpression(assignStatement.LeftExpression);
            assignStatement.RightExpression = OptimizeExpression(assignStatement.RightExpression);
            newStatements.Add(assignStatement);

            return(newStatements);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Parses a statement.
        /// </summary>
        public static bool AcceptStatement(string Text, int Start, out Statement Statement, out int LastChar)
        {
            // Constant assignment
            string varname;
            if (AcceptString(Text, Start, "const", out LastChar))
            {
                if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                {
                    if (AcceptWord(Text, LastChar, out varname, out LastChar) && ValidVariable(varname))
                    {
                        if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                        {
                            if (AcceptString(Text, LastChar, "=", out LastChar))
                            {
                                if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                                {
                                    Expression value;
                                    if (AcceptExpression(Text, LastChar, out value, out LastChar))
                                    {
                                        AcceptWhitespace(Text, LastChar, out LastChar);
                                        if (AcceptString(Text, LastChar, ";", out LastChar))
                                        {
                                            Statement = new ConstantStatement(varname, value);
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Define
            Expression type;
            if (AcceptTightExpression(Text, Start, out type, out LastChar))
            {
                if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                {
                    if (AcceptWord(Text, LastChar, out varname, out LastChar) && ValidVariable(varname))
                    {
                        if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                        {
                            if (AcceptString(Text, LastChar, "=", out LastChar))
                            {
                                if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                                {
                                    Expression value;
                                    if (AcceptExpression(Text, LastChar, out value, out LastChar))
                                    {
                                        AcceptWhitespace(Text, LastChar, out LastChar);
                                        if (AcceptString(Text, LastChar, ";", out LastChar))
                                        {
                                            Statement = new DefineStatement(type, varname, value);
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Assign
            if (AcceptWord(Text, Start, out varname, out LastChar) && ValidVariable(varname))
            {
                if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                {
                    if (AcceptString(Text, LastChar, "=", out LastChar))
                    {
                        if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                        {
                            Expression value;
                            if (AcceptExpression(Text, LastChar, out value, out LastChar))
                            {
                                AcceptWhitespace(Text, LastChar, out LastChar);
                                if (AcceptString(Text, LastChar, ";", out LastChar))
                                {
                                    Statement = new AssignStatement(varname, value);
                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            // Return
            if (AcceptString(Text, Start, "return", out LastChar))
            {
                if (AcceptWhitespace(Text, LastChar, out LastChar) > 0)
                {
                    Expression returnvalue;
                    if (AcceptExpression(Text, LastChar, out returnvalue, out LastChar))
                    {
                        AcceptWhitespace(Text, LastChar, out LastChar);
                        if (AcceptString(Text, LastChar, ";", out LastChar))
                        {
                            Statement = new ReturnStatement(returnvalue);
                            return true;
                        }
                    }
                }
            }

            Statement = null;
            return false;
        }