示例#1
0
        public override bool Execute()
        {
            if (!Subprogram.VarExists(VarName, ParentSubprogram))
            {
                if (inputValue)
                {
                    VarValue = Subprogram.PromptInputValue <string>();
                }

                if (VarValue != null)
                {
                    ParentSubprogram.ListVar.Add(new StringVar(VarName, VarValue));
                }
                else
                {
                    Error    = true;
                    ErrorMsg = "Variable " + VarName + " ne peut pas être égal à NULL.";
                }
            }
            else
            {
                Error    = true;
                ErrorMsg = "Variable " + VarName + " existe déjà.";
            }

            if (!Error)
            {
                return(true);
            }
            else
            {
                FormControlWindow.TerminalWriteLine("VarError : " + ErrorMsg);
                return(false);
            }
        }
示例#2
0
        public StringExpression(Node _nodeStringExpression, Subprogram _parentSubprogram)
        {
            ParentSubprogram = _parentSubprogram;

            for (int i = 0; i < _nodeStringExpression.GetChildCount(); i++)
            {
                switch (_nodeStringExpression.GetChildAt(i).GetId())
                {
                case (int)KropConstants.EXPRESSION:
                    ExpressionOne = _nodeStringExpression.GetChildAt(i);
                    break;

                case (int)KropConstants.BOOLEAN_EXPRESSION_REST:
                    for (int y = 0; y < _nodeStringExpression.GetChildAt(i).GetChildCount(); y++)
                    {
                        switch (_nodeStringExpression.GetChildAt(i).GetChildAt(y).GetId())
                        {
                        case (int)KropConstants.ADD:
                            add = true;
                            break;

                        case (int)KropConstants.STRING_VALUE:
                            ExpressionTwo = _nodeStringExpression.GetChildAt(i).GetChildAt(y);
                            break;
                        }
                    }
                    break;
                }
            }
        }
示例#3
0
        public InstructionSetVar(Node _nodeIntStatement, Subprogram _parentSubprogram)
        {
            ParentSubprogram = _parentSubprogram;

            for (int i = 0; i < _nodeIntStatement.GetChildCount(); i++)
            {
                switch (_nodeIntStatement.GetChildAt(i).GetId())
                {
                case (int)KropConstants.WORD:
                    varToken = (Token)_nodeIntStatement.GetChildAt(i);
                    break;

                case (int)KropConstants.SET_VAR_VALUE:
                    if (_nodeIntStatement.GetChildAt(i).GetChildAt(0).GetId() == (int)KropConstants.INPUT)
                    {
                        inputValue = true;
                    }
                    else
                    {
                        SetVarValue = _nodeIntStatement.GetChildAt(i);
                    }
                    break;
                }
            }
        }
示例#4
0
        public InstructionString(Node _nodeIntStatement, Subprogram _parentSubprogram)
        {
            this.ParentSubprogram = _parentSubprogram;

            for (int i = 0; i < _nodeIntStatement.GetChildCount(); i++)
            {
                switch (_nodeIntStatement.GetChildAt(i).GetId())
                {
                case (int)KropConstants.WORD:
                    Token token = (Token)_nodeIntStatement.GetChildAt(i);
                    VarName = token.GetImage();
                    break;

                case (int)KropConstants.STRING_VAR_VALUE:

                    switch (_nodeIntStatement.GetChildAt(i).GetChildAt(0).GetId())
                    {
                    case (int)KropConstants.STRING_EXPRESSION:
                        VarValue = AlgorithmicExpression.CalculStringExpression(_nodeIntStatement.GetChildAt(i).GetChildAt(0), _parentSubprogram);
                        break;

                    case (int)KropConstants.INPUT:
                        inputValue = true;
                        break;
                    }
                    break;
                }
            }
        }
示例#5
0
        /// <summary>
        /// Execute the selected program
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnPlay_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Running program " + cbxProgram.SelectedItem.ToString());

            btnPlay.Visible    = false;
            btnStop.Visible    = true;
            btnPause.Visible   = true;
            btnSave.Enabled    = false;
            btnDelete.Enabled  = false;
            cbxProgram.Enabled = false;
            cbxGarden.Enabled  = false;
            txtCode.Enabled    = false;

            FormControlWindow.IS_PAUSING  = false;
            FormControlWindow.IS_STOPPING = false;

            this.Refresh();

            if (!IS_RUNNING)
            {
                IS_RUNNING = true;

                if (cbxGarden.SelectedIndex == 0)
                {
                    Game.ChangeGarden(Game.WIDTHGARDEN, Game.HEIGHTGARDEN); //Load default garden
                }
                else
                {
                    Game.ChangeGarden(cbxGarden.SelectedItem.ToString());   //Load selected garden
                }

                try
                {
                    Node       program   = new KropParser(new StringReader(txtCode.Text.ToLower())).Parse(); //Analyze the selected program and throw an error if there is a parser error
                    Subprogram myProgram = new Subprogram(program);                                          //Create Execution Tree

                    txtTerminal.ResetText();
                    Game.ANT.ResetPlace();

                    myProgram.Execute();                                            //Execute the program
                }
                catch (PerCederberg.Grammatica.Runtime.ParserLogException msgError) //Stop program if parser error
                {
                    TerminalWriteLine("ParserError : " + msgError.Message);
                }
                finally
                {
                    EndingProgram();
                }
            }
        }
示例#6
0
        public InstructionIf(Node _nodeIfElseStatement, Subprogram _parentSubprogram)
        {
            ParentSubprogram = _parentSubprogram;
            //Construct the different If branches
            for (int i = 0; i < _nodeIfElseStatement.GetChildCount(); i++)
            {
                switch (_nodeIfElseStatement.GetChildAt(i).GetId())
                {
                case (int)KropConstants.IF_STATEMENT:
                    for (int y = 0; y < _nodeIfElseStatement.GetChildAt(i).GetChildCount(); y++)
                    {
                        switch (_nodeIfElseStatement.GetChildAt(i).GetChildAt(y).GetId())
                        {
                        case (int)KropConstants.CONDITON_STATEMENT:
                            this.Conds = Subprogram.SetCond(_nodeIfElseStatement.GetChildAt(i).GetChildAt(y), _parentSubprogram);
                            break;

                        case (int)KropConstants.PROGRAM:
                            this.IfBranch = new Subprogram(_nodeIfElseStatement.GetChildAt(i).GetChildAt(y), _parentSubprogram);
                            break;

                        default:
                            break;
                        }
                    }
                    break;

                case (int)KropConstants.ELSE_STATEMENT:
                    for (int y = 0; y < _nodeIfElseStatement.GetChildAt(i).GetChildCount(); y++)
                    {
                        switch (_nodeIfElseStatement.GetChildAt(i).GetChildAt(y).GetId())
                        {
                        case (int)KropConstants.PROGRAM:
                            this.ElseBranch = new Subprogram(_nodeIfElseStatement.GetChildAt(i).GetChildAt(y), _parentSubprogram);
                            break;

                        default:
                            break;
                        }
                    }
                    break;

                default:
                    break;
                }
            }

            Console.WriteLine(this.Conds.Count);
        }
示例#7
0
        public override bool Execute()
        {
            if (CanExecute())
            {
                if ((Var = ParentSubprogram.GetVar(varToken.GetImage(), ParentSubprogram)) == null)
                {
                    Error    = true;
                    ErrorMsg = "Variable " + varToken.GetImage() + " n'existe pas.";
                }

                if (!Error)
                {
                    if (Var is IntVar intVar)
                    {
                        if (inputValue)
                        {
                            intVar.SetValue(Subprogram.PromptInputValue <int>());
                        }
                        else
                        {
                            intVar.SetValue(AlgorithmicExpression.CalculExpression(SetVarValue.GetChildAt(0), ParentSubprogram));
                        }
                    }
                    else if (Var is StringVar stringVar)
                    {
                        if (inputValue)
                        {
                            stringVar.SetValue(Subprogram.PromptInputValue <string>());
                        }
                        else
                        {
                            stringVar.SetValue(AlgorithmicExpression.CalculStringExpression(SetVarValue.GetChildAt(0), ParentSubprogram));
                        }
                    }
                    return(true);
                }
                else
                {
                    FormControlWindow.TerminalWriteLine("VarError : " + ErrorMsg);
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
示例#8
0
        public InstructionDire(Node _nodeDireStatement, Subprogram _parentSubprogram)
        {
            ParentSubprogram = _parentSubprogram;

            for (int i = 0; i < _nodeDireStatement.GetChildCount(); i++)
            {
                if (_nodeDireStatement.GetChildAt(i).GetId() == (int)KropConstants.DIRE_VALUE)
                {
                    for (int y = 0; y < _nodeDireStatement.GetChildAt(i).GetChildCount(); y++)
                    {
                        switch (_nodeDireStatement.GetChildAt(i).GetChildAt(y).GetId())
                        {
                        case (int)KropConstants.STRING_EXPRESSION:
                            IsStringValue    = true;
                            stringExpression = _nodeDireStatement.GetChildAt(i).GetChildAt(y);
                            break;

                        case (int)KropConstants.ATOM:
                            Token token;
                            token = (Token)_nodeDireStatement.GetChildAt(i).GetChildAt(y).GetChildAt(0);
                            if (_nodeDireStatement.GetChildAt(i).GetChildAt(y).GetChildAt(0).GetId() == (int)KropConstants.NUMBER)
                            {
                                IsStringValue = true;
                                Value         = token.GetImage();
                            }
                            else
                            {
                                VarName = token.GetImage();
                            }
                            break;

                        case (int)KropConstants.INPUT:
                            inputValue    = true;
                            IsStringValue = true;
                            break;
                        }
                    }
                }
            }
        }
示例#9
0
        public BooleanExpression(Node _nodeBooleanExpression, Subprogram _parentSubprogram, bool _isNot)
        {
            ParentSubprogram = _parentSubprogram;
            IsNot            = _isNot;

            for (int i = 0; i < _nodeBooleanExpression.GetChildCount(); i++)
            {
                switch (_nodeBooleanExpression.GetChildAt(i).GetId())
                {
                case (int)KropConstants.EXPRESSION:
                    ExpressionOne = _nodeBooleanExpression.GetChildAt(i);
                    break;

                case (int)KropConstants.BOOLEAN_EXPRESSION_REST:
                    for (int y = 0; y < _nodeBooleanExpression.GetChildAt(i).GetChildCount(); y++)
                    {
                        switch (_nodeBooleanExpression.GetChildAt(i).GetChildAt(y).GetId())
                        {
                        case (int)KropConstants.EGAL:
                            IsEgal = true;
                            break;

                        case (int)KropConstants.BIGGER:
                            IsBigger = true;
                            break;

                        case (int)KropConstants.SMALLER:
                            IsSmaller = true;
                            break;

                        case (int)KropConstants.EXPRESSION:
                            ExpressionTwo = _nodeBooleanExpression.GetChildAt(i).GetChildAt(y);
                            break;
                        }
                    }
                    break;
                }
            }
        }
示例#10
0
        public InstructionWhile(Node _nodeWhileStatement, Subprogram _parentSubprogram)
        {
            ParentSubprogram = _parentSubprogram;

            //Construct the While branch
            for (int i = 0; i < _nodeWhileStatement.GetChildCount(); i++)
            {
                switch (_nodeWhileStatement.GetChildAt(i).GetId())
                {
                case (int)KropConstants.CONDITON_STATEMENT:
                    this.Conds = Subprogram.SetCond(_nodeWhileStatement.GetChildAt(i), _parentSubprogram);
                    break;

                case (int)KropConstants.PROGRAM:
                    this.WhileBranch = new Subprogram(_nodeWhileStatement.GetChildAt(i), _parentSubprogram);
                    break;

                default:
                    break;
                }
            }
        }
示例#11
0
        public override bool Execute()
        {
            if (CanExecute())
            {
                if (inputValue)
                {
                    Value = Subprogram.PromptInputValue <string>();
                }
                else
                {
                    Value = AlgorithmicExpression.CalculStringExpression(stringExpression, ParentSubprogram);
                }

                if (Value != null && IsStringValue == true)
                {
                    FormControlWindow.TerminalWriteLine("Fourmi dit : " + Value);
                    return(true);
                }
                else
                {
                    if (VarName != null && IsStringValue == false)
                    {
                        if ((Value = Subprogram.VarToString(VarName, ParentSubprogram)) == null)
                        {
                            ErrorMsg = "Variable " + VarName + " n'existe pas.";
                        }
                        else
                        {
                            FormControlWindow.TerminalWriteLine("Fourmi dit : " + Value);
                            return(true);
                        }
                    }
                }
            }

            FormControlWindow.TerminalWriteLine("DireError : " + ErrorMsg);
            return(false);
        }
示例#12
0
 public virtual void SetValue(T _value)
 {
     Subprogram.VarValueChanged(this);
 }
示例#13
0
        public static Subprogram BuildIR(this MethodInfo method,
                                         IList <SpecialRegister> srpool,
                                         IDictionary <MethodInfo, Subprogram> spmap,
                                         bool anonymousKernel = false)
        {
            if (!method.IsStatic)
            {
                throw new ArgumentException("Only static methods are supported", "method");
            }

            bool kernel = anonymousKernel || Attribute.GetCustomAttribute(method, typeof(KernelAttribute)) != null;
            bool result = method.ReturnType != typeof(void);

            if (kernel && result)
            {
                throw new ArgumentException("Kernels can not have return parameter", "method");
            }

            List <FormalParameter> formalParameters = new List <FormalParameter>(method.GetParameters().Select(pi =>
            {
                PassingStyles ps   = pi.ParameterType.IsByRef ? pi.IsOut ? PassingStyles.OUT : PassingStyles.REF : PassingStyles.VAL;
                Type pt            = pi.ParameterType.IsByRef ? pi.ParameterType.GetElementType() : pi.ParameterType;
                FormalParameter fp = pt.IsArray ? new FormalParameter(pt.GetElementType(), anonymousKernel ? StateSpaces.GLOBAL :
                                                                      (Attribute.GetCustomAttribute(pi, typeof(StateSpaceAttribute)) as StateSpaceAttribute).StateSpace, ps) :
                                     new Argument(pt, ps);
                fp.Name = pi.Name;
                return(fp);
            }));

            if (result)
            {
                FormalParameter returnParameter = method.ReturnType.IsArray ? new FormalParameter(method.ReturnType.GetElementType(),
                                                                                                  (Attribute.GetCustomAttribute(method.ReturnParameter, typeof(StateSpaceAttribute)) as StateSpaceAttribute).StateSpace,
                                                                                                  PassingStyles.OUT) :
                                                  new Argument(method.ReturnType, PassingStyles.OUT);
                returnParameter.Name = method.Name;
                formalParameters.Add(returnParameter);
            }

            IList <FormalParameter> formalParametersRO = formalParameters.AsReadOnly();

            IList <VirtualRegister> localVariablesRO = new List <VirtualRegister>(method.GetMethodBody().LocalVariables.Select(lvi =>
                                                                                                                               new VirtualRegister(InstructionSelector.UpconvertMapping[lvi.LocalType.IsArray ? typeof(int) : lvi.LocalType]))).AsReadOnly();

            Subprogram subprogram = kernel ? new Kernel(formalParametersRO) : new Subprogram(formalParametersRO);

            subprogram.Name = method.Name;

            spmap.Add(method, subprogram);

            Func <Type, StateSpaces, InstructionSelector.DynamicRegister> regalloc =
                IRBuildOptions.WasteRegisters ?
                (Func <Type, StateSpaces, InstructionSelector.DynamicRegister>)RegisterAllocator.Waste :
                new RegisterAllocator().Allocate;

            subprogram.CFGRoot = BuildIRCFG(BuildCILCFG(method.GetInstructions().First()),
                                            new Stack <Tuple <Tuple <GenericOperand, bool>, InstructionSelector> >(),
                                            new Dictionary <CILBB, List <CILBBImplementation> >(),
                                            formalParametersRO, localVariablesRO, result, srpool, spmap, regalloc).AsBasicBlock;

            if (regalloc.Target != null && !(regalloc.Target as RegisterAllocator).FinishTest())
            {
                throw new Exception("There is a bug in instruction selecting phase: we have live registers");
            }

            return(subprogram);
        }
示例#14
0
        public static string ToPTX(this Subprogram subprogram, bool declaration = false)
        {
            StringBuilder ptx = new StringBuilder();

            // Declare header.

            if (subprogram is Kernel)
            {
                ptx.AppendFormat(".entry {0}({1})", subprogram.Name, string.Join(", ", subprogram.FormalParameters.Select(fp =>
                                                                                                                          ".param." + (fp.StateSpace == StateSpaces.REG ? fp.UnderlyingType.ToPTX() : fp.DataType.ToPTX() +
                                                                                                                                       ".ptr." + fp.StateSpace.ToString().ToLower() + ".align " + fp.UnderlyingType.SizeOf()) +
                                                                                                                          " " + "%param$" + fp)));
            }
            else
            {
                ptx.AppendFormat(".func ({0}){1}({2})",
                                 string.Join(", ", from fp in subprogram.FormalParameters where fp.PassingStyle != PassingStyles.VAL
                                             select ".reg." + fp.DataType.ToPTX() + " " + fp),
                                 subprogram.Name,
                                 string.Join(", ", from fp in subprogram.FormalParameters where fp.PassingStyle != PassingStyles.OUT
                                             select ".reg." + fp.DataType.ToPTX() + " " + (fp.PassingStyle == PassingStyles.REF ? "%init$" : "") + fp));
            }

            if (declaration)
            {
                return(ptx.ToString());
            }
            else
            {
                ptx.AppendLine();
            }

            ptx.AppendLine("{");

            if (subprogram is Kernel)
            {
                // Declare argument-to-register mappings.
                ptx.AppendLine("// Argument-to-register mappings.");
                ptx.AppendLine(string.Join("\n", subprogram.FormalParameters.Select(ep => ".reg." + ep.DataType.ToPTX() + " " + ep + ";")));
            }

            // Perform basic blocks labeling.
            IList <BasicBlock> bblist = subprogram.GetBasicBlocks();

            for (int idx = 0; idx < bblist.Count(); idx++)
            {
                bblist.ElementAt(idx).Label = "BB" + idx;
            }

            // Perform register counting and naming.
            Dictionary <Type, int> typestats = new Dictionary <Type, int>();

            foreach (Type type in Util.NumericTypes.Add(typeof(bool)))
            {
                typestats.Add(type, 0);
            }
            foreach (VirtualRegister vr in subprogram.LocalVariables)
            {
                if (vr.Name == null)
                {
                    vr.Name = (typestats[vr.DataType]++).ToString();
                }
                else
                {
                    typestats[vr.DataType] = Math.Max(typestats[vr.DataType], int.Parse(vr.Name) + 1);
                }
                vr.Name = "%" + vr.DataType.Format() + "$" + vr.Name;
            }

            Console.WriteLine("INFO: There are {0} virtual registers in PTX code for {1}",
                              typestats.Sum(kvp => kvp.Value) + subprogram.FormalParameters.Count, subprogram.Name);

            // Perform register declaration.
            ptx.AppendLine("// Internally used registers.");
            ptx.AppendLine(".reg.pred %p;");
            ptx.AppendLine(string.Join("\n", from typestat in typestats where typestat.Value > 0
                                       select ".reg." + typestat.Key.ToPTX() + " %" + typestat.Key.Format() + "$<" + typestat.Value.ToString() + ">;"));

            if (subprogram is Kernel)
            {
                // Perform kernel parameters loading.
                ptx.AppendLine("// Kernel parameters loading.");
                ptx.AppendLine(string.Join("\n", subprogram.FormalParameters.Select(fp => "ld.param." +
                                                                                    (fp.StateSpace == StateSpaces.REG ? fp.UnderlyingType.ToPTX() : fp.DataType.ToPTX()) + " " +
                                                                                    fp + ", [%param$" + fp + "];")));
            }
            else
            {
                // Perform ref-parameters initialization.
                ptx.AppendLine("// Ref-parameters initialization.");
                ptx.AppendLine(string.Join("\n", from fp in subprogram.FormalParameters where fp.PassingStyle == PassingStyles.REF
                                           select "mov." + fp.DataType.ToPTX() + " " + fp + ", %init$" + fp + ";"));
            }

            // Perform basic blocks code generation.
            for (int i = 0; i < bblist.Count - 1; i++)
            {
                ptx.AppendLine(bblist[i].ToPTX(bblist[i + 1]));
            }
            ptx.Append(bblist[bblist.Count - 1].ToPTX(null));
            ptx.AppendLine("}");

            return(ptx.ToString());
        }