Пример #1
0
 protected override void ConvertStart()
 {
     _inList.Clear();
     _listDepth  = 0;
     _inTable    = false;
     CurrentLink = null;
 }
Пример #2
0
        /// <summary>
        /// Extracts the style="" attribute from the element
        /// and properly formats the style for some element.
        /// Removes any properties that are not 'on the list'
        /// including any properties that use IE's expression.
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private string GetStyleStr(ParserNode node)
        {
            string style = node.Attributes["style"];
            string ret   = "";

            if (style != null)
            {
                System.Collections.Generic.List <string> str = new System.Collections.Generic.List <string>();
                string[] split = style.Trim().Split(new char[1] {
                    ';'
                });
                foreach (string s in split)
                {
                    string trimmed = s.Trim();
                    if (trimmed.Length > 0)
                    {
                        string[] elem = trimmed.Split(':');
                        if (elem.Length == 2)
                        {
                            elem[0] = elem[0].Trim().ToLower();
                            elem[1] = elem[1].Trim();
                            if (!elem[1].ToLower().Contains("expression") && STYLE_WHITELIST.Contains(elem[0]))
                            {
                                str.Add(elem[0] + ": " + elem[1]);
                            }
                        }
                    }
                }

                ret = "{" + string.Join(";", str.ToArray()) + "}";
            }
            return(ret);
        }
Пример #3
0
 CSharpVisitor(string input)
 {
     this.input      = input;
     stack.Push(Root = new ParserNode {
         Type = "Root", Start = 0, End = input.Length
     });
 }
Пример #4
0
        protected ParserNode HandleLevel_TagSpecial_For()
        {
            Tokens.MoveNext();

            String VarName = CurrentToken.Text;

            Tokens.MoveNext();
            Tokens.ExpectValueAndNext("in");
            ParserNode LoopIterator = HandleLevel_Expression();

            Tokens.ExpectValueAndNext("%}");

            ParserNode ElseBlock = new DummyParserNode();
            ParserNode BodyBlock = HandleLevel_Root();

            if (Tokens.Current.Text == "else")
            {
                Tokens.MoveNext();
                Tokens.ExpectValueAndNext("%}");
                ElseBlock = HandleLevel_Root();
            }

            Tokens.ExpectValueAndNext("endfor");
            Tokens.ExpectValueAndNext("%}");

            return(new ForeachParserNode()
            {
                LoopIterator = LoopIterator,
                VarName = VarName,
                BodyBlock = BodyBlock,
                ElseBlock = ElseBlock,
            });
        }
Пример #5
0
    // Use this for initialization
	public void Start(string text) {
	    localText = text;
        StripExtraCharacter(ref localText);
        StripComments(ref localText);
        localIndex = 0;
        braceStart = 0;
        braceEnd = 0;
        error = false;
        errorText = "";
        starting = true;

        ReadWord(null);
        localText = "";

        if (debug) DebugNode(root);
        if (braceStart == braceEnd) {
            OnAttributes(root);
        }
        else {
            if (!error) {
                errorText = "Parse ERROR!! : braces count fail.";
                error = true;
            }
        }


        if (error) {
            Debug.Log(errorText);
        }
        root = null;
    }
Пример #6
0
        public override object Calculate(Context context, ParserNode parentNode)
        {
            object left = LeftChildExpression.Calculate(context, this);
            object right = RightChildExpression.Calculate(context, this);

            if (left == null && right == null)
                return "";

            if (left == null && right.GetType() == typeof(string))
                return right;

            if (right == null && left.GetType() == typeof(string))
                return left;

            left = left ?? "";
            right = right ?? "";

            if (left.GetType() == typeof(string) || right.GetType() == typeof(string))
                return left.ToString() + right.ToString();

            if (left.IsNumeric() && right.IsNumeric())
            {
                if (left.GetType() == typeof(int) && right.GetType() == typeof(int))
                    return (int)left + (int)right;
                else
                    return Decimal.Add((decimal)left, (decimal)right);
            }

            return left.ToString() + right.ToString();
        }
 public static void DoPush(this Stack<ParserNode> i, ParserNode s)
 {
     if (s != null)
     {
         i.Push(s);
     }
 }
		public ParserNodeTernaryOperation(ParserNode ConditionNode, ParserNode TrueNode, ParserNode FalseNode, String Operator)
		{
			this.ConditionNode = ConditionNode;
			this.TrueNode = TrueNode;
			this.FalseNode = FalseNode;
			this.Operator = Operator;
		}
Пример #9
0
        protected ParserNode _HandleLevel_OpBase(Func <ParserNode> HandleLevelNext, string[] Operators, Func <ParserNode, String, ParserNode> HandleOperator)
        {
            ParserNode ParserNode = HandleLevelNext();

            while (Tokens.HasMore)
            {
                switch (CurrentTokenType)
                {
                case "OperatorTemplateToken":
                    string Operator = CurrentToken.Text;
                    bool   Found    = false;
                    foreach (var CurrentOperator in Operators)
                    {
                        if (Operator == CurrentOperator)
                        {
                            ParserNode = HandleOperator(ParserNode, Operator);
                            Found      = true;
                            break;
                        }
                    }
                    if (!Found)
                    {
                        return(ParserNode);
                    }
                    break;

                default:
                    return(ParserNode);
                }
            }

            return(ParserNode);
        }
Пример #10
0
 private ParserNode CreateNode(ParserContext context)
 {
     var node = new ParserNode(context, Reduction.Product);
     node.Children.AddRange(PopChildren(context).Reverse());
     node.EnsureResultComputed();
     return node;
 }
Пример #11
0
        public bool Reduce()
        {
            bool reduced = false;

            for (int i = 0; i < _grammar.Productions.Count && !reduced; i++)
            {
                var production = _grammar.Productions[i];
                var lookahead = tokenizer.LookAhead();

                // hack for numbers now
                int t;
                if (production.Variable.Compare.Equals("NUMBER") && int.TryParse(_internalStack.Peek().Compare, out t))
                {
                    _internalStack.DoPush(production.Variable.ToNode(new[] { _internalStack.Pop() }));
                    reduced = true;
                }
                // end hack

                if (production.Matcher.TryMatch(lookahead, _internalStack))
                {
                    var tArray = new ParserNode[production.Matcher.Symbols.Count];
                    for (int j = 0; j < production.Matcher.Symbols.Count; j++)
                    {
                        tArray[j] = _internalStack.Pop();
                    }
                    _internalStack.DoPush(production.Variable.ToNode(tArray));
                    reduced = true;
                }
            }
            return reduced;
        }
Пример #12
0
        private void HandleQuickTags(ParserNode node, bool isStart)
        {
            switch (node.Name)
            {
            case "i":
            case "em":
                AddQuickTag(node, "_", isStart);
                break;

            case "b":
            case "strong":
                AddQuickTag(node, "*", isStart);
                break;

            case "s":
            case "del":
            case "strike":
                AddQuickTag(node, "-", isStart);
                break;

            case "sub":
                AddQuickTag(node, "~", isStart);
                break;

            case "sup":
                AddQuickTag(node, "^", isStart);
                break;

            case "cite":
                AddQuickTag(node, "??", isStart);
                break;

            case "span":
                AddQuickTag(node, "%", isStart);
                break;

            case "code":
                ParserNode cnode;
                if (isStart)
                {
                    cnode = node.PrevNode;
                    //if the previous node is a pre tag, then we dont do the code quick tag.
                    if (!(cnode != null && cnode.NodeType == System.Xml.XmlNodeType.Element && cnode.Name == "pre"))
                    {
                        AddQuickTag(node, "@", isStart);
                    }
                }
                else
                {
                    cnode = node.NextNode;
                    //if the previous node is a pre tag, then we dont do the code quick tag.
                    if (!(cnode != null && cnode.NodeType == System.Xml.XmlNodeType.EndElement && cnode.Name == "pre"))
                    {
                        AddQuickTag(node, "@", isStart);
                    }
                }
                break;
            }
        }
Пример #13
0
 protected ParserNode _HandleLevel_Op(Func <ParserNode> HandleLevelNext, string[] Operators, Func <ParserNode, ParserNode, String, ParserNode> HandleOperator)
 {
     return(_HandleLevel_OpBase(HandleLevelNext, Operators, delegate(ParserNode ParserNode, String Operator) {
         Tokens.MoveNext();
         ParserNode RightNode = HandleLevelNext();
         return HandleOperator(ParserNode, RightNode, Operator);
     }));
 }
Пример #14
0
        private string GetStyleOrClassStr(ParserNode node)
        {
            string ret = GetClassStr(node);

            if (ret.Length < 1)
            {
                ret = GetStyleStr(node);
            }
            return(ret);
        }
 /// <summary>
 /// Adds the node to the previous's linked list, then puts the node in the node list.
 /// </summary>
 /// <param name="node"></param>
 private void AddNode(ParserNode node)
 {
     if (Nodes.Count > 0)
     {
         ParserNode prev = Nodes[Nodes.Count - 1];
         prev.NextNode = node;
         node.PrevNode = prev;
     }
     Nodes.Add(node);
 }
Пример #16
0
        private string GetClassStr(ParserNode node)
        {
            string cl  = node.Attributes["class"];
            string ret = "";

            if (cl != null)
            {
                ret = string.Format("({0})", cl);
            }
            return(ret);
        }
Пример #17
0
 public ParserNode HandleLevel_Ternary()
 {
     return(_HandleLevel_Op(
                HandleLevel_Filter,
                new string[] { "?" },
                (ParserNode ConditionNode, ParserNode TrueNode, String Operator) => {
         Tokens.ExpectValueAndNext(":");
         ParserNode FalseNode = HandleLevel_Sum();
         return new ParserNodeTernaryOperation(ConditionNode, TrueNode, FalseNode, Operator);
     }
                ));
 }
Пример #18
0
        public ParserNode HandleLevel_Root()
        {
            var ParserNodeContainer = new ParserNodeContainer();

            try
            {
                while (Tokens.HasMore)
                {
                    //Console.WriteLine(CurrentToken);
                    switch (CurrentTokenType)
                    {
                    case "RawTemplateToken":
                        ParserNodeContainer.Add(new ParserNodeLiteral()
                        {
                            Text = ((RawTemplateToken)CurrentToken).Text,
                        });
                        Tokens.MoveNext();
                        break;

                    case "OpenTagTemplateToken":
                        string OpenType = CurrentToken.Text;

                        Tokens.MoveNext();

                        switch (OpenType)
                        {
                        case "{{":
                            ParserNodeContainer.Add(new ParserNodeOutputExpression()
                            {
                                Parent = HandleLevel_Tag()
                            });
                            Tokens.ExpectValueAndNext("}}");
                            break;

                        case "{%": {
                            ParserNode ParserNode = HandleLevel_TagSpecial();
                            ParserNodeContainer.Add(ParserNode);
                            //ParserNode.Dump();
                        } break;
                        }
                        break;

                    default:
                        throw (new Exception(String.Format("Unprocessed Token Type '{0}'('{1}')", CurrentTokenType, CurrentToken.Text)));
                    }
                }
            }
            catch (Finalize_HandlingLevel_Root)
            {
            }

            return(ParserNodeContainer);
        }
Пример #19
0
        static public string Reformat(ParserNode node, string input, ParserType parserType)
        {
            switch (parserType)
            {
            case ParserType.HTML: return(HTMLVisitor.Format(node, input));

            case ParserType.JSON: return(JSONVisitor.Format(node, input));

            case ParserType.XML: return(XMLVisitor.Format(node, input));

            default: throw new Exception("Unable to reformat this type");
            }
        }
Пример #20
0
 private void AddQuickTag(ParserNode node, string repl, bool isStart)
 {
     if (isStart)
     {
         AddOutput(" ");
         AddOutput(repl);
         AddOutput(GetStyleStr(node));
     }
     else
     {
         AddOutput(repl + " ");
     }
 }
Пример #21
0
        private void AddBlockTag(ParserNode node, string tag, bool isStart)
        {
            _exitExtendedBlock = false;

            if (isStart)
            {
                AddOutput(tag + GetStyleOrClassStr(node) + ". ", 2, true);
            }
            else
            {
                AddOutput("", 2, false);
            }
        }
Пример #22
0
        protected override void HandleText(ParserNode node)
        {
            //special case: if extended block ends and just text is the next element,
            //we will use a paragraph tag.
            if (_exitExtendedBlock)
            {
                AddOutput("p. ", 2, true);
                _exitExtendedBlock = false;
            }

            string output = node.Value;

            AddOutput(output.Trim());
        }
Пример #23
0
        protected ParserNode HandleLevel_TagSpecial_Autoescape()
        {
            Tokens.MoveNext();

            ParserNode AutoEscapeExpression = HandleLevel_Expression();

            Tokens.ExpectValueAndNext("%}");

            ParserNode BodyBlock = HandleLevel_Root();

            Tokens.ExpectValueAndNext("endautoescape");
            Tokens.ExpectValueAndNext("%}");

            return(new ParserNodeAutoescape(AutoEscapeExpression, BodyBlock));
        }
        private void HandleElementStart(Sgml.SgmlReader reader)
        {
            //ghetto, but the SgmlReader has no way to get ALL attributes.
            ParserNode node = new ParserNode(reader.Name, System.Xml.XmlNodeType.Element);

            node.AddAttribute("style", reader.GetAttribute("style"));
            node.AddAttribute("title", reader.GetAttribute("title"));
            node.AddAttribute("class", reader.GetAttribute("class"));
            node.AddAttribute("href", reader.GetAttribute("href"));
            node.AddAttribute("src", reader.GetAttribute("src"));
            node.AddAttribute("colspan", reader.GetAttribute("colspan"));
            node.AddAttribute("rowspan", reader.GetAttribute("rowspan"));

            AddNode(node);
        }
Пример #25
0
        ParserNode AddNode(ParserRuleContext context, Dictionary <string, object> attributes)
        {
            var node = new ParserNode {
                Parent = Parent, LocationParserRule = context
            };

            foreach (var pair in attributes)
            {
                if (pair.Value == null)
                {
                }
                else if (pair.Value is string)
                {
                    node.AddAttr(pair.Key, pair.Value as string);
                }
                else if (pair.Value is IToken)
                {
                    node.AddAttr(pair.Key, input, pair.Value as IToken);
                }
                else if (pair.Value is ITerminalNode)
                {
                    node.AddAttr(pair.Key, input, pair.Value as ITerminalNode);
                }
                else if (pair.Value is ParserRuleContext)
                {
                    node.AddAttr(pair.Key, input, pair.Value as ParserRuleContext);
                }
                else if (pair.Value is IEnumerable <ParserRuleContext> )
                {
                    foreach (var value in pair.Value as IEnumerable <ParserRuleContext> )
                    {
                        node.AddAttr(pair.Key, input, value as ParserRuleContext);
                    }
                }
                else
                {
                    throw new Exception($"Unknown attribute: {pair.Key}");
                }
            }

            stack.Push(node);
            VisitChildren(context);
            stack.Pop();
            return(node);
        }
Пример #26
0
        public ParserNode HandleLevel_TagSpecial_If()
        {
            bool Alive = true;

            Tokens.MoveNext();

            ParserNode ConditionNode = HandleLevel_Expression();

            Tokens.ExpectValueAndNext("%}");

            ParserNode BodyIfNode   = HandleLevel_Root();
            ParserNode BodyElseNode = new DummyParserNode();

            while (Alive)
            {
                switch (CurrentToken.Text)
                {
                case "endif":
                    Tokens.MoveNext();
                    Tokens.ExpectValueAndNext("%}");
                    Alive = false;
                    break;

                case "else":
                    Tokens.MoveNext();
                    Tokens.ExpectValueAndNext("%}");

                    BodyElseNode = HandleLevel_Root();

                    break;

                default:
                    throw (new Exception(String.Format("Unprocessed Token Type '{0}'", CurrentTokenType)));
                }
            }

            return(new ParserNodeIf()
            {
                ConditionNode = ConditionNode,
                BodyIfNode = BodyIfNode,
                BodyElseNode = BodyElseNode,
            });
        }
        List <ParserNode> GetSelectionNodes()
        {
            var nodes         = RootNode().GetAllNodes();
            var fullLocation  = new Dictionary <int, Dictionary <int, ParserNode> >();
            var startLocation = new Dictionary <int, ParserNode>();

            foreach (var node in nodes)
            {
                if (!fullLocation.ContainsKey(node.Start))
                {
                    fullLocation[node.Start] = new Dictionary <int, ParserNode>();
                }
                fullLocation[node.Start][node.End] = node;

                startLocation[node.Start] = node;
            }

            var result = new List <ParserNode>();

            foreach (var range in Selections)
            {
                ParserNode found = null;
                if ((fullLocation.ContainsKey(range.Start)) && (fullLocation[range.Start].ContainsKey(range.End)))
                {
                    found = fullLocation[range.Start][range.End];
                }
                else if (startLocation.ContainsKey(range.Cursor))
                {
                    found = startLocation[range.Cursor];
                }
                else
                {
                    found = nodes.Where(node => (range.Start >= node.Start) && (range.End <= node.End)).OrderBy(node => node.Depth).LastOrDefault();
                }
                if (found == null)
                {
                    throw new Exception("No node found");
                }
                result.Add(found);
            }
            return(result);
        }
Пример #28
0
        static void Main(string[] args)
        {
            string contents = null;

            //Obtaining paths from the user --------------------------------------------------
            Console.WriteLine("Please enter the folder path to the files you wish to parse:");
            var parserFiles = @"" + Console.ReadLine();

            Console.WriteLine("Please enter the folder path to the template files that are to be used for generation:");
            var TemplateIn = @"" + Console.ReadLine();

            Console.WriteLine("Please enter the folder path to the insertion points that are to be used for generation:");
            var InterfaceIn = @"" + Console.ReadLine();

            Console.WriteLine("If you wish to configure the testbench please enter the path to the configuration file:");
            var configTB = @"" + Console.ReadLine();

            Console.WriteLine("Please enter the path of the desired output: ");
            var TemplateOut = @"" + Console.ReadLine();

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

            //Merging files to be parsed before initiating the parser.
            foreach (string file in Directory.EnumerateFiles(parserFiles, "*.vhd"))
            {
                contents += File.ReadAllText(file);
                Console.WriteLine("Added file: " + file);
                contents += " EndOfFileIdentifier ";
            }
            StringReader lSource = new StringReader(contents);
            Parser       lParser = new Parser(lSource);
            ParserNode   lClause = lParser.ParseNextNode();

            while (lClause != null)
            {
                lClause = lParser.ParseNextNode();
            }
            Generator lGenerator = new Generator(lParser, TemplateIn, TemplateOut, InterfaceIn, configTB);


            Console.WriteLine("Testbench files have been successfully generated.");
        }
Пример #29
0
		protected ParserNode HandleLevel_TagSpecial_Block()
		{
			Tokens.MoveNext();

			String BlockName = CurrentToken.Text;
			Tokens.MoveNext();
			Tokens.ExpectValueAndNext("%}");

			ParserNode BodyBlock = InsideABlock(BlockName, delegate()
			{
				return HandleLevel_Root();
			});

			Tokens.ExpectValueAndNext("endblock");
			Tokens.ExpectValueAndNext("%}");

			Blocks[BlockName] = BodyBlock;

			return new ParserNodeCallBlock(BlockName);
		}
        public bool TryMatch(string lookahead, Stack<ParserNode> nodes)
        {
            var sArray = Symbols.ToArray().Reverse().ToArray();
            bool result = false;
            if (nodes.Count() >= Symbols.Count)
            {
                // set to true until something fails
                result = true;
                var tArray = new ParserNode[Symbols.Count];
                for (int i = 0; i < Symbols.Count; i++)
                {
                    tArray[i] = nodes.Pop();

                    if (!sArray[i].Equals(tArray[i]))
                    {
                        result = false;
                    }
                }

                // at this point, we match, but we havent checked ahead yet
                if (result && Lookahead != null)
                {
                    var doesLookaheadMatch = Lookahead.Equals(lookahead);
                    result = doesLookaheadMatch == LookaheadBool;
                }

                //if (!result)
                //{
                    tArray = tArray.Reverse().ToArray();
                    foreach (var n in tArray)
                    {
                        nodes.Push(n);
                    }
                //}
                //else
                //{

                //}
            }
            return result;
        }
Пример #31
0
        public string HTML2Markup(string html)
        {
            _lastNewLines = 0;
            _currentNode  = null;

            //replace &nbsp; type junk with their actual chars or textile representations of them.
            html = ProcessGlyphs(html);

            //add a div as the root node or the SGML lib only will process the first element!
            html = string.Format("<div>{0}</div>", html);

            System.IO.StringReader rdr = new System.IO.StringReader(html);

            _output = new System.Text.StringBuilder();

            _sgmlReader.InputStream = rdr;

            MemorySgmlReader memRdr = new MemorySgmlReader(_sgmlReader);

            foreach (ParserNode n in memRdr.Nodes)
            {
                _currentNode = n;
                switch (n.NodeType)
                {
                case System.Xml.XmlNodeType.Element:
                    HandleElementStart(n);
                    break;

                case System.Xml.XmlNodeType.EndElement:
                    HandleElementEnd(n);
                    break;

                case System.Xml.XmlNodeType.Text:
                    HandleText(n);
                    break;
                }
            }

            return(_output.ToString());
        }
Пример #32
0
 protected virtual void HandleText(ParserNode node)
 {
 }
Пример #33
0
 void DebugNode(ParserNode node) {
     string str = node.name;
     for (int i = 0; i < node.pairs.Count; i++) {
         str += " " + node.pairs[i].name + " = " + node.pairs[i].value;
     }
     Debug.Log(str);
     for (int i = 0; i < node.sons.Count; i++) {
         DebugNode(node.sons[i]);
     }
 }
Пример #34
0
 public ParseResult(ParserNode root, IList<SyntaxError> errors)
 {
     Root = root;
     SyntaxErrors = new ReadOnlyCollection<SyntaxError>(errors);
 }
Пример #35
0
 public override object Calculate(Context context, ParserNode parentNode)
 {
     object res = context.GetVariableValue(fVar.Name);
     context.SetVariableValue(fVar.Name, new Addition(Var, new IntegerConstant(Amount)).Calculate(context, this));
     return res;
 }
Пример #36
0
 public override object Calculate(Context context, ParserNode parentNode)
 {
     object val = ChildExpression.Calculate(context, this);
     if (val == null)
         throw new Exception("null cannot be the operand of a bitwise complement (~)");
     if (val.GetType() == typeof(int))
         return ~((int)val);
     if (val.GetType() == typeof(uint))
         return ~((uint)val);
     if (val.GetType() == typeof(long))
         return ~((long)val);
     if (val.GetType() == typeof(ulong))
         return ~((ulong)val);
     throw new Exception(val + " cannot be the operand of a bitwise complement (~)");
 }
Пример #37
0
        public override object Calculate(Context context, ParserNode parentNode)
        {
            object left = LeftChildExpression.Calculate(context, this);
            object right = RightChildExpression.Calculate(context, this);

            left = left ?? Decimal.Zero;
            right = right ?? Decimal.One;

            if (!left.IsNumeric())
            {
                decimal res = decimal.Zero;
                Decimal.TryParse(left.ToString(), out res);
                left = res;
            }

            if (!right.IsNumeric())
            {
                decimal res = decimal.Zero;
                Decimal.TryParse(right.ToString(), out res);
                right = res;
            }

            return Decimal.Divide(Convert.ToDecimal(left), Convert.ToDecimal(right));
        }
Пример #38
0
        public override object Calculate(Context context, ParserNode parentNode)
        {
            if (Name == "write" || Name == "print" || Name == "echo")
            {
                if (fArguments.Length > 1 && fArguments[0] is StringConstant)
                {
                    string s = fArguments[0].Calculate(context, this).ToString();
                    object[] objParams = new object[fArguments.Length-1];
                    for(int i=1; i<fArguments.Length; i++)
                        objParams[i - 1] = fArguments[i].Calculate(context, this).ToString();
                    context.Output.Write(String.Format(s, objParams));
                }
                else
                    foreach (Expression expression in fArguments)
                        context.Output.Write(expression.Calculate(context, this));
            }
            else if (Name == "eval" && fArguments.Length>0)
            {
                Interpreter ip = new Interpreter("$" + fArguments[0].Calculate(context, this) + "$", null);
                ip.Parse();
                ip.Execute();
                return ip.Output;
            }
            else if (Name == "typeof")
            {
                if (fArguments.Length == 0 || !(fArguments[0] is Variable))
                    throw new Exception("typeof operator argument error. Usage: typeof(DateTime)");
                string typeName = (fArguments[0] as Variable).Name;
                return Context.GetType(typeName, context.Using);
            }
            else if (context.Functions[Name] != null)
            {
                FunctionDefinitionStatement func = (FunctionDefinitionStatement)context.Functions[Name];

                Hashtable arguments = new Hashtable();
                int i = 0;
                foreach (Expression expression in fArguments)
                {
                    object paramVal = expression.Calculate(context, this);
                    if (func.Parameters.Count > i)
                        arguments[func.Parameters[i]] = paramVal;
                    i++;
                }
                func.Block.Execute(context, this, arguments);
                object res = Context.ReturnValue;
                Context.ReturnValue = null;
                return res;
            }
            else
                throw new Exception("Undefined function: " + this);
            return null;
        }
Пример #39
0
 public override object Calculate(Context context, ParserNode parentNode)
 {
     return fValue;
 }
Пример #40
0
 public override object Calculate(Context context, ParserNode parentNode)
 {
     object left = Exp.Calculate(context, this);
     Type type = Context.GetType(typeName, context.Using);
     if (type == null)
         throw new Exception("There is no such type name: " + typeName);
     return left == null ? false : (left.GetType() == type);
 }
Пример #41
0
 public override object Calculate(Context context, ParserNode parentNode)
 {
     object val = nullableExp.Calculate(context, this);
     if (val == null || val.Equals(""))
         return notNullExp.Calculate(context, this);
     else
         return val;
 }
Пример #42
0
        public override object Calculate(Context context, ParserNode parentNode)
        {
            object res = LeftChildExpression.Calculate(context, this);

            // eğer sonuç null ve LeftExp variable ise static call olabilir
            if (res == null && LeftChildExpression is Variable)
            {
                string className = (LeftChildExpression as Variable).Name;
                Type t = Context.GetType(className, context.Using);
                if (t != null)
                {
                    if (RightChildExpression is Variable)
                    {
                        string propName = (RightChildExpression as Variable).Name;
                        PropertyInfo pi = t.GetProperty(propName, BindingFlags.Static | BindingFlags.Public);
                        if (pi != null)
                            res = pi.GetValue(null, null);
                        else
                        {
                            FieldInfo fi = t.GetField(propName);
                            if (fi != null)
                                res = fi.GetValue(null);
                            else
                                res = "";
                        }
                    }
                    else if (RightChildExpression is FunctionCall)
                    {
                        FunctionCall fc = (FunctionCall)RightChildExpression;

                        object[] paramValues = new object[fc.Arguments.Length];
                        Type[] paramTypes = new Type[fc.Arguments.Length];
                        int i = 0;
                        foreach (Expression exp in fc.Arguments)
                        {
                            paramValues[i] = exp.Calculate(context, this);
                            paramTypes[i] = paramValues[i]==null ? null : paramValues[i].GetType();
                            i++;
                        }

                        //MethodInfo mi = t.GetMethod(fc.Name, BindingFlags.Static | BindingFlags.Public, null, paramTypes, null);
                        MethodInfo mi = null; ParameterInfo[] arrPi;
                        FindMethod(t, fc.Name, paramTypes, out mi, out arrPi, BindingFlags.Static | BindingFlags.Public);
                        if (mi == null)
                            throw new Exception("Undefined param types for static method: " + this);
                        else
                            res = mi.Invoke(null, paramValues);
                    }
                    else if (RightChildExpression is MemberAccess)
                    {
                        res = new MemberAccess(new MemberAccess(this.LeftChildExpression, (this.RightChildExpression as MemberAccess).LeftChildExpression), (this.RightChildExpression as MemberAccess).RightChildExpression).Calculate(context, this);
                    }
                    else
                        res = null;
                }
                else
                    throw new Exception("Undefined static method: " + this);
            }
            else if (RightChildExpression is MemberAccess)
            {
                res = new MemberAccess(new MemberAccess(this.LeftChildExpression, (this.RightChildExpression as MemberAccess).LeftChildExpression), (this.RightChildExpression as MemberAccess).RightChildExpression).Calculate(context, this);
            }
            else if (RightChildExpression is FunctionCall)
            {
                FunctionCall fc = (FunctionCall)RightChildExpression;

                List<object> paramValues = new List<object>();
                List<Type> paramTypes = new List<Type>();
                int i = 0;
                foreach (Expression exp in fc.Arguments)
                {
                    paramValues.Add(exp.Calculate(context, this));
                    paramTypes.Add(paramValues[i] == null ? typeof(object) : paramValues[i].GetType());
                    i++;
                }

                if (res is string) {
                    switch (fc.Name.ToLowerInvariant())
                    {
                        case "split":
                            return res.ToString().Split(new string[] { paramValues[0].ToString() }, StringSplitOptions.RemoveEmptyEntries);
                    }
                }

                //MethodInfo mi = res.GetType().GetMethod(fc.Name, paramTypes);
                MethodInfo mi = null;
                ParameterInfo[] pinfo = null;
                FindMethod(res.GetType(), fc.Name, paramTypes.ToArray(), out mi, out pinfo);

                if (mi == null)
                    throw new Exception("Undefined method: " + this);
                else
                {
                    if (mi.GetParameters().Length > paramTypes.Count)
                    {
                        paramTypes.Add(typeof(object[]));
                        paramValues.Add(new object[0]);
                    }
                    for (int j = 0; j < paramTypes.Count; j++)
                    {
                        try
                        {
                            if(!paramTypes[j].IsSubclassOf(pinfo[j].ParameterType))
                                paramValues[j] = paramValues[j].ChangeType(pinfo[j].ParameterType);
                        }
                        catch
                        {
                            throw new Exception("Cannot convert from " + paramValues[j].GetType().Name + " to " + pinfo[j].ParameterType.Name + " or undefined method: " + this);
                        }
                    }
                    res = mi.Invoke(res, paramValues.ToArray());
                }
            }
            else if (RightChildExpression is Variable)
            {
                Variable var = (Variable)RightChildExpression;
                PropertyInfo pi = res.GetType().GetProperty(var.Name);
                if (pi != null)
                {
                    try
                    {
                        res = pi.GetValue(res, null);
                    }
                    catch(Exception ex)
                    {
                        throw new Exception("Property found but couldnt be read: " + this + " (" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message) + ")");
                    }
                }
                else
                {
                    FieldInfo fi = res.GetType().GetField(var.Name);
                    if (fi != null)
                    {
                        try
                        {
                            res = fi.GetValue(res);
                        }
                        catch(Exception ex)
                        {
                            throw new Exception("Field found but couldnt be read: " + this + " (" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message) + ")");
                        }
                    }
                    else
                    {
                        MethodInfo mi = res.GetType().GetMethod("get_Item", new Type[] { typeof(string) });
                        if (mi != null)
                        {
                            try
                            {
                                object paramObj = var.Name.ChangeType(mi.GetParameters()[0].ParameterType);
                                res = mi.Invoke(res, new object[] { paramObj });
                            }
                            catch(Exception ex)
                            {
                                throw new Exception("Indexer found but couldnt be read: " + this + " (" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message) + ")");
                            }
                        }
                        else
                            throw new Exception("Undefined property, field or indexer parameter: " + this);
                    }
                }
            }
            else
            {
                object val = RightChildExpression.Calculate(context, this);
                if (val.IsNumeric() && res.GetType() == typeof(string))
                    res = res.ToString()[Convert.ToInt32(val)];
                else
                    res = res.GetIndexedValue(val);
            }
            return res;
        }
Пример #43
0
		public ParserNodeAccess(ParserNode Parent, ParserNode Key)
		{
			this.Parent = Parent;
			this.Key = Key;
		}
Пример #44
0
 public ParserTree(IGrammar grammarReference, ParserNode singleNode)
 {
     _grammarReference = grammarReference;
     _hackingStack = new Stack<ParserNode>(new[] { singleNode });
 }
Пример #45
0
    void OnAttributes(ParserNode node) {
        if (node.parent != null) {
            node.name = node.parent.name + "/" + node.name;
        }
        CallStart(ref node.name); 

        CallOnNode(ref node.name, node.pairs);

        for (int i = 0; i < node.sons.Count; i++) {
            OnAttributes(node.sons[i]);
        }

        CallEnd(ref node.name);
    }
Пример #46
0
 public override object Calculate(Context context, ParserNode parentNode)
 {
     object res = LeftChildExpression.Calculate(context, this);
     object val = RightChildExpression.Calculate(context, this);
     if (val.IsNumeric() && res.GetType() == typeof(string))
         res = res.ToString()[Convert.ToInt32(val)];
     else
         res = res.GetIndexedValue(val);
     return res;
 }
Пример #47
0
        public ParserNode HandleLevel_Identifier()
        {
            ParserNode ParserNode;

            switch (CurrentTokenType)
            {
            case "OperatorTemplateToken":
                String Operator = CurrentToken.Text;
                switch (Operator)
                {
                // Unary Operators
                case "+":
                case "-":
                    Tokens.MoveNext();
                    ParserNode = new ParserNodeUnaryOperation()
                    {
                        Parent   = HandleLevel_Identifier(),
                        Operator = Operator,
                    };
                    Tokens.MoveNext();
                    break;

                case "(":
                    Tokens.MoveNext();
                    ParserNode = HandleLevel_Expression();
                    Tokens.ExpectValueAndNext(")");
                    break;

                default:
                    throw (new Exception(String.Format("Invalid operator '{0}'('{1}')", CurrentTokenType, CurrentToken.Text)));
                }
                break;

            case "NumericLiteralTemplateToken":
                ParserNode = new ParserNodeNumericLiteral()
                {
                    Value = Int64.Parse(CurrentToken.Text),
                };
                Tokens.MoveNext();
                break;

            case "IdentifierTemplateToken":
                String Id = CurrentToken.Text;
                Tokens.MoveNext();

                // Constants.
                switch (Id)
                {
                case "true":
                    ParserNode = new ParserNodeConstant(Id);
                    break;

                case "false":
                    ParserNode = new ParserNodeConstant(Id);
                    break;

                case "none":
                    ParserNode = new ParserNodeConstant(Id);
                    break;

                default:
                    ParserNode = new ParserNodeIdentifier(Id);
                    break;
                }

                bool Running = true;
                while (Running)
                {
                    switch (CurrentToken.Text)
                    {
                    // Dot identifier accessor.
                    case ".": {
                        Tokens.MoveNext();
                        TemplateToken AcessToken = Tokens.ExpectTypeAndNext(typeof(IdentifierTemplateToken));
                        ParserNode = new ParserNodeAccess(ParserNode, new ParserNodeStringLiteral(AcessToken.Text));
                    } break;

                    // Brace expression accessor.
                    case "[": {
                        Tokens.MoveNext();
                        ParserNode AccessNode = HandleLevel_Expression();
                        Tokens.ExpectValueAndNext("]");
                        ParserNode = new ParserNodeAccess(ParserNode, AccessNode);
                    } break;

                    default:
                        Running = false;
                        break;
                    }
                }

                break;

            case "StringLiteralTemplateToken":
                ParserNode = new ParserNodeStringLiteral(((StringLiteralTemplateToken)CurrentToken).UnescapedText);
                Tokens.MoveNext();
                break;

            default:
                throw (new Exception(String.Format("Invalid Identifier '{0}'('{1}')", CurrentTokenType, CurrentToken.Text)));
            }

            return(ParserNode);
        }
Пример #48
0
        protected override void HandleElementEnd(ParserNode node)
        {
            HandleQuickTags(node, false);

            ParserNode next = node.NextNode;
            ParserNode prev = node.PrevNode;

            switch (node.Name)
            {
            case "p":
            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
            case "h7":
                AddOutput("", 2, false);
                break;

            case "blockquote":
                AddBlockTag(node, "bq", false);
                break;

            case "a":
                if (CurrentLink.Attributes["title"] != null)
                {
                    AddOutput("(" + CurrentLink.Attributes["title"] + ")");
                }

                AddOutput("\"");

                if (CurrentLink != null && CurrentLink.Attributes.ContainsKey("href"))
                {
                    AddOutput(":" + GetTextileHref(CurrentLink.Attributes["href"]) + " ");
                }
                CurrentLink = null;
                break;

            case "pre":
                //if the previous element is a code element, we dont do the end...
                if (prev != null &&
                    prev.NodeType == System.Xml.XmlNodeType.EndElement &&
                    prev.Name == "code")
                {
                    break;
                }

                AddOutput("", 1, false);
                AddExtendedBlockTag(node, "pre", false);
                break;

            case "code":
                if (next != null &&
                    next.NodeType == System.Xml.XmlNodeType.EndElement &&
                    next.Name == "pre")
                {
                    AddOutput("", 1, false);
                    AddExtendedBlockTag(node, "bc", false);
                }
                break;

            //lists
            case "ol":
                _listDepth--;
                _inList.Pop();
                AddOutput("", _listDepth > 0 ? 1 : 2, false);
                break;

            case "ul":
                _listDepth--;
                _inList.Pop();
                AddOutput("", _listDepth > 0 ? 1 : 2, false);
                break;

            case "li":
                AddOutput("", 1, false);
                break;

            //tables
            case "table":
                AddOutput("", 2, false);
                _inTable = false;
                break;

            case "tr":
                AddOutput("|", 1, false);
                break;

            default:
                break;
            }
        }
Пример #49
0
 public abstract object Calculate(Context context, ParserNode parentNode);
Пример #50
0
        public override object Calculate(Context context, ParserNode parentNode)
        {
            object left = LeftChildExpression.Calculate(context, this);
            object right = RightChildExpression.Calculate(context, this);

            if(left!=null && left.GetType()==typeof(string))
                return left.ToString()[Convert.ToInt32(right)];

            return left.GetIndexedValue(right);
        }
Пример #51
0
        public override object Calculate(Context context, ParserNode parentNode)
        {
            object left = LeftChildExpression.Calculate(context, this);
            object right = RightChildExpression.Calculate(context, this);

            if (left == null && right == null)
            {
                left = right = 0;
            }

            if (left == null)
            {
                if (right.GetType() == typeof(string))
                    left = "";
                else if (right.GetType() == typeof(DateTime))
                    left = new DateTime(0, 0, 0);
                else
                    left = 0;
            }

            if (right == null)
            {
                if (left.GetType() == typeof(string))
                    right = "";
                else if (left.GetType() == typeof(DateTime))
                    right = new DateTime(1, 1, 1);
                else
                    right = 0;
            }

            try
            {
                if (left.GetType() == typeof(string) && right.GetType() != typeof(string))
                    left = left.ChangeType(right.GetType());

                if (right.GetType() == typeof(string) && left.GetType() != typeof(string))
                    right = right.ChangeType(left.GetType());
            }
            catch { }

            if (left.IsNumeric() && right.IsNumeric())
            {
                left = Convert.ToDecimal(left);
                right = Convert.ToDecimal(right);
            }

            if (left.GetType() != right.GetType())
            {
                left = left.ToString();
                right = right.ToString();
            }

            IComparable leftC = (IComparable)left;

            switch (Operator)
            {
                case ComparisonOperator.Equal:
                    return leftC.CompareTo(right) == 0;
                case ComparisonOperator.NotEqual:
                    return leftC.CompareTo(right) != 0;
                case ComparisonOperator.LessThan:
                    return leftC.CompareTo(right) < 0;
                case ComparisonOperator.GreaterThan:
                    return leftC.CompareTo(right) > 0;
                case ComparisonOperator.LessThanOrEqual:
                    return leftC.CompareTo(right) < 0 || leftC.CompareTo(right) == 0;
                case ComparisonOperator.GreaterThanOrEqual:
                    return leftC.CompareTo(right) > 0 || leftC.CompareTo(right) == 0;
                default:
                    throw new Exception("Undefined comparison operation: " + Operator);
            }
        }
Пример #52
0
 public override object Calculate(Context context, ParserNode parentNode)
 {
     return AndExpression.ParseBool(boolExp.Calculate(context, this)) ?
         trueExpression.Calculate(context, this)
         :
         falseExpression.Calculate(context, this);
 }
Пример #53
0
        public override object Calculate(Context context, ParserNode parentNode)
        {
            object left = LeftChildExpression.Calculate(context, this);
            object right = RightChildExpression.Calculate(context, this);

            if (left.IsNumeric() && right.IsNumeric())
                return ((int)left) ^ ((int)right);
            else
                return AndExpression.ParseBool(left) ^ AndExpression.ParseBool(right);
        }
Пример #54
0
 protected virtual void HandleElementStart(ParserNode node)
 {
 }
		public ParserNodeBinaryOperation(ParserNode LeftNode, ParserNode RightNode, String Operator)
		{
			this.LeftNode = LeftNode;
			this.RightNode = RightNode;
			this.Operator = Operator;
		}
Пример #56
0
 protected virtual void HandleElementEnd(ParserNode node)
 {
 }
Пример #57
0
 public ParserNodeChildrenCollectionEumerator EnumerateChildren(ParserNode node)
 {
     return(new ParserNodeChildrenCollectionEumerator(node.TokenId, node.NodeType));
 }
Пример #58
0
		public ParserNodeAutoescape(ParserNode AutoescapeExpression, ParserNode Body)
		{
			this.AutoescapeExpression = AutoescapeExpression;
			this.Body = Body;
		}
Пример #59
0
 private void CheckForPossibleMistakenEmptyStatement(ParserNode bodyNode)
 {
     if (bodyNode.Result is EmptyStatement && bodyNode.Context.Lexer.Peek().GetTokenCode() == (int) OPEN_BRACE)
         WarningEmptyStatement(bodyNode.Context, bodyNode.Range.Start);
 }
Пример #60
0
 void ReadWord(ParserNode parent) {
     if (error) return;
     char c;
     bool end = false;
     string word = "";
     while (!end) {
         if (error) end = true;
         if (localIndex == localText.Length) {
             end = true;
             break;
         }
         c = localText[localIndex];
         localIndex++;
         if (c=='{') { // start node
             if (!starting) {
                 error = true;
                 errorText = "Parse ERROR!! : commas pair not found.";
             }
             else {
                 ParserNode node = new ParserNode();
                 node.name = word;
                 if (parent == null) {
                     node.parent = null;
                     root = node;
                 }
                 else {
                     node.parent = parent;
                     parent.sons.Add(node);
                 }
                 ReadWord(node);
                 word = "";
                 braceStart++;
             }
         }
         else if (c == '=') { // value
             if (!starting) {
                 error = true;
                 errorText = "Parse ERROR!! : commas pair not found.";
             }
             else {
                 pair.name = word;
                 word = "";
                 equal = 0;
                 equalCount = true;
             }
         }
         else if (c == '}') { // end node
             braceEnd++;
             end = true;
         }
         else if (c == '"') { // start and end of value
             if (!starting) {
                 if (parent == null) {
                     error = true;
                     errorText = "Parse ERROR!! : braces count fail.";
                 }
                 else {
                     pair.value = word;
                     word = "";
                     parent.pairs.Add(pair);
                     equal = -1;
                     equalCount = false;
                 }
             }
             else {
                 if (equal > 0) {
                     error = true;
                     errorText = "Parse ERROR!! : commas pair not found.";
                 }
                 if (equal == -1) {
                     error = true;
                     errorText = "Parse ERROR!! : equal not found.";
                 }
             }
             starting = !starting;
         }
         else {
             word += c;
             if (equalCount) equal++;
         }
     }
 }