Example #1
0
        public StructureDefine(string S)
        {
            operationString = "List values";
            //returnType = new ValueType(VT.Cadress);
            ValueType curVt = new ValueType(VT.Cunknown);

            values = new List <IOperation>();

            if (S.Length == 0)
            {
                return;
            }
            string[] sSplited = MISC.splitBy(S, ',').ToArray();
            for (int i = 0; i < sSplited.Length; i++)
            {
                try
                {
                    values.Add(BinaryOperation.ParseFrom(sSplited[i]));

                    if (i > 0 && curVt != values[values.Count - 1].returnTypes())
                    {
                        throw new Exception("Define struct must contain only monotype args");
                    }

                    curVt = values[values.Count - 1].returnTypes();
                }
                catch (Exception e)
                {
                    throw new Exception("Can not parse define from \"" + sSplited[i] + "\"");
                }
            }
            returnType = curVt.TypeOfPointerToThis();
        }
Example #2
0
 public CycleFor(string parseCondition, CommandOrder actions)
 {
     condition            = new Equal(BinaryOperation.ParseFrom(parseCondition), new ASTvalue(new ValueType(VT.Cboolean), (object)true));
     this.actions         = actions;
     GlobalOperatorNumber = ++MISC.GlobalOperatorNumber;
     FindIterateVars();
 }
Example #3
0
 public CycleWhile(string parseCondition, string parseActions, bool doFirst)
 {
     condition = new Equal(BinaryOperation.ParseFrom(parseCondition), new ASTvalue(new ValueType(VT.Cboolean), (object)true));
     MISC.GoDeep("WHILE");
     actions = new CommandOrder(parseActions, ';');
     MISC.GoBack();
     this.doFirst = doFirst;
 }
Example #4
0
        public ASTTree(string s)
        {
            string sTrim = "";

            ClearTree();

            sTrim    = FuncTrimmer(s); // remove last ^
            original = s;
            string[] funcParseMaterial = sTrim.Split('^');
            try
            {
                for (int i = 0; i < funcParseMaterial.Length; i++)
                {
                    if (funcParseMaterial[i].IndexOf("(") >= 0)
                    {
                        funcs.Add(new ASTFunction(funcParseMaterial[i]));
                    }
                    else
                    {
                        IOperation def = BinaryOperation.ParseFrom(funcParseMaterial[i]);
                        if ((def as Assum) == null && (def as Define) == null)
                        {
                            throw new Exception("Can not parse function or define:\t " + MISC.StringFirstLetters(funcParseMaterial[i], 20, true));
                        }
                        else
                        {
                            GlobalVars.MergeWith(new CommandOrder(new ICommand[] { def }));
                        }
                    }
                }
                // after function declaration we have int foo(); int foo(){return 0;}; need to make them a one function
                for (int i = 0; i < funcs.Count; i++)
                {
                    for (int j = i + 1; j < funcs.Count; j++)
                    {
                        if (funcs[i] != null && funcs[j] != null)
                        {
                            if (MISC.CompareFunctionSignature(funcs[i], funcs[j]))
                            {
                                funcs[i] = funcs[j]; funcs[j] = null;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MISC.ConsoleWriteLine("ERROR:\n" + e.Message, ConsoleColor.Red);
                ClearTree();
                return;
            }
        }
Example #5
0
 public static IOperation ParseFrom(string s)
 {
     if (s.IndexOf("break") == 0)
     {
         return(new Brk());
     }
     if (s.IndexOf("continue") == 0)
     {
         return(new Cnt());
     }
     if (s.IndexOf("return") == 0)
     {
         return(new Ret(BinaryOperation.ParseFrom(s.Substring(6))));
     }
     throw new Exception("Can not parse uniq keyword:\t " + MISC.StringFirstLetters(s, 20, true));
 }
Example #6
0
        public OperatorIf(string parseCondition, string parseActions, string parseElseAction)
        {
            condition = new Equal(BinaryOperation.ParseFrom(parseCondition), new ASTvalue(new ValueType(VT.Cboolean), (object)true));
            actions   = new List <CommandOrder>();
            actions.Add(new CommandOrder());
            actions.Add(new CommandOrder());

            MISC.GoDeep("IFTHEN");
            actions[0].MergeWith(new CommandOrder(parseActions, ';'));
            MISC.GoBack();
            if (parseElseAction.Length > 0)
            {
                MISC.GoDeep("IFELSE");
                actions[1].MergeWith(new CommandOrder(parseElseAction, ';'));
                MISC.GoBack();
            }
        }
Example #7
0
        public static IOperation ParseFrom(string s)
        {
            if (s.IndexOf('{') == 0 && s.LastIndexOf('}') == s.Length - 1)
            {
                return(new StructureDefine(MISC.getIn(s, 0)));
            }
            if (s.IndexOf('(') == 0 && s.LastIndexOf(')') == s.Length - 1)
            {
                return(BinaryOperation.ParseFrom(MISC.breakBrackets(s)));
            }


            if (s.Length > 2 && s.IndexOf("--") == s.Length - 2)
            {
                return(new Dscr(ParseFrom(s.Substring(0, s.Length - 2))));
            }

            if (s.Length > 2 && s.IndexOf("++") == s.Length - 2)
            {
                return(new Incr(ParseFrom(s.Substring(0, s.Length - 2))));
            }

            if (s.IndexOf("-") == 0)
            {
                return(new Mins(ParseFrom(s.Substring(1, s.Length - 1))));
            }

            if (s.IndexOf("!") == 0)
            {
                return(new Nega(ParseFrom(s.Substring(1, s.Length - 1))));
            }

            if (s.IndexOf("&") == 0)
            {
                IOperation gettingAdressOf = ParseFrom(s.Substring(1, s.Length - 1));

                return(new Adrs(gettingAdressOf));
            }
            if (s.IndexOf("*") == 0)
            {
                IOperation pointTo = ParseFrom(s.Substring(1, s.Length - 1));
                return(new GetValByAdress(pointTo, (pointTo).returnTypes()));

                throw new Exception("Invalid pointer selected!");
            }
            if (s.LastIndexOf("]") == s.Length - 1 && s.IndexOf("[") > 0)
            {
                string        sContainBrackets = s.Substring(s.IndexOf("["));
                List <string> getedBrs         = MISC.splitByQuad(sContainBrackets);

                IOperation resOper = ParseFrom(s.Substring(0, s.IndexOf('[')));

                for (int o = 0; o < getedBrs.Count; o++)
                {
                    IOperation currentBrsOp = BinaryOperation.ParseFrom(getedBrs[o]);
                    resOper = new GetValByAdress(new Summ(resOper, currentBrsOp), resOper.returnTypes());
                }
                return(resOper);
            }
            try
            {
                return(new ASTFunctionCall(s));
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("is not a function") < 0)
                {
                    throw new Exception(e.Message);
                }
            }

            int varType = Math.Max((s.IndexOf("int") >= 0) ? 2 : -1, Math.Max((s.IndexOf("double") >= 0) ? 5 : -1, Math.Max((s.IndexOf("char") >= 0) ? 3 : -1,
                                                                                                                            Math.Max((s.IndexOf("string") >= 0) ? 5 : -1, (s.IndexOf("bool") >= 0) ? 3 : -1))));

            if (varType >= 0)
            {
                s = s.Insert(varType + 1, "$");
                return(new Define(s));
            }


            //f (s.IndexOf('(') == 0 && s.LastIndexOf(')') == s.Length - 1)
            //return ParseFrom(MISC.breakBrackets(s));



            try
            {
                return(new ASTvalue(s));
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("GetAddr") == 0)
                {
                    int newAdress = int.Parse(e.Message.Split('_')[1]);
                    return(new GetValByAdress(new ASTvalue(new ValueType(VT.Cadress), (object)newAdress),
                                              ASTTree.variables[newAdress].getValueType));
                }
                throw new Exception(e.Message);
            }
        }
Example #8
0
        public ASTFunctionCall(string s)
        {
            string ErrString = "";

            if (s.IndexOf("(") < 0)
            {
                throw new Exception(s + " is not a function!");
            }
            string approximateFuncName = s.Substring(0, s.IndexOf("("));
            bool   foundAnalog = false; int i = 0;
            //define required types
            string incomeValuesString = MISC.getIn(s, s.IndexOf('('));

            List <ValueType> callingTypes;

            arguments = new List <IOperation>();

            if (incomeValuesString.Length > 0)
            {
                callingTypes = new List <ValueType>();
                List <string> incomeValues = MISC.splitBy(incomeValuesString, ',');
                for (int df = 0; df < incomeValues.Count; df++)
                {
                    arguments.Add(BinaryOperation.ParseFrom(incomeValues[df]));
                    callingTypes.Add(arguments[arguments.Count - 1].returnTypes());
                }
            }
            else
            {
                callingTypes = new List <ValueType>();
                //callingTypes.Add(ValueType.Cvoid);
            }

            i = 0;
            while (!foundAnalog && i < ASTTree.funcs.Count)
            {
                bool nameSame  = (ASTTree.funcs[i].getName == approximateFuncName);
                int  haveTypes = ASTTree.funcs[i].returnTypesList().Count,
                     callTypes = callingTypes.Count;

                if (nameSame && (haveTypes == callTypes || (haveTypes <= callTypes && ASTTree.funcs[i].infiniteParamsAfter >= 0)))
                {
                    int          checkCount = Math.Min(arguments.Count, ASTTree.funcs[i].ParamCount);
                    IOperation[] children = new IOperation[checkCount]; IOperation[] otherParmas = new IOperation[arguments.Count - checkCount];
                    for (int j = 0; j < arguments.Count; j++)
                    {
                        if (j < checkCount)
                        {
                            children[j] = arguments[j];
                        }
                        else
                        {
                            otherParmas[j - checkCount] = arguments[j];
                        }
                    }
                    if (callingTypes.Count != 0)
                    {
                        try
                        {
                            //ValueType returnType = MISC.CheckTypeCorrect(null, ASTTree.funcs[i].tpcv, ref children);
                            ValueType returnType = TypeConverter.TryConvert(ASTTree.funcs[i].tpcv, ref children);
                            arguments = children.ToList();
                            arguments.AddRange(otherParmas.ToList());
                            foundAnalog = true;
                            break;
                        }
                        catch (Exception e) { ErrString += e.Message + "\n"; };
                    }
                    else
                    {
                        if (nameSame && callTypes == 0 && callTypes == haveTypes)
                        {
                            foundAnalog = true; break;
                        }
                    }
                }
                //else
                //{
                //    if (nameSame)
                //    {
                //        foundAnalog = true; break;
                //    }
                //}
                //// if same name then check correct of all types including
                //if (nameSame)
                //{
                //    foundAnalog = true;
                //    List<ValueType> requiredArgTypes = ASTTree.funcs[i].returnTypesList();
                //    if (requiredArgTypes.Count == callingTypes.Count)
                //    {
                //        for (int j = 0; j < callingTypes.Count; j++)
                //            if (callingTypes[j] != requiredArgTypes[j])
                //                foundAnalog = false;    // не совпадает тип соответствующих аргументов
                //    }
                //    else
                //        foundAnalog = false;    // не совпадает количество параметров
                //}
                i++;
            }
            // declare
            functionCallNumber = i;

            //make bug
            if (!foundAnalog)
            {
                if (ErrString == "")
                {
                    throw new Exception("Function with this name/arguments was never declared!");
                }
                else
                {
                    throw new Exception(ErrString);
                }
            }
        }
Example #9
0
        public ICommand ParseCommand2(String S)
        {
            int s1 = MISC.IndexOfOnLevel0(S, "(", 0),
                s2 = MISC.IndexOfOnLevel0(S, ")", 0),
                p1 = MISC.IndexOfOnLevel0(S, "{", 0),
                p2 = MISC.IndexOfOnLevel0(S, "}", 0);

            if (s2 < s1 || p2 < p1)
            {
                throw new Exception("Command contains incorrect brackets:\t" + MISC.StringFirstLetters(S, 20, true));
            }

            if (p1 == 0 && p2 == S.Length - 1)
            {
                MISC.GoDeep("Block");
                CommandOrder co = new CommandOrder(MISC.getIn(S, 0), ';');
                MISC.GoBack();
                return(co);
            }

            // Binary operation usuall
            if ((p1 < 0 || (MISC.IndexOfOnLevel0(S, "=", 0) > 0)) &&
                S.ToLower().IndexOf("if") != 0 && S.ToLower().IndexOf("for") != 0)
            {
                IOperation newBO = BinaryOperation.ParseFrom(S);
                if ((newBO as Assum) != null && (newBO as Assum).requiredUpdate != "none")
                {
                    string needUpdate = (newBO as Assum).requiredUpdate;
                    if (needUpdate.IndexOf("structdefineinfor") == 0)
                    {
                        string nam = (newBO as Assum).GetAssumableName;
                        if (nam == "-")
                        {
                            throw new Exception("What are you doing!?");
                        }
                        List <IOperation> values = (newBO as Assum).GetStructDefine();
                        List <ICommand>   res    = new List <ICommand>();
                        for (int i = 0; i < values.Count; i++)
                        {
                            res.Add(new Assum(BinaryOperation.ParseFrom(nam + "[" + i + "]"), values[i]));
                        }

                        return(new CommandOrder(res.ToArray()));
                    }
                }
                else
                {
                    return(newBO);
                }
            }
            // _______________________
            if (s1 > 0)
            {
                string operatorFind = S.Remove(s1);
                // simple if
                if (operatorFind == "if")
                {
                    // we gonna parse IF from this shit!
                    string conditionParse   = MISC.getIn(S, 2),
                           firstActionParse = S.Substring(s2 + 1);

                    int indElse = MISC.IndexOfOnLevel0(firstActionParse, "else", 0);
                    if (indElse > 0)
                    {
                        string secondActionParse = firstActionParse.Substring(indElse + 4);
                        firstActionParse = firstActionParse.Substring(0, indElse);

                        return(new OperatorIf(conditionParse, firstActionParse, secondActionParse));
                    }
                    return(new OperatorIf(conditionParse, firstActionParse, ""));
                }
                // simple while
                if (operatorFind == "while")
                {
                    string conditionParse = MISC.getIn(S, 5),
                           iterationParse = S.Substring(s2 + 1);
                    return(new CycleWhile(conditionParse, iterationParse, false));
                }
                // reverse while
                if (p1 == 2 && S.Remove(p1) == "do")
                {
                    int whilePos = MISC.IndexOfOnLevel0(S, "while", 0);

                    if (whilePos < -1)
                    {
                        throw new Exception("No while, but used \"do\"\t " + MISC.StringFirstLetters(S, 20, true));
                    }

                    string iterationParse = MISC.getIn(S, 2),
                           conditionParse = MISC.getIn(S, s1);

                    return(new CycleWhile(conditionParse, iterationParse, true));
                }
                // FOR mazafaka
                if (operatorFind == "for")
                {
                    string partsParse = MISC.getIn(S, 3),
                           allOther   = S.Substring(s2 + 1);
                    string[] spp      = partsParse.Split(';');
                    if (spp.Length != 3)
                    {
                        throw new Exception("Invalid count of FOR-cycle condition parts\t " + MISC.StringFirstLetters(S, 20, true));
                    }

                    MISC.GoDeep("FOR");
                    this.MergeWith(new CommandOrder(spp[0], ','));
                    if (spp[1] == "")
                    {
                        spp[1] = "true";                // condition
                    }
                    CommandOrder actions = new CommandOrder(allOther, ';'); actions.MergeWith(new CommandOrder(spp[2], ','));


                    CycleFor cf = new CycleFor(spp[1], actions);
                    MISC.GoBack();

                    return(cf);
                }
                throw new Exception("Can not parse a command\t " + MISC.StringFirstLetters(S, 20, true));
            }

            return(new CommandOrder());
        }
Example #10
0
        public Define(string s, bool autoAssume)
        {
            //string firstPart = s.Substring(0, s.IndexOf("$") + 1);  // int&a,b
            //while (s.IndexOf(',') > 0)
            //{
            //    int at = s.IndexOf(',');
            //    s = s.Substring(0, s.IndexOf(',')) + ';' + firstPart + s.Substring(s.IndexOf(',') + 1);
            //    //
            //}

            string[] ss = s.Split('$');
            //string varName;
            VT   varType;
            bool everDefined = false;

            for (int i = 0; i < ASTTree.variables.Count; i++)
            {
                if (ASTTree.variables[i].name == ss[1] && MISC.isVariableAvailable(i))
                {
                    everDefined = true; break;
                }
            }

            if (ss[1].Length > 0 && !everDefined)
            {
                varName = ss[1];
            }
            else
            {
                throw new Exception("Can not define " + ((everDefined) ? "again " : "") + "variable with name \"" + ss[1] + "\"");
            }

            ss[0].ToLower();
            varType = detectType(ss[0]);

            //for (int i =0; i < varName.Length; i++){
            //bool isPointer = false;
            int pointerLevel = 0;

            while (varName.IndexOf('*') == 0)
            {
                pointerLevel++; varName = varName.Substring(1);
            }
            returnType = new ValueType(varType, pointerLevel);
            defineType = returnType;

            //____________________________________

            if (varName.LastIndexOf("]") == varName.Length - 1 && varName.IndexOf("[") > 0)
            {
                List <string> inBr = MISC.splitByQuad(varName);  // [] [] [ ] []
                varName = varName.Substring(0, varName.IndexOf('['));

                for (int ib = 0; ib < inBr.Count; ib++)
                {
                    string inBrack = inBr[ib];
                    int    length  = 0;
                    if (inBrack != "")
                    {
                        IOperation arrayLength = BinaryOperation.ParseFrom(inBrack);
                        if (arrayLength.returnTypes() != VT.Cint)
                        {
                            throw new Exception("Int only can be array length parameter");
                        }
                        //IOperation arrayLength = BinaryOperation.ParseFrom(inBrack);
                        //if (arrayLength as ASTvalue == null || arrayLength.returnTypes() != VT.Cint)
                        //    throw new Exception("Incorrect array length parameters!");

                        //length = (int)(arrayLength as ASTvalue).getValue;
                        //if (length < 1)
                        //    throw new Exception("Array length should be 1 and more!");
                    }

                    //for (int i = 0; i < length; i++)
                    //{
                    //    // as default variable
                    //    ASTvariable newVar = new ASTvariable(new ValueType(varType, pointerLevel), varName + "#" + i, 0);
                    //    ASTTree.variables.Add(newVar);
                    //    MISC.pushVariable(ASTTree.variables.Count - 1);
                    //    ASTTree.tokens.Add(newVar);
                    //}
                    defineType = defineType.TypeOfPointerToThis();
                }
            }
            //_________________________________________

            ASTvariable NV = new ASTvariable(defineType, varName, pointerLevel, MISC.GetCurrentVariableAdressType());

            var = NV;
            ASTTree.variables.Add(NV);
            MISC.pushVariable(ASTTree.variables.Count - 1);
            if (autoAssume)
            {
                MISC.defineVariable(ASTTree.variables.Count - 1);
            }

            ASTTree.tokens.Add(NV);
            a = NV;

            returnType = a.returnTypes();

            b = new ASTvalue(new ValueType(VT.Cadress), (object)(ASTTree.variables.Count - 1));
        }
Example #11
0
        public ASTTree(string s, string path)
        {
            LLVM.CurrentCode = "";
            this.path        = path;
            string sTrim = "";

            ClearTree();

            data = DateTime.Now;

            sTrim    = FuncTrimmer(s); // remove last ^
            original = s;
            string[] funcParseMaterial = sTrim.Split('^');
            generatedTime.Add((DateTime.Now - data).Seconds * 1000 + (DateTime.Now - data).Milliseconds); data = DateTime.Now;
            try
            {
                for (int i = 0; i < funcParseMaterial.Length; i++)
                {
                    if (funcParseMaterial[i].IndexOf("(") >= 0)
                    {
                        funcs.Add(new ASTFunction(funcParseMaterial[i]));

                        int found = -1;
                        for (int f = 0; f < funcs.Count - 1; f++)
                        {
                            if (funcs[f].getName == funcs[funcs.Count - 1].getName)
                            {
                                found++;
                            }
                        }
                        funcs[funcs.Count - 1].LLVMnumber = found;
                    }
                    else
                    {
                        IOperation def = BinaryOperation.ParseFrom(funcParseMaterial[i]);
                        if ((def as Assum) == null && (def as Define) == null)
                        {
                            throw new Exception("Can not parse function or define:\t " + MISC.StringFirstLetters(funcParseMaterial[i], 20, true));
                        }
                        else
                        {
                            GlobalVars.MergeWith(new CommandOrder(new ICommand[] { def }));
                        }
                    }
                }
                // after function declaration we have int foo(); int foo(){return 0;}; need to make them a one function
                for (int i = 0; i < funcs.Count; i++)
                {
                    for (int j = i + 1; j < funcs.Count; j++)
                    {
                        if (funcs[i] != null && funcs[j] != null)
                        {
                            if (MISC.CompareFunctionSignature(funcs[i], funcs[j]))
                            {
                                funcs[i] = funcs[j]; funcs[j] = null;
                            }
                        }
                    }
                }

                //GlobalVarsVars = GlobalVars.findAllVariables();
                foreach (ASTvariable va in variables)
                {
                    if (va.adress.typ == VAT.Global && va.everUsed > 0)
                    {
                        GlobalVarsVars.Add(va);
                    }
                }
            }
            catch (Exception e)
            {
                MISC.ConsoleWriteLine("ERROR:\n" + e.Message, ConsoleColor.Red);
                ClearTree();
                return;
            }
            generatedTime.Add((DateTime.Now - data).Seconds * 1000 + (DateTime.Now - data).Milliseconds);
        }
Example #12
0
 public CycleWhile(string parseCondition, CommandOrder actions, bool doFirst)
 {
     condition    = new Equal(BinaryOperation.ParseFrom(parseCondition), new ASTvalue(new ValueType(VT.Cboolean), (object)true));
     this.actions = actions;
     this.doFirst = doFirst;
 }