Exemplo n.º 1
0
        public string CreateNfaRule(ParseTreeNode node)
        {
            string ruleName = node.FindTokenAndGetText();

            if (_partNumber.ContainsKey(ruleName))
            {
                string parts  = "";
                int    number = _partNumber[ruleName];
                for (int i = 0; i <= number; i++)
                {
                    if (parts != "")
                    {
                        parts += ", ";
                    }
                    parts += "Get" + ruleName.Replace('-', '_') + i + "(rulenames)";
                }

                _partNumber.Remove(ruleName);

                return("\t\tpublic State Get" + ruleName.Replace('-', '_') + "(List<string> rulenames)\r\n" +
                       "\t\t{\r\n" +
                       "\t\t\trulenames.Insert(0, \"" + node.FindTokenAndGetText() + "\");\r\n" +
                       "\t\t\tState rule = State.NoCloneAlternation(" + parts + ");\r\n" +
                       "\t\t\trule = OnMarkRule(rule, rulenames);\r\n" +
                       "\t\t\trulenames.RemoveAt(0);\r\n" +
                       "\t\t\treturn rule;\r\n" +
                       "\t\t}\r\n");
            }

            return("");
        }
Exemplo n.º 2
0
        public string CreateNfaRulePart(ParseTreeNode node)
        {
            ParseTreeNode elements = null;

            foreach (var child in node.ChildNodes)
            {
                if (child.Term.Name == "elements")
                {
                    elements = child;
                }
            }

            var nodeName = node.FindTokenAndGetText();
            int number   = 0;

            if (_partNumber.ContainsKey(nodeName))
            {
                number = _partNumber[nodeName] + 1;
            }
            _partNumber[nodeName] = number;

            return("\t\tpublic State Get" + node.FindTokenAndGetText().Replace('-', '_') + number + "(List<string> rulenames)\r\n" +
                   "\t\t{\r\n" +
                   "\t\t\tState rule = " + CreateAlternation(elements.ChildNodes[0], true) + ";\r\n" +
                   "\t\t\treturn rule;\r\n" +
                   "\t\t}\r\n");
        }
Exemplo n.º 3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="node"></param>
 /// <param name="index"></param>
 ///
 private void ChildrenNodesRetrevial(ParseTreeNode node, ref int index)
 {
     if (node.ChildNodes.Count > 0)
     {
         foreach (var item in node.ChildNodes)
         {
             ChildrenNodesRetrevial(item, ref index);
         }
     }
     else if (node.FindTokenAndGetText() != null)
     {
         _cSharpCode[index] = _cSharpCode[index] + node.FindTokenAndGetText() + " ";
     }
 }
Exemplo n.º 4
0
        private static string GetParseTreeNodeText(ParseTreeNode parseTreeNode)
        {
            if (parseTreeNode == null)
            {
                return(string.Empty);
            }

            // We cannot use FindTokenAndGetText always because it will give us only the text of the root node in
            // case of complex expressions. So we have to do that:
            if (parseTreeNode.ChildNodes.Count > 0)
            {
                var result = new StringBuilder();
                foreach (var node in parseTreeNode.ChildNodes)
                {
                    int offset = node.Span.Location.Position - parseTreeNode.Span.Location.Position;
                    if (result.Length < offset)
                    {
                        result.Append(' ', offset - result.Length);
                    }

                    result.Append(GetParseTreeNodeText(node));
                }

                return(result.ToString());
            }

            return(parseTreeNode.FindTokenAndGetText() ?? string.Empty);
        }
Exemplo n.º 5
0
        ///Translate a constant number (Int32 or Double)
        private ILanguageExpression translate_Constant_Number(ParseTreeNode node)
        {
            var numberText = node.FindTokenAndGetText();

            Int32 intNumber;

            if (Int32.TryParse(numberText, out intNumber))
            {
                return(ValuePrimitive <MathematicaScalar> .Create(
                           GMacRootAst.ScalarType,
                           MathematicaScalar.Create(SymbolicUtils.Cas, intNumber)
                           ));
            }

            Double doubleNumber;

            if (Double.TryParse(numberText, out doubleNumber))
            {
                return(ValuePrimitive <MathematicaScalar> .Create(
                           GMacRootAst.ScalarType,
                           MathematicaScalar.Create(SymbolicUtils.Cas, doubleNumber)
                           ));
            }

            return(CompilationLog.RaiseGeneratorError <ILanguageExpression>("Constant number not recognized", node));
        }
Exemplo n.º 6
0
 // this is where data is initially passed to the item
 public override void Init(AstContext context, ParseTreeNode treeNode)
 {
     string sVal = treeNode.FindTokenAndGetText();
     base.Init(context, treeNode);
     var nodes = treeNode.GetMappedChildNodes();
     var functionOrProperty = AddChild("FunctionOrId", nodes[0]);
     if (functionOrProperty is SelectFunctionNode)
     {
         _TheFunction = (SelectFunctionNode)functionOrProperty;
     }
     else if (functionOrProperty is SelectPropertyNode)
     {
         _PropNode = (SelectPropertyNode)functionOrProperty;
     }
     else
     {
         throw new Exception("Unmanaged type in selectmemberaccessnode");
     }
     if (nodes.Count > 1)
     {
         var child = AddChild("Queue", nodes[1]);
         string sval = nodes[1].FindTokenAndGetText();
         if (child is LeftObjectNode)
         {
             _queue = (LeftObjectNode)child;
         }
     }
 }
Exemplo n.º 7
0
        private IExpression BuildCharvalExpression(ParseTreeNode node)
        {
            var charval = node.FindTokenAndGetText();            //.Replace("\\", "\\\\");

            charval = charval.Substring(1, charval.Length - 2);
            return(new CharvalExpression(this, charval));
        }
Exemplo n.º 8
0
        private void PerformFor(string for_var_name, ParseTreeNode enter, ParseTreeNode action, ParseTreeNode statements)
        {
            int sum = action.FindTokenAndGetText() == "++" ? 1 : -1;

            while (true)
            {
                object exp = Scope.Solve(enter);

                if (exp == null || !(exp is bool) || !(bool)exp)
                {
                    return;
                }

                DoStatements(statements);

                if (Signal == Signal.BREAK)
                {
                    break;
                }

                Scope.AutoSum(for_var_name, sum);

                Signal = Signal.NORMAL;
            }
            Signal = Signal.NORMAL;
        }
Exemplo n.º 9
0
        internal static bool DrawAST(ParseTreeNode id)
        {
            if (id.ChildNodes.Count == 1)
            {
                string func_name = id.FindTokenAndGetText();

                List <ScopeMember> functs = Program.Global.GetFunctions(func_name);

                if (functs.Count != 0)
                {
                    foreach (var f in functs)
                    {
                        string fname = f.Name + f.GetHashCode();

                        ASTImageCreator imgCreator = new ASTImageCreator(f.Root, Program.ImagePath, fname, Function: true);

                        Logger.AddImg(imgCreator.GetAsImage64());
                    }
                    return(true);
                }
                else
                {
                    Logger.AddError(id, "No existe ninguna función con ese nombre");
                }
            }
            return(false);
        }
Exemplo n.º 10
0
 public override void Init(ParsingContext context, ParseTreeNode treeNode)
 {
     base.Init(context, treeNode);
     Node = treeNode;
     if (treeNode.ChildNodes.Count >= 2)
     {
         ParseTreeNode targetNode    = treeNode.ChildNodes[0];
         ParseTreeNode argumentsNode = treeNode.ChildNodes[1];
         if (treeNode.ChildNodes.Count == 4)
         {
             RefrerenceElement = AddChild("Reference", treeNode.ChildNodes[0]);
             targetNode        = treeNode.ChildNodes[2];
             argumentsNode     = treeNode.ChildNodes[3];
         }
         TargetRef = AddChild("Target", targetNode);
         Arguments = AddChild("Args", argumentsNode);
         string text = "";
         if (targetNode.Term.Name == "identifier")
         {
             text += targetNode.FindTokenAndGetText();
         }
         else
         {
             text += TargetRef.AsString;
         }
         if (targetNode.Term.FlagIsSet(TermFlags.IsOperator))
         {
             text += targetNode.Term.Name;
         }
         _targetName = text;
         AsString    = "Call " + _targetName;
     }
 }
Exemplo n.º 11
0
        private static AggregationFunction ToAggregationFunction(ParseTreeNode node)
        {
            var text = node.FindTokenAndGetText().ToLower();

            switch (text)
            {
            case "количество":
            case "count":
                return(AggregationFunction.Count);

            case "сумма":
            case "sum":
                return(AggregationFunction.Sum);

            case "минимум":
            case "min":
                return(AggregationFunction.Min);

            case "максимум":
            case "max":
                return(AggregationFunction.Max);

            case "среднее":
            case "avg":
                return(AggregationFunction.Avg);

            default:
                throw new InvalidOperationException(string.Format("Invalid aggregation function {0}", text));
            }
        }
Exemplo n.º 12
0
        //-----------------------------------------
        public void CreateDefinedRulesList(ParseTreeNode node, List<string> rulenames)
        {
            foreach (var child in node.ChildNodes)
                CreateDefinedRulesList(child, rulenames);

            if (node.Term.Name == "newrulename")
                rulenames.Add(node.FindTokenAndGetText());
        }
Exemplo n.º 13
0
        public static BaijiType BuildMapKeyType(ParseTreeNode mapKeyTypeNode)
        {
            var baseTypeKeyword = mapKeyTypeNode.FindTokenAndGetText();
            var bType           = ConvertBaseTypeKeywordToBaseType(baseTypeKeyword);
            var type            = new BaseType(bType);

            return(type);
        }
Exemplo n.º 14
0
        // Build a variable reference (the "v" in "v = 1"
        void BuildVariableReference(IronyParser parser, Root root, Expression parentExpression, ParseTreeNode currentNode)
        {
            var e = new VariableReference(parentExpression, currentNode.FindToken().Convert());

            e.Name             = currentNode.FindTokenAndGetText();
            e.ParentExpression = parentExpression;
            parentExpression.ChildExpressions.Add(e);
        }
Exemplo n.º 15
0
        public void CreateUsedRulesList(ParseTreeNode node, List <string> rulenames)
        {
            foreach (var child in node.ChildNodes)
            {
                CreateUsedRulesList(child, rulenames);
            }

            if (node.Term.Name == "rulename")
            {
                var rulename = node.FindTokenAndGetText();

                if (rulenames.Find((fromList) => { return(fromList == rulename); }) == null)
                {
                    rulenames.Add(node.FindTokenAndGetText());
                }
            }
        }
Exemplo n.º 16
0
        private static TeLiteralNumber TranslateLiteralNumber(ParseTreeNode exprNode)
        {
            exprNode.Assert(TextExpressionDslParseNodeNames.LiteralNumber);

            var numberText = exprNode.FindTokenAndGetText();

            return(new TeLiteralNumber(numberText));
        }
Exemplo n.º 17
0
        private static TeLiteralString TranslateSqString(ParseTreeNode exprNode)
        {
            exprNode.Assert(TextExpressionDslParseNodeNames.SqString);

            return(new TeLiteralString(
                       exprNode.FindTokenAndGetText().QuoteLiteralToValue()
                       ));
        }
Exemplo n.º 18
0
        private static SqlBinaryOperator ToBinaryOperator(ParseTreeNode node)
        {
            var operatorText = node.FindTokenAndGetText().ToLower();

            switch (operatorText)
            {
            case "and":
            case "и":
                return(SqlBinaryOperator.And);

            case "or":
            case "или":
                return(SqlBinaryOperator.Or);

            case "+":
                return(SqlBinaryOperator.Plus);

            case "-":
                return(SqlBinaryOperator.Minus);

            case "=":
                return(SqlBinaryOperator.Eq);

            case ">":
                return(SqlBinaryOperator.GreaterThan);

            case "<":
                return(SqlBinaryOperator.LessThan);

            case ">=":
                return(SqlBinaryOperator.GreaterThanOrEqual);

            case "<=":
                return(SqlBinaryOperator.LessThanOrEqual);

            case "like":
            case "подобно":
                return(SqlBinaryOperator.Like);

            case "<>":
            case "!=":
                return(SqlBinaryOperator.Neq);

            case "*":
                return(SqlBinaryOperator.Mult);

            case "/":
                return(SqlBinaryOperator.Div);

            case "%":
                return(SqlBinaryOperator.Remainder);

            default:
                throw new InvalidOperationException(string.Format("unexpected binary operator [{0}]", operatorText));
            }
        }
Exemplo n.º 19
0
        public override void Init(AstContext context, ParseTreeNode treeNode)
        {
            base.Init(context, treeNode);

            //TODO: units conversion
            _Value   = decimal.Parse(treeNode.FindTokenAndGetText(), CultureInfo.InvariantCulture);
            AsString = string.Format(
                CultureInfo.InvariantCulture,
                "{0:G}m",
                _Value
                );
        }
Exemplo n.º 20
0
        //public string CreateNfaRules(ParseTreeNode node)
        //{
        //    string result = "";
        //    foreach (var child in node.ChildNodes)
        //        result += CreateNfaRulePart(child);
        //    foreach (var child in node.ChildNodes)
        //        result += CreateNfaRule(child);
        //    return result;
        //}

        //public string CreateNfaRule(ParseTreeNode node)
        //{
        //    string ruleName = node.FindTokenAndGetText();

        //    if (_partNumber.ContainsKey(ruleName))
        //    {
        //        string parts = "";
        //        int number = _partNumber[ruleName];
        //        for (int i = 0; i <= number; i++)
        //        {
        //            if (parts != "")
        //                parts += ", ";
        //            parts += "Get" + ruleName.Replace('-', '_') + i + "(rulenames)";
        //        }

        //        _partNumber.Remove(ruleName);

        //        return "\t\tpublic State Get" + ruleName.Replace('-', '_') + "(List<string> rulenames)\r\n" +
        //            "\t\t{\r\n" +
        //            "\t\t\trulenames.Insert(0, \"" + node.FindTokenAndGetText() + "\");\r\n" +
        //            "\t\t\tState rule = State.NoCloneAlternation(" + parts + ");\r\n" +
        //            "\t\t\trule = OnMarkRule(rule, rulenames);\r\n" +
        //            "\t\t\trulenames.RemoveAt(0);\r\n" +
        //            "\t\t\treturn rule;\r\n" +
        //            "\t\t}\r\n";
        //    }

        //    return "";
        //}

        //public string CreateNfaRulePart(ParseTreeNode node)
        //{
        //    ParseTreeNode elements = null;
        //    foreach (var child in node.ChildNodes)
        //        if (child.Term.Name == "elements")
        //            elements = child;

        //    var nodeName = node.FindTokenAndGetText();
        //    int number = 0;
        //    if (_partNumber.ContainsKey(nodeName))
        //        number = _partNumber[nodeName] + 1;
        //    _partNumber[nodeName] = number;

        //    return "\t\tpublic State Get" + node.FindTokenAndGetText().Replace('-', '_') + number + "(List<string> rulenames)\r\n" +
        //        "\t\t{\r\n" +
        //        "\t\t\tState rule = " + CreateAlternation(elements.ChildNodes[0], true) + ";\r\n" +
        //        "\t\t\treturn rule;\r\n" +
        //        "\t\t}\r\n";
        //}

        //public string CreateAlternation(ParseTreeNode node, bool change)
        //{
        //    int count = 0;
        //    string result = "";
        //    foreach (var child in node.ChildNodes)
        //    {
        //        if (result != "")
        //            result += ",";
        //        //result += CreateConcatanation(child, change);
        //        result += CreateSubstraction(child, change);
        //        count++;
        //    }

        //    if (count > 1)
        //        result = "State.NoCloneAlternation(" + result + ")";

        //    return result;
        //}

        //public string CreateSubstraction(ParseTreeNode node, bool change)
        //{
        //    List<string> items = new List<string>();
        //    foreach (var child in node.ChildNodes)
        //        items.Add(CreateConcatanation(child, change));

        //    if (items.Count == 1)
        //        return items[0];

        //    if (items.Count == 2)
        //        return "State.Substract(" + items[0] + "," + items[1] + ")";

        //    throw new NotImplementedException();
        //    //return CreateConcatanation(node.FirstChild, change);
        //}

        //public string CreateConcatanation(ParseTreeNode node, bool change)
        //{
        //    List<string> items = new List<string>();

        //    foreach (var child in node.ChildNodes)
        //        items.Add(CreateRepeation(child));

        //    string result = "";
        //    foreach (var item in items)
        //    {
        //        if (result != "")
        //            result += ",";
        //        result += item;
        //    }

        //    if (items.Count > 1)
        //    {
        //        if (change)
        //            result = "State.NoCloneConcatanation(OnChangeConcatanation(rulenames," + result + "))";
        //        else
        //            result = "State.NoCloneConcatanation(" + result + ")";
        //    }

        //    return result;
        //}

        //public string CreateRepeation(ParseTreeNode node)
        //{
        //    if (node.ChildNodes[0].ChildNodes.Count == 0)
        //        return CreateElement(node.ChildNodes[1]);

        //    return CreateRepeat(node);
        //}

        //public string CreateRepeat(ParseTreeNode node)
        //{
        //    string repeatChar = "*";
        //    int repeat1 = -1, repeat2 = -1;
        //    var repeat = node.ChildNodes[0].ChildNodes[0];

        //    if (repeat.ChildNodes.Count == 1)
        //    {
        //        repeat2 = repeat1 = int.Parse(repeat.ChildNodes[0].FindTokenAndGetText());
        //    }
        //    else if (repeat.ChildNodes.Count >= 3)
        //    {
        //        if (repeat.ChildNodes[0].ChildNodes.Count != 0)
        //            repeat1 = int.Parse(repeat.ChildNodes[0].FindTokenAndGetText());

        //        repeatChar = repeat.ChildNodes[1].FindTokenAndGetText();

        //        if (repeat.ChildNodes[2].ChildNodes.Count != 0)
        //            repeat2 = int.Parse(repeat.ChildNodes[2].FindTokenAndGetText());
        //    }

        //    string result = null;
        //    if (repeatChar == "*")
        //    {
        //        result = "State.Repeat(" + repeat1 + "," + repeat2 + "," + CreateElement(node.ChildNodes[1]) + ")";
        //    }
        //    else if (repeatChar == "#")
        //    {
        //        if (repeat2 != -1)
        //            throw new NotImplementedException();

        //        result = "State.NoCloneRepeatBy(" + CreateElement(node.ChildNodes[1]) + ", GetCOMMA(rulenames))";

        //        if (repeat1 <= 0)
        //            result = "State.NoCloneOption(" + result + ")";

        //        if (repeat1 > 1)
        //            result = "State.Repeat(" + repeat1 + "," + repeat2 + "," + result + ")";
        //    }
        //    else
        //        throw new NotImplementedException();

        //    return result;
        //}

        //public string CreateElement(ParseTreeNode node)
        //{
        //    switch (node.ChildNodes[0].Term.Name)
        //    {
        //        case "rulename":
        //            return "Get" + node.ChildNodes[0].FindTokenAndGetText().Replace('-', '_') + "(rulenames)";
        //        case "group":
        //            return "(" + CreateAlternation(node.ChildNodes[0].ChildNodes[1], false) + ")";
        //        case "option":
        //            return "State.NoCloneOption(" + CreateAlternation(node.ChildNodes[0].ChildNodes[1], false) + ")";
        //        case "numval":
        //            return CreateNumval(node.ChildNodes[0]);
        //        case "charval":
        //            return CreateCharval(node.ChildNodes[0]);
        //        case "func":
        //            return CreateFunc(node.ChildNodes[0]);
        //    }

        //    throw new InvalidProgramException();
        //}

        //public string CreateNumval(ParseTreeNode node)
        //{
        //    if (node.ChildNodes[1].FirstChild.Term.Name == "hexval")
        //    {
        //        var hexval = node.ChildNodes[1].FirstChild;

        //        var hexdig1 = "0" + hexval.FirstChild.FindTokenAndGetText();
        //        if (hexval.ChildNodes.Count == 1)
        //            return hexdig1;

        //        var op = hexval.ChildNodes[1].FindTokenAndGetText();

        //        if (op == "-")
        //            return "(" + hexdig1 + ".To(0x" +
        //                hexval.ChildNodes[1].LastChild.FindTokenAndGetText() + "))";

        //        if (op == ".")
        //        {
        //            var hexvalpointstart = hexval.ChildNodes[1].FirstChild;

        //            string arr = hexdig1 + ",";
        //            foreach (var hexval1 in hexvalpointstart.ChildNodes)
        //                arr += "0x" + hexval1.LastChild.FindTokenAndGetText() + ",";

        //            return "(State)(new byte[] {" + arr + "})";
        //        }

        //        return hexdig1;
        //    }

        //    throw new InvalidProgramException("Dec and Binary const not implemented");
        //}

        //public string CreateCharval(ParseTreeNode node)
        //{
        //    return "FromString(" + node.FindTokenAndGetText().Replace("\\", "\\\\") + ",rulenames)";
        //}

        //public string CreateFunc(ParseTreeNode node)
        //{
        //    string args = "";

        //    foreach (var funcarg in node.ChildNodes[3].ChildNodes)
        //    {
        //        if (args != "")
        //            args += ",";
        //        args += CreateAlternation(funcarg.ChildNodes[0], false);
        //    }

        //    return node.ChildNodes[1].FindTokenAndGetText() + "(" + args + ")";
        //}

        //-----------------------------------------

        public void CreateDefinedRulesList(ParseTreeNode node, List <string> rulenames)
        {
            foreach (var child in node.ChildNodes)
            {
                CreateDefinedRulesList(child, rulenames);
            }

            if (node.Term.Name == "newrulename")
            {
                rulenames.Add(node.FindTokenAndGetText());
            }
        }
Exemplo n.º 21
0
        public override void Init(AstContext context, ParseTreeNode treeNode)
        {
            base.Init(context, treeNode);

            //TODO: units conversion
            _Value=decimal.Parse(treeNode.FindTokenAndGetText(), CultureInfo.InvariantCulture);
            AsString=string.Format(
                CultureInfo.InvariantCulture,
                "{0:G}m",
                _Value
            );
        }
Exemplo n.º 22
0
		private void BuildRuleExpressions(ParseTreeNode node)
		{
			var ruleName = node.FindTokenAndGetText();
			var rule = rules.ContainsKey(ruleName) ? rules[ruleName] : rules[ruleName] = new AlternationExpression();

			ParseTreeNode elements = null;
			foreach (var child in node.ChildNodes)
				if (child.Term.Name == "elements")
					elements = child;

			rule.Add(
				BuildAlternationExpression(elements.ChildNodes[0]));
		}
Exemplo n.º 23
0
        private static string GetNodeScript(ParseTreeNode node, int NodeId)
        {
            string script = "";

            script += $"{NodeId} [label=\"{node.Term}";
            string tokenText = node.FindTokenAndGetText();

            if (!string.IsNullOrEmpty(tokenText) && node.ChildNodes.Count == 0)
            {
                script += $" [{tokenText}]";
            }
            script += "\"];";
            return(script);
        }
Exemplo n.º 24
0
        private object GetExpValue(ParseTreeNode node)
        {
            if (node == null)
            {
                return(null);
            }

            string curr_content = node.FindTokenAndGetText();

            switch (node.Term.Name)
            {
            case "IDENTIFICADOR": return(GetVar(curr_content)?.Value);

            case "NUMERO":
                bool accepted = double.TryParse(curr_content, out double cont);

                return(accepted ? (object)cont : null);

            case "CADENA": return(curr_content.Replace("\"", ""));

            case "LOGICO_TRUE": return(true);

            case "LOGICO_FALSE": return(false);

            case "LLAMADA_FUNCION": return(Raise(node, this));

            case "EXPRESION":
            case "OPERANDO":
            case "OPERACION":
            {
                int childCount = node.ChildNodes.Count;

                switch (childCount)
                {
                //Operando unico
                case 1: return(GetExpValue(node.ChildNodes[0]));

                //Operando unario (-, !)
                case 2: return(Resolve(node.ChildNodes[0].FindTokenAndGetText(), GetExpValue(node.ChildNodes[1]), node));

                //Operando binario (+, -, *, /, %, ^, ~, >, <, >=, <=, ==, !=, &&, ||, |&)
                case 3: return(Resolve(GetExpValue(node.ChildNodes[0]), node.ChildNodes[1].FindTokenAndGetText(), GetExpValue(node.ChildNodes[2]), node));
                }
            }
            break;
            }

            return(null);
        }
Exemplo n.º 25
0
        public string declaracionDeClase(ParseTreeNode nodo, List <ParseTreeNode> nodos, int i)
        {
            string salida           = "";
            var    acceso           = nodo.FindTokenAndGetText();
            var    palabraReservada = nodos[i + 3].FindTokenAndGetText();
            var    nombreClase      = nodos[i + 4].FindTokenAndGetText();

            if (this.lexicConfig.reservadas.Contains(nombreClase))
            {
                salida = "El nombre de la clase [" + nombreClase + "] esta usando una palabra reservada \r\n" +
                         getErrorLine(acceso + " " + palabraReservada + " " + nombreClase, "Estas usando como nombre de clase una palabra que pertenece " +
                                      " al lenguaje JAVA. Intenta cambiarla");
            }
            return(salida);
        }
Exemplo n.º 26
0
        public override void Init(Irony.Ast.AstContext context, ParseTreeNode parseNode)
        {
            if (!parseNode.FindTokenAndGetText().StartsWith("$"))
            {
                parseNode.AstNode = new LiteralValueNode();
                ((LiteralValueNode)parseNode.AstNode).Init(context, parseNode);
                return;
            }

            base.Init(context, parseNode);
            template         = parseNode.Token.ValueString;
            tokenText        = parseNode.Token.Text;
            templateSettings = parseNode.Term.AstConfig.Data as StringTemplateSettings;
            ParseSegments(context);
            AsString = "\"" + template + "\" (templated string)";
        }
Exemplo n.º 27
0
        private static UnaryOperator ToUnaryOperator(ParseTreeNode node)
        {
            var text = node.FindTokenAndGetText().ToLower();

            switch (text)
            {
            case "not":
            case "не":
                return(UnaryOperator.Not);

            case "-":
                return(UnaryOperator.Negation);

            default:
                throw new InvalidOperationException(string.Format("unexpected unary operator [{0}]", text));
            }
        }
Exemplo n.º 28
0
        internal static void AddError(ParseTreeNode node, String message)
        {
            Token token = node.FindToken();

            int line = 0;
            int col  = 0;

            if (token != null)
            {
                line = token.Location.Line;
                col  = token.Location.Column;
            }

            message = "[" + node.FindTokenAndGetText() + "] " + message;

            Logs?.Add(new LogMessage(ErrorLevel.Error, new SourceLocation(0, line, col), message, null));
        }
Exemplo n.º 29
0
        // this is where data is initially passed to the item
        public override void Init(AstContext context, ParseTreeNode treeNode)
        {
            string sVal = treeNode.FindTokenAndGetText();

            base.Init(context, treeNode);
            var nodes = treeNode.GetMappedChildNodes();
            property = treeNode;

            if (nodes.Count > 1)
            {
                var child = AddChild("Queue", nodes[1]);
                string sval = nodes[1].FindTokenAndGetText();
                if (child is LeftObjectNode)
                {
                    _queue = (LeftObjectNode)child;
                }
            }
        }
Exemplo n.º 30
0
        private void BuildRuleExpressions(ParseTreeNode node)
        {
            var ruleName = node.FindTokenAndGetText();
            var rule     = rules.ContainsKey(ruleName) ? rules[ruleName] : rules[ruleName] = new AlternationExpression();

            ParseTreeNode elements = null;

            foreach (var child in node.ChildNodes)
            {
                if (child.Term.Name == "elements")
                {
                    elements = child;
                }
            }

            rule.Add(
                BuildAlternationExpression(elements.ChildNodes[0]));
        }
Exemplo n.º 31
0
        public string declaracionDeArreglo(ParseTreeNode nodo, List <ParseTreeNode> nodos, int i)
        {
            string salida              = "";
            var    tipoArreglo         = nodo.FindTokenAndGetText();
            var    corcheteA           = nodos[i + 3].FindTokenAndGetText();
            var    corcheteC           = nodos[i + 4].FindTokenAndGetText();
            var    identificador       = nodos[i + 5].FindTokenAndGetText();
            var    igual               = nodos[i + 6].FindTokenAndGetText();
            var    nuevo               = nodos[i + 7].FindTokenAndGetText();
            var    tipoArregloAsignado = nodos[i + 8].FindTokenAndGetText();
            var    line = tipoArreglo + " " + corcheteA + " " + corcheteC + " " + identificador + " " + igual + " " + nuevo + " " + tipoArregloAsignado;

            if (tipoArreglo != tipoArregloAsignado)
            {
                salida = "El arreglo [" + identificador + "] no puede inicializarse con el tipo [" + tipoArregloAsignado + "] \r\n" +
                         getErrorLine(line, "El arreglo se esta incializando con diferente tipo");
            }
            return(salida);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Compare two parse tree nodes and return true only if the contents of the whole trees match
        /// </summary>
        /// <param name="node1"></param>
        /// <param name="node2"></param>
        /// <returns></returns>
        public static bool IsSameParseTreeNode(this ParseTreeNode node1, ParseTreeNode node2)
        {
            var stack1 = new Stack <ParseTreeNode>();
            var stack2 = new Stack <ParseTreeNode>();

            stack1.Push(node1);
            stack2.Push(node2);

            while (stack1.Count > 0)
            {
                node1 = stack1.Pop();
                node2 = stack2.Pop();

                if (ReferenceEquals(node1, null) || ReferenceEquals(node2, null))
                {
                    return(false);
                }

                if (ReferenceEquals(node1, node2))
                {
                    return(true);
                }

                if (node1.ChildNodes.Count != node2.ChildNodes.Count)
                {
                    return(false);
                }

                if (node1.FindTokenAndGetText() != node2.FindTokenAndGetText())
                {
                    return(false);
                }

                for (var i = 0; i < node1.ChildNodes.Count; i++)
                {
                    stack1.Push(node1.ChildNodes[i]);
                    stack2.Push(node2.ChildNodes[i]);
                }
            }

            return(true);
        }
Exemplo n.º 33
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        private void FlowConditionalStatements(ParseTreeNode node)
        {
            bool first = true;
            int  index = 0;

            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                if (first)
                {
                    _cSharpCode.Add(node.FindTokenAndGetText() + "(");
                    index = _cSharpCode.Count - 1;
                    first = false;
                }
                else
                {
                    foreach (var item in node.ChildNodes[i].ChildNodes)
                    {
                        ChildrenNodesRetrevial(item, ref index);
                    }
                }
            }
        }
Exemplo n.º 34
0
        private static DatePart ToDatePart(ParseTreeNode node)
        {
            var text = node.FindTokenAndGetText().ToLower();

            switch (text)
            {
            case "год":
            case "year":
                return(DatePart.Year);

            case "квартал":
            case "quarter":
                return(DatePart.Quarter);

            case "месяц":
            case "month":
                return(DatePart.Month);

            case "неделя":
            case "week":
                return(DatePart.Week);

            case "день":
            case "day":
                return(DatePart.Day);

            case "час":
            case "hour":
                return(DatePart.Hour);

            case "минута":
            case "minute":
                return(DatePart.Minute);

            default:
                throw new InvalidOperationException("Unexpected date part literal " + node);
            }
        }
Exemplo n.º 35
0
        ConstantExpressionAst BuildDecimalIntegerLiteralAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.decimal_integer_literal);
            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.decimal_integer_literal.Pattern, RegexOptions.IgnoreCase);
            string digits = matches.Groups[this._grammar.decimal_digits.Name].Value;
            string typeSuffix = matches.Groups[this._grammar.numeric_type_suffix.Name].Value;
            string longTypeSuffix = matches.Groups[this._grammar.long_type_suffix.Name].Value;
            string multiplier = matches.Groups[this._grammar.numeric_multiplier.Name].Value;

            // The type of an integer literal is determined by its value, the presence or absence of long-type-suffix, and the
            // presence of a numeric-multiplier (§2.3.5.1.3).

            object value;

            if (typeSuffix == string.Empty)
            {
                // For an integer literal with no long-type-suffix
                // • If its value can be represented by type int (§4.2.3), that is its type;
                // • Otherwise, if its value can be represented by type long (§4.2.3), that is its type.
                if (!ParseIntOrLongLiteral(digits, multiplier, NumberStyles.Integer, out value))
                {
                    decimal decimalValue;
                    double doubleValue;
                    if (decimal.TryParse(digits, out decimalValue))
                        // • Otherwise, if its value can be represented by type decimal (§2.3.5.1.2), that is its type.
                        value = NumericMultiplier.Multiply(decimalValue, multiplier);
                    else if (double.TryParse(digits, out doubleValue))
                        // • Otherwise, it is represented by type double (§2.3.5.1.2).
                        value = NumericMultiplier.Multiply(doubleValue, multiplier);
                    else
                        // For PowerShell compatibility throw an error here instead of saturating the double to infinity.
                        throw new OverflowException(string.Format("The integer literal {0} is too large.", matches.Value));
                }
            }
            else if (longTypeSuffix != string.Empty)
            {
                // For an integer literal with long-type-suffix

                long longValue;

                // • If its value can be represented by type long (§4.2.3), that is its type;
                if (long.TryParse(digits, out longValue))
                    value = NumericMultiplier.Multiply(longValue, multiplier);
                else
                    // • Otherwise, that literal is ill formed.
                    throw new ArithmeticException(string.Format("The integer literal {0} is invalid because it does not fit into a long.", matches.Value));
            }
            else
            {
                // The spec doesn't explicitly mention this case, but it seems to be handled
                // similar to a long suffix.
                decimal decimalValue;

                if (decimal.TryParse(digits, out decimalValue))
                    value = NumericMultiplier.Multiply(decimalValue, multiplier);
                else
                    throw new ArithmeticException(string.Format("The integer literal {0} is invalid because it does not fit into a decimal.", matches.Value));
            }

            return new ConstantExpressionAst(new ScriptExtent(parseTreeNode), value);
        }
Exemplo n.º 36
0
        ConstantExpressionAst BuildHexadecimalIntegerLiteralAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.hexadecimal_integer_literal);

            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.hexadecimal_integer_literal.Pattern, RegexOptions.IgnoreCase);
            string value = matches.Groups[this._grammar.hexadecimal_digits.Name].Value;

            return new ConstantExpressionAst(new ScriptExtent(parseTreeNode), Convert.ToInt32(value, 16));
        }
Exemplo n.º 37
0
        ConstantExpressionAst BuildHexadecimalIntegerLiteralAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.hexadecimal_integer_literal);

            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.hexadecimal_integer_literal.Pattern, RegexOptions.IgnoreCase);
            string digits = matches.Groups[this._grammar.hexadecimal_digits.Name].Value;
            string multiplier = matches.Groups[this._grammar.numeric_multiplier.Name].Value;

            object value;
            // Hex literals can only be int or long.
            if (!ParseIntOrLongLiteral(digits, multiplier, NumberStyles.AllowHexSpecifier, out value))
                throw new OverflowException(string.Format("The integer literal {0} is too large.", matches.Value));

            return new ConstantExpressionAst(new ScriptExtent(parseTreeNode), value);
        }
Exemplo n.º 38
0
 private IExpression BuildCharvalExpression(ParseTreeNode node)
 {
     var charval = node.FindTokenAndGetText();//.Replace("\\", "\\\\");
     charval = charval.Substring(1, charval.Length - 2);
     return new CharvalExpression(this, charval);
 }
Exemplo n.º 39
0
		public string CreateCharval(ParseTreeNode node)
		{
			return "FromString(" + node.FindTokenAndGetText().Replace("\\", "\\\\") + ",rulenames)";
		}
Exemplo n.º 40
0
        StringConstantExpressionAst BuildVerbatimStringLiteralAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.verbatim_string_literal);

            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.verbatim_string_literal.Pattern, RegexOptions.IgnoreCase);
            string value = matches.Groups[this._grammar.verbatim_string_characters.Name].Value;

            return new StringConstantExpressionAst(new ScriptExtent(parseTreeNode), value, StringConstantType.SingleQuoted);
        }
Exemplo n.º 41
0
        ConstantExpressionAst BuildDecimalIntegerLiteralAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.decimal_integer_literal);
            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.decimal_integer_literal.Pattern, RegexOptions.IgnoreCase);
            string digits = matches.Groups[this._grammar.decimal_digits.Name].Value;
            string typeSuffix = matches.Groups[this._grammar.numeric_type_suffix.Name].Value;
            string longTypeSuffix = matches.Groups[this._grammar.long_type_suffix.Name].Value;
            string multiplier = matches.Groups[this._grammar.numeric_multiplier.Name].Value;

            // The type of an integer literal is determined by its value, the presence or absence of long-type-suffix, and the
            // presence of a numeric-multiplier (§2.3.5.1.3).

            object value;

            if (typeSuffix == string.Empty)
            {
                // For an integer literal with no long-type-suffix

                int intValue;
                long longValue;
                decimal decimalValue;
                double doubleValue;

                // Note: TryParse will only ever return false here if the conversion overflows because
                // all other conditions are impossible when the supplied string consists only of digits.
                if (int.TryParse(digits, out intValue))
                    // • If its value can be represented by type int (§4.2.3), that is its type;
                    value = NumericMultiplier.Multiply(intValue, multiplier);
                else if (long.TryParse(digits, out longValue))
                    // • Otherwise, if its value can be represented by type long (§4.2.3), that is its type.
                    value = NumericMultiplier.Multiply(longValue, multiplier);
                else if (decimal.TryParse(digits, out decimalValue))
                    // • Otherwise, if its value can be represented by type decimal (§2.3.5.1.2), that is its type.
                    value = decimalValue;
                else if (double.TryParse(digits, out doubleValue))
                    // • Otherwise, it is represented by type double (§2.3.5.1.2).
                    value = doubleValue;
                else
                    // For PowerShell compatibility throw an error here instead of saturating the double to infinity.
                    throw new OverflowException(string.Format("The integer literal {0} is too large.", matches.Value));
            }
            else if (longTypeSuffix != string.Empty)
            {
                // For an integer literal with long-type-suffix

                long longValue;

                // • If its value can be represented by type long (§4.2.3), that is its type;
                if (long.TryParse(digits, out longValue))
                    value = NumericMultiplier.Multiply(longValue, multiplier);
                else
                    // • Otherwise, that literal is ill formed.
                    throw new ArithmeticException(string.Format("The integer literal {0} is invalid because it does not fit into a long.", matches.Value));
            }
            else
            {
                throw new NotImplementedException("Decimal type suffix not yet implemented");
            }

            return new ConstantExpressionAst(new ScriptExtent(parseTreeNode), value);
        }
Exemplo n.º 42
0
        ConstantExpressionAst BuildHexadecimalIntegerLiteralAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.hexadecimal_integer_literal);

            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.hexadecimal_integer_literal.Pattern, RegexOptions.IgnoreCase);
            string digits = matches.Groups[this._grammar.hexadecimal_digits.Name].Value;
            string multiplier = matches.Groups[this._grammar.numeric_multiplier.Name].Value;

            object value = NumericMultiplier.Multiply(Convert.ToInt32(digits, 16), multiplier);
            return new ConstantExpressionAst(new ScriptExtent(parseTreeNode), value);
        }
Exemplo n.º 43
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 private void FlowConditionalStatements(ParseTreeNode node)
 {
     bool first = true;
     int index = 0;
     for (int i = 0; i < node.ChildNodes.Count; i++)
     {
         if (first)
         {
             _cSharpCode.Add(node.FindTokenAndGetText() + "(");
             index = _cSharpCode.Count - 1;
             first = false;
         }
         else
         {
             foreach (var item in node.ChildNodes[i].ChildNodes)
             {
                 ChildrenNodesRetrevial(item, ref index);
             }
         }
     }
 }
Exemplo n.º 44
0
		public string CreateNfaRulePart(ParseTreeNode node)
		{
			ParseTreeNode elements = null;
			foreach (var child in node.ChildNodes)
				if (child.Term.Name == "elements")
					elements = child;

			var nodeName = node.FindTokenAndGetText();
			int number = 0;
			if (_partNumber.ContainsKey(nodeName))
				number = _partNumber[nodeName] + 1;
			_partNumber[nodeName] = number;

			return "\t\tpublic State Get" + node.FindTokenAndGetText().Replace('-', '_') + number + "(List<string> rulenames)\r\n" +
				"\t\t{\r\n" +
				"\t\t\tState rule = " + CreateAlternation(elements.ChildNodes[0], true) + ";\r\n" +
				"\t\t\treturn rule;\r\n" +
				"\t\t}\r\n";
		}
Exemplo n.º 45
0
        private ConstantExpressionAst BuildDoubleRealLiteralAst(ParseTreeNode parseTreeNode, Group multiplier)
        {
            string digits = parseTreeNode.FindTokenAndGetText();

            if (multiplier.Success)
            {
                digits = RemoveMatchedString(digits, multiplier);
            }

            double value;
            if (!double.TryParse(digits, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value))
            {
                throw new OverflowException(string.Format("The real literal {0} is too large.", digits));
            }

            if (multiplier.Success)
            {
                value *= NumericMultiplier.GetValue(multiplier.Value);
            }

            return new ConstantExpressionAst(new ScriptExtent(parseTreeNode), value);
        }
Exemplo n.º 46
0
 // Build a variable reference (the "v" in "v = 1"
 void BuildVariableReference(IronyParser parser, Root root, Expression parentExpression, ParseTreeNode currentNode)
 {
     var e = new VariableReference(parentExpression, currentNode.FindToken().Convert());
     e.Name = currentNode.FindTokenAndGetText();
     e.ParentExpression = parentExpression;
     parentExpression.ChildExpressions.Add(e);
 }
Exemplo n.º 47
0
        private static string GetParseTreeNodeText(ParseTreeNode parseTreeNode)
        {
            if (parseTreeNode == null)
            {
                return string.Empty;
            }

            // We cannot use FindTokenAndGetText always because it will give us only the text of the root node in
            // case of complex expressions. So we have to do that:
            if (parseTreeNode.ChildNodes.Count > 0)
            {
                var result = new StringBuilder();
                foreach (var node in parseTreeNode.ChildNodes)
                {
                    int offset = node.Span.Location.Position - parseTreeNode.Span.Location.Position;
                    if (result.Length < offset)
                    {
                        result.Append(' ', offset - result.Length);
                    }

                    result.Append(GetParseTreeNodeText(node));
                }

                return result.ToString();
            }

            return parseTreeNode.FindTokenAndGetText() ?? string.Empty;
        }
Exemplo n.º 48
0
 public override void Init(AstContext context, ParseTreeNode parseNode)
 {
     Operator = parseNode.FindTokenAndGetText();
 }
            public string Translate(ParseTreeNode node)
            {
                string res = null;
                switch (Type)
                {
                    case Types.AsIs:
                        res = Convert.ToString(node.FindTokenAndGetText());
                        break;
                    case Types.AsIsTitleCase:
                        res = ToTitleCase(Convert.ToString(node.FindTokenAndGetText()));
                        break;
                    case Types.ConstantReplacement:
                        res = ConstantReplacement;
                        break;
                    case Types.DictionaryReplacement:
                        string replacement;
                        ReplacementDict.TryGetValue(node.FindTokenAndGetText(),out replacement);
                        res = replacement;
                        break;
                    case Types.CustomFunction:
                        res = Convert.ToString(TranslateFunction.Invoke(node));
                        break;
                }

                if (res == null) return res;
                //add space if necessary
                var terminal = node.Term as Terminal;
                if (terminal == null) return res;
                if (terminal.SkipsWhitespaceAfter)res += " ";

                return res;
            }
        private object ProcessNode(ParseTreeNode node, string fxName)
        {
            object result = null;

            switch (node.Term.Name)
            {
                case "function_expression":
                    fxName = node.ChildNodes[0].FindTokenAndGetText().TrimStart('@');
                    var fxParams = (List<object>)ProcessNode(node.ChildNodes[1], fxName);
                    var args = new TextFunctionPipelineArgs()
                    {
                        FunctionName = fxName,
                        Args = fxParams.ToArray(),
                        CustomFunctionHandlers = _fxCustomHandlers
                    };
                    if (_fxHandlerLookup.ContainsKey(fxName))
                    {
                        var fx = _fxHandlerLookup[fxName];
                        fx.ProcessFunction(args);
                    }
                    else
                    {
                        // Send to the ProcessTextFunction pipeline....
                        CorePipeline.Run("ProcessTextFunction", args);

                        // Save reference to the handling processor...
                        if (args.FunctionHandled && args.HandledBy != null)
                            _fxHandlerLookup.Add(fxName, args.HandledBy);
                    }
                    if (args.FunctionHandled)
                        result = args.Result;
                    else
                        result = "'@" + fxName + "' function is not recognized.";
                    break;

                case "argument_list_par":
                case "argument_list_opt":
                    if (node.ChildNodes.Count == 0)
                        return new List<object>();
                    else
                        result = ProcessNode(node.FirstChild, fxName);
                    break;

                case "argument_list":
                    var parameters = new List<object>();
                    foreach (var p in node.ChildNodes)
                    {
                        var pValue = ProcessNode(p, fxName);
                        if (pValue != null)
                            parameters.Add(pValue);
                    }
                    result = parameters;
                    break;

                case "bin_op_expression":
                    var b_operand1 = ProcessNode(node.ChildNodes[0], fxName);
                    var b_operand2 = ProcessNode(node.ChildNodes[2], fxName);
                    var b_op = node.ChildNodes[1].FindTokenAndGetText();
                    result = EvaluateOperation(b_operand1, b_op, b_operand2);
                    break;

                case "parenthesized_expression":
                    result = ProcessNode(node.ChildNodes[0], fxName);
                    break;

                case "unary_expression":
                    var u_op = node.FindTokenAndGetText();
                    var u_operand = ProcessNode(node.ChildNodes[1], fxName);
                    result = EvaluateUnaryOperation(u_op, u_operand);
                    break;

                case "StringLiteral":
                    // Remove the surrounding quotes (")
                    var s = node.FindTokenAndGetText();
                    s = ResolveExpressionVariables(s); // resolve embedded field variables
                    result = s.Length > 2 ? s.Substring(1, s.Length - 2) : string.Empty;
                    break;

                case "guid_variable":
                    result = _variables[node.FindTokenAndGetText()];
                    break;

                case "Number":
                    var n = node.FindTokenAndGetText();
                    if (n.Contains("."))
                        result = decimal.Parse(n);
                    else
                        result = int.Parse(n);
                    break;

                case "true":
                case "True":
                    result = true;
                    break;
                case "false":
                case "False":
                    result = false;
                    break;
                case "null":
                    result = null;
                    break;
                default:
                    throw new Exception(string.Format("Unhandled argument type: [{0}][{1}]", node.Term.Name, node.FindTokenAndGetText()));
            }

            return result;
        }
Exemplo n.º 51
0
        ConstantExpressionAst BuildRealLiteralAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.real_literal);
            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.real_literal.Pattern, RegexOptions.IgnoreCase);
            Group multiplier = matches.Groups[this._grammar.numeric_multiplier.Name];
            Group decimalTypeSuffix = matches.Groups[this._grammar.decimal_type_suffix.Name];

            if (decimalTypeSuffix.Success)
            {
                return BuildDecimalRealLiteralAst(parseTreeNode, multiplier, decimalTypeSuffix);
            }

            return BuildDoubleRealLiteralAst(parseTreeNode, multiplier);
        }
Exemplo n.º 52
0
 public override void Init(AstContext context, ParseTreeNode parseNode)
 {
     Value = Php54Utils.StringToInteger(parseNode.FindTokenAndGetText());
 }
Exemplo n.º 53
0
        TokenKind SelectTokenKind(ParseTreeNode parseTreeNode)
        {
            if (!(parseTreeNode.Term is Terminal)) throw new InvalidOperationException(parseTreeNode.ToString());

            var text = parseTreeNode.FindTokenAndGetText();

            switch (text)
            {
                case "=":
                    return TokenKind.Equals;

                case "+=":
                    return TokenKind.PlusEquals;

                case "-=":
                    return TokenKind.MinusEquals;

                case "*=":
                    return TokenKind.MultiplyEquals;

                case "/=":
                    return TokenKind.DivideEquals;

                case "%=":
                    return TokenKind.RemainderEquals;

                default:
                    throw new NotImplementedException(parseTreeNode.ToString());
            }
        }
Exemplo n.º 54
0
		public static string GetMessage(ParseTreeNode node, string message)
		{
			return string.Format(@"ParseTreeNode: {0}, Error: {1}", node.FindTokenAndGetText(), message);
		}
Exemplo n.º 55
0
        private ConstantExpressionAst BuildDecimalRealLiteralAst(ParseTreeNode parseTreeNode, Group multiplier, Group decimalTypeSuffix)
        {
            string digits = parseTreeNode.FindTokenAndGetText();

            if (multiplier.Success)
            {
                digits = RemoveMatchedString(digits, multiplier);
            }

            digits = RemoveMatchedString(digits, decimalTypeSuffix);

            decimal value;
            if (!decimal.TryParse(digits, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value))
            {
                throw new OverflowException(string.Format("Bad numeric constant: {0}.", parseTreeNode.FindTokenAndGetText()));
            }

            if (multiplier.Success)
            {
                value *= NumericMultiplier.GetValue(multiplier.Value);
            }

            return new ConstantExpressionAst(new ScriptExtent(parseTreeNode), value);
        }
Exemplo n.º 56
0
        public void CreateUsedRulesList(ParseTreeNode node, List<string> rulenames)
        {
            foreach (var child in node.ChildNodes)
                CreateUsedRulesList(child, rulenames);

            if (node.Term.Name == "rulename")
            {
                var rulename = node.FindTokenAndGetText();

                if (rulenames.Find((fromList) => { return fromList == rulename; }) == null)
                    rulenames.Add(node.FindTokenAndGetText());
            }
        }
Exemplo n.º 57
0
        ExpressionAst BuildExpandableStringLiteralAst(ParseTreeNode parseTreeNode)
        {
            var matches = Regex.Match(parseTreeNode.FindTokenAndGetText(), this._grammar.expandable_string_literal.Pattern, RegexOptions.IgnoreCase);
            string value = matches.Groups[this._grammar.expandable_string_characters.Name].Value +
                matches.Groups[this._grammar.dollars.Name].Value
                ;

            var ast = new ExpandableStringExpressionAst(new ScriptExtent(parseTreeNode), value, StringConstantType.DoubleQuoted);
            if (ast.NestedExpressions.Any())
            {
                return ast;
            }
            return new StringConstantExpressionAst(new ScriptExtent(parseTreeNode), value, StringConstantType.DoubleQuoted);
        }
Exemplo n.º 58
0
 public override void Init(AstContext context, ParseTreeNode parseNode)
 {
     var StringWithQuotes = parseNode.FindTokenAndGetText();
     UnquotedString = Php54Utils.FullStringUnquote(StringWithQuotes);
     Interpolate = (StringWithQuotes[0] == '"');
 }
Exemplo n.º 59
0
 private static T FindTokenAndGetValue <T>(this ParseTreeNode node)
 {
     try { return(node.FindToken().ValueString.As <T>()); }
     catch { throw node.GetException($"Invalid token '{node.FindTokenAndGetText()}'. Expected a token of type {typeof(T)}"); }
 }
Exemplo n.º 60
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="node"></param>
 /// <param name="index"></param>
 /// 
 private void ChildrenNodesRetrevial(ParseTreeNode node, ref int index)
 {
     if (node.ChildNodes.Count > 0)
     {
         foreach (var item in node.ChildNodes)
         {
             ChildrenNodesRetrevial(item, ref index);
         }
     }
     else if (node.FindTokenAndGetText() != null)
     {
         _cSharpCode[index] = _cSharpCode[index] + node.FindTokenAndGetText() + " ";
     }
 }