Beispiel #1
0
        /// <summary>
        ///		Parses an expression for use in an original template
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public string ReparseExpression(IMorestachioExpression expression)
        {
            var visitor = new ToParsableStringExpressionVisitor();

            expression.Accept(visitor);
            return(visitor.StringBuilder.ToString());
        }
Beispiel #2
0
 /// <inheritdoc />
 public IfExpressionScopeDocumentItem(CharacterLocation location, IMorestachioExpression value,
                                      IEnumerable <ITokenOption> tagCreationOptions,
                                      bool inverted)
     : base(location, value, tagCreationOptions)
 {
     Inverted = inverted;
 }
Beispiel #3
0
 /// <inheritdoc />
 public IsolationScopeDocumentItem(CharacterLocation location, IsolationOptions isolationOptions,
                                   IMorestachioExpression morestachioExpression,
                                   IEnumerable <ITokenOption> tagCreationOptions) : base(location, tagCreationOptions)
 {
     Isolation = isolationOptions;
     ScopeIsolationExpression = morestachioExpression;
 }
Beispiel #4
0
        /// <summary>
        ///     Will walk the path by using the path seperator "." and evaluate the object at the end
        /// </summary>
        /// <returns></returns>
        internal ContextObject GetContextForPath(Traversable elements,
                                                 ScopeData scopeData,
                                                 IMorestachioExpression morestachioExpression)
        {
            if (_key == "x:null" || !elements.HasValue)
            {
                return(this);
            }
            //look at the first element if its an alias switch to that alias
            //var peekPathPart = elements.Peek();
            if (elements.Count == 1 && elements.Current.Value == PathType.Null)
            {
                return(scopeData.ParserOptions.CreateContextObject("x:null", null));
            }

            var targetContext = this;

            if (elements.Current.Value == PathType.DataPath)
            {
                var getFromAlias = scopeData.GetVariable(targetContext, elements.Current.Key);
                if (getFromAlias != null)
                {
                    elements      = elements.Next();
                    targetContext = getFromAlias;
                }
            }

            return(targetContext.LoopContextTraversable(elements, scopeData, morestachioExpression));
            //return await targetContext.GetContextForPathInternal(elements, scopeData, morestachioExpression);
        }
Beispiel #5
0
        /// <summary>
        ///		Sets an Option that was requested from template
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="parserOptions"></param>
        /// <returns></returns>
        public async Promise SetOption(string name, IMorestachioExpression value, ParserOptions parserOptions)
        {
            var val = (await value.GetValue(new ContextObject(parserOptions, ".", null, new object()), new ScopeData()))
                      .Value;

            if (name.Equals("TokenPrefix", StringComparison.InvariantCultureIgnoreCase))
            {
                if (val == null)
                {
                    Errors.Add(new MorestachioSyntaxError(CurrentLocation.AddWindow(new CharacterSnippedLocation()),
                                                          "SET OPTION", "VALUE", $"The expression returned null for option '{name}' that does not accept a null value"));
                    return;
                }
                PrefixToken = val.ToString();
            }
            if (name.Equals("TokenSuffix", StringComparison.InvariantCultureIgnoreCase))
            {
                if (val == null)
                {
                    Errors.Add(new MorestachioSyntaxError(CurrentLocation.AddWindow(new CharacterSnippedLocation()),
                                                          "SET OPTION", "VALUE", $"The expression returned null for option '{name}' that does not accept a null value"));
                    return;
                }
                SuffixToken = val.ToString();
            }
        }
        internal static void WriteExpressionToXml(this XmlWriter writer, IMorestachioExpression morestachioExpression)
        {
            switch (morestachioExpression)
            {
            case MorestachioExpression _:
                writer.WriteStartElement("Expression");
                break;

            case MorestachioArgumentExpressionList _:
                writer.WriteStartElement("ExpressionArgList");
                break;

            case MorestachioMultiPartExpressionList _:
                writer.WriteStartElement("ExpressionMultiPart");
                break;

            case MorestachioExpressionString _:
                writer.WriteStartElement("ExpressionString");
                break;

            case MorestachioExpressionNumber _:
                writer.WriteStartElement("ExpressionNumber");
                break;

            case MorestachioOperatorExpression _:
                writer.WriteStartElement("ExpressionOperator");
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(morestachioExpression));
            }
            morestachioExpression.WriteXml(writer);
            writer.WriteEndElement();
        }
Beispiel #7
0
 /// <summary>
 ///		Creates a new Token Pair
 /// </summary>
 public TokenPair(IComparable type,
                  CharacterLocation tokenLocation,
                  IMorestachioExpression expression,
                  EmbeddedInstructionOrigin isEmbeddedToken = EmbeddedInstructionOrigin.Self)
     : this(type, null, tokenLocation, expression, null, isEmbeddedToken)
 {
 }
Beispiel #8
0
        /// <summary>
        ///     Will walk the path by using the path seperator "." and evaluate the object at the end
        /// </summary>
        /// <returns></returns>
        internal async ContextObjectPromise GetContextForPath(Traversable elements,
                                                              ScopeData scopeData,
                                                              IMorestachioExpression morestachioExpression)
        {
            if (Key == "x:null" || !elements.HasValue)
            {
                return(this);
            }
            //look at the first element if its an alias switch to that alias
            //var peekPathPart = elements.Peek();
            if (elements.Count == 1 && elements.Current.Value == PathType.Null)
            {
                return(Options.CreateContextObject("x:null", CancellationToken, null));
            }

            if (elements.Current.Value == PathType.DataPath)
            {
                var getFromAlias = scopeData.GetVariable(elements.Current.Key);
                if (getFromAlias != null)
                {
                    elements = elements.Next();
                    return(await getFromAlias.GetContextForPathInternal(elements, scopeData, morestachioExpression));
                }
            }

            return(await GetContextForPathInternal(elements, scopeData, morestachioExpression));
        }
Beispiel #9
0
 /// <summary>
 ///
 /// </summary>
 public InvalidPathEventArgs(ContextObject sender, IMorestachioExpression expression, string pathPart, Type type)
 {
     Sender     = sender;
     Expression = expression;
     PathPart   = pathPart;
     Type       = type;
 }
 /// <inheritdoc />
 public ImportPartialDocumentItem(CharacterLocation location,
                                  IMorestachioExpression value,
                                  IMorestachioExpression context,
                                  IEnumerable <ITokenOption> tagCreationOptions)
     : base(location, value, tagCreationOptions)
 {
     Context = context;
 }
Beispiel #11
0
 /// <inheritdoc />
 public MorestachioLocalizationDocumentItem(CharacterLocation location,
                                            IMorestachioExpression value,
                                            IMorestachioExpression explicitCulture,
                                            IEnumerable <ITokenOption> tagCreationOptions) : base(location, tagCreationOptions)
 {
     ExplicitCulture       = explicitCulture;
     MorestachioExpression = value;
 }
Beispiel #12
0
 /// <inheritdoc />
 public SwitchDocumentItem(CharacterLocation location,
                           IMorestachioExpression value,
                           bool shouldScopeToValue,
                           IEnumerable <ITokenOption> tagCreationOptions)
     : base(location, value, tagCreationOptions)
 {
     ScopeToValue = shouldScopeToValue;
 }
 /// <summary>
 ///		Creates an new Variable that expires when its enclosing scope (<see cref="IdVariableScope"/>) is closed
 /// </summary>
 /// <param name="value"></param>
 /// <param name="morestachioExpression"></param>
 /// <param name="idVariableScope"></param>
 public EvaluateLetVariableDocumentItem(CharacterLocation location,
                                        string value,
                                        IMorestachioExpression morestachioExpression,
                                        int idVariableScope,
                                        IEnumerable <ITokenOption> tagCreationOptions)
     : base(location, value, morestachioExpression, idVariableScope, tagCreationOptions)
 {
 }
Beispiel #14
0
 /// <summary>
 ///		Creates a new Token Pair
 /// </summary>
 public TokenPair(IComparable type, string value, CharacterLocation tokenLocation,
                  IMorestachioExpression expression, ScopingBehavior?noScope = null)
 {
     Type = type;
     MorestachioExpression = expression;
     TokenLocation         = tokenLocation;
     ScopeBehavior         = noScope;
     Value = value;
 }
        /// <inheritdoc />
        protected override void DeSerializeXml(XmlReader reader)
        {
            reader.ReadStartElement();
            var subtree = reader.ReadSubtree();

            subtree.Read();
            MorestachioExpression = subtree.ParseExpressionFromKind();
            reader.Skip();
            base.DeSerializeXml(reader);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        protected MorestachioOperatorExpression(SerializationInfo info, StreamingContext context)
        {
            Location = CharacterLocation.FromFormatString(info.GetString(nameof(Location)));
            var opText = info.GetString(nameof(Operator));

            Operator       = MorestachioOperator.Yield().First(f => f.OperatorText.Equals(opText));
            LeftExpression =
                info.GetValue(nameof(LeftExpression), typeof(IMorestachioExpression)) as IMorestachioExpression;
            RightExpression =
                info.GetValue(nameof(RightExpression), typeof(IMorestachioExpression)) as IMorestachioExpression;
        }
Beispiel #17
0
 /// <inheritdoc />
 protected override void DeSerializeXml(XmlReader reader)
 {
     reader.ReadStartElement();
     if (reader.Name == ExpressionTokenizer.ExpressionNodeName)
     {
         var subtree = reader.ReadSubtree();
         subtree.Read();
         MorestachioExpression = subtree.ParseExpressionFromKind();
         reader.Skip();
     }
     base.DeSerializeXml(reader);
 }
        private static string StringifyExpression(IMorestachioExpression expression)
        {
            if (expression == null)
            {
                return(null);
            }

            var visitor = new ToParsableStringExpressionVisitor();

            visitor.Visit(expression);
            return(visitor.StringBuilder.ToString());
        }
 /// <inheritdoc />
 protected override void DeSerializeXml(XmlReader reader)
 {
     base.DeSerializeXml(reader);
     if (reader.Name == "With")
     {
         reader.ReadStartElement();
         var subtree = reader.ReadSubtree();
         subtree.Read();
         Context = subtree.ParseExpressionFromKind();
         reader.Skip();
         reader.ReadEndElement();
     }
 }
Beispiel #20
0
        internal ContextObject LoopContextTraversable(Traversable elements,
                                                      ScopeData scopeData,
                                                      IMorestachioExpression morestachioExpression)
        {
            ContextObject context = this;

            while (elements != null && elements.HasValue)
            {
                context  = context.GetContextForPathInternal(elements, scopeData, morestachioExpression);
                elements = elements.Next();
            }

            return(context);
        }
Beispiel #21
0
        public async Task TestExpressionRuns(string variation, int width, int depth, int noArguments, int runs)
        {
            var expression = ConstructExpression("", width, depth, noArguments);

            ExpressionParser.ParseExpression("data", TokenzierContext.FromText("data"));

            var data = new Dictionary <string, object>();

            for (int i = 0; i < width; i++)
            {
                data["data"] = new Dictionary <string, object>();
            }


            var totalTime = Stopwatch.StartNew();
            var parseTime = Stopwatch.StartNew();
            IMorestachioExpression morestachioExpression = null;

            for (var i = 0; i < runs; i++)
            {
                morestachioExpression = ExpressionParser.ParseExpression(expression.Item1,
                                                                         TokenzierContext.FromText(expression.Item1));
            }

            parseTime.Stop();
            var executeTime = Stopwatch.StartNew();

            for (int i = 0; i < runs; i++)
            {
                var parserOptions = new ParserOptions("");
                await morestachioExpression.GetValue(new ContextObject(".", null, data)
                {
                }, new ScopeData(parserOptions));
            }
            executeTime.Stop();
            totalTime.Stop();
            PerformanceCounter.PerformanceCounters.Add(new PerformanceCounter.ExpressionPerformanceCounterEntity(variation)
            {
                TimePerRun  = new TimeSpan(parseTime.ElapsedTicks / runs),
                RunOver     = runs,
                Width       = width,
                Depth       = depth,
                NoArguments = noArguments,
                ParseTime   = parseTime.Elapsed,
                TotalTime   = totalTime.Elapsed,
                ExecuteTime = executeTime.Elapsed
            });
        }
        /// <inheritdoc />
        public void ReadXml(XmlReader reader)
        {
            var opText = reader.GetAttribute(nameof(Operator));

            Operator = MorestachioOperator.Yield().First(f => f.OperatorText.Equals(opText));
            Location = CharacterLocation.FromFormatString(reader.GetAttribute(nameof(Location)));
            reader.ReadStartElement();
            var leftSubTree = reader.ReadSubtree();

            LeftExpression = leftSubTree.ParseExpressionFromKind();
            if (reader.Name == nameof(RightExpression))
            {
                var rightSubtree = reader.ReadSubtree();
                RightExpression = rightSubtree.ParseExpressionFromKind();
            }
        }
Beispiel #23
0
        /// <inheritdoc />
        public override ContextObject HandlePathContext(KeyValuePair <string, PathType> currentElement,
                                                        IMorestachioExpression morestachioExpression,
                                                        ScopeData scopeData)
        {
            if (currentElement.Value != PathType.DataPath || !currentElement.Key.StartsWith("$"))
            {
                return(null);
            }
            object value = null;

            if (currentElement.Key.Equals("$recursion"))
            {
                value = scopeData.PartialDepth.Count;
            }
            return(value == null ? null : scopeData.ParserOptions.CreateContextObject(currentElement.Key, value, this));
        }
        /// <inheritdoc />
        protected override ContextObject HandlePathContext(
            Traversable elements,
            KeyValuePair <string, PathType> currentElement,
            IMorestachioExpression morestachioExpression,
            ScopeData scopeData)
        {
            if (currentElement.Value != PathType.DataPath || !currentElement.Key.StartsWith("$"))
            {
                return(null);
            }
            object value = null;

            if (currentElement.Key.Equals("$first"))
            {
                value = scopeData.PartialDepth.Count;
            }
            return(value == null ? null : Options.CreateContextObject(currentElement.Key, CancellationToken, value, this));
        }
Beispiel #25
0
        public void TestExpressionCanParseOperators(string query)
        {
            var sw = new Stopwatches();
            IMorestachioExpression expressions = null;
            TokenzierContext       context     = null;

            for (int i = 0; i < 50000; i++)
            {
                sw.Start();
                context     = TokenzierContext.FromText(query);
                expressions = ExpressionParser.ParseExpression(query, context);
                sw.Stop();
            }

            Assert.Warn("Result: " + sw.Elapsed + " average: " + sw.ElapsedAverage);
            //TestContext.Out.WriteLine();

            //Assert.That(expressions, Is.Not.Null, () => context.Errors.GetErrorText());
            //Assert.That(context.Errors, Is.Empty, () => context.Errors.GetErrorText());

            //var visitor = new ToParsableStringExpressionVisitor();
            //expressions.Accept(visitor);

            //var actual = visitor.StringBuilder.ToString();
            //Assert.That(actual, Is.EqualTo(query));


            //var template = "{{" + query + "}}";
            //var data = new Dictionary<string, object>();
            //for (var index = 0; index < args.Length; index++)
            //{
            //	var arg = args[index];
            //	data.Add(((char)('A' + index)).ToString(), arg);
            //}
            //var result = await ParserFixture.CreateAndParseWithOptions(template, data, ParserOptionTypes.UseOnDemandCompile, options =>
            //{
            //	//options.Formatters.AddSingleGlobal<object, object>(f =>
            //	//{
            //	//	return f;
            //	//}, "Self");
            //});
            //Assert.That(result, Is.EqualTo((valExp).ToString()));
        }
Beispiel #26
0
        /// <inheritdoc />
        protected override void DeSerializeXml(XmlReader reader)
        {
            reader.ReadStartElement();            //Path
            var subTree = reader.ReadSubtree();

            subTree.ReadStartElement();
            MorestachioExpression = subTree.ParseExpressionFromKind();
            reader.Skip();
            //reader.ReadEndElement();//Path
            if (reader.Name == nameof(ExplicitCulture))
            {
                reader.ReadStartElement();                //nameof(ExplicitCulture)
                var subtree = reader.ReadSubtree();
                subtree.Read();
                ExplicitCulture = subtree.ParseExpressionFromKind();
                reader.Skip();
                reader.ReadEndElement();                //nameof(ExplicitCulture)
            }
            base.DeSerializeXml(reader);
        }
Beispiel #27
0
        internal static IMorestachioExpression ParseExpressionFromKind(this XmlReader reader)
        {
            IMorestachioExpression exp = null;

            switch (reader.GetAttribute(ExpressionKindNodeName))
            {
            case "Expression":
                exp = new MorestachioExpression();
                break;

            case "ExpressionList":
                exp = new MorestachioExpressionList();
                break;

            case "ExpressionString":
                exp = new MorestachioExpressionString();
                break;
            }
            exp.ReadXml(reader);
            return(exp);
        }
Beispiel #28
0
        internal static IMorestachioExpression ParseExpressionFromKind(this XmlReader reader)
        {
            IMorestachioExpression exp = null;

            switch (reader.Name)
            {
            case "Expression":
                exp = new MorestachioExpression();
                break;

            case "ExpressionMultiPart":
                exp = new MorestachioMultiPartExpressionList();
                break;

            case "ExpressionArgList":
                exp = new MorestachioArgumentExpressionList();
                break;

            case "ExpressionString":
                exp = new MorestachioExpressionString();
                break;

            case "ExpressionNumber":
                exp = new MorestachioExpressionNumber();
                break;

            case "ExpressionOperator":
                exp = new MorestachioOperatorExpression();
                break;

            case "ExpressionBracket":
                exp = new MorestachioBracketExpression();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(ExpressionKindNodeName));
            }
            exp.ReadXml(reader);
            return(exp);
        }
Beispiel #29
0
        /// <summary>
        ///		Renders a Expression into the visitor
        /// </summary>
        public static void Visit(this IMorestachioExpressionVisitor visitor, IMorestachioExpression morestachioExpression)
        {
            switch (morestachioExpression)
            {
            case MorestachioExpression expression1:
                visitor.Visit(expression1);
                break;

            case ExpressionArgument expressionArgument:
                visitor.Visit(expressionArgument);
                break;

            case MorestachioBracketExpression operatorExpression:
                visitor.Visit(operatorExpression);
                break;

            case MorestachioArgumentExpressionList expressionList:
                visitor.Visit(expressionList);
                break;

            case MorestachioMultiPartExpressionList expressionList:
                visitor.Visit(expressionList);
                break;

            case MorestachioExpressionString expressionString:
                visitor.Visit(expressionString);
                break;

            case MorestachioExpressionNumber expressionNumber:
                visitor.Visit(expressionNumber);
                break;

            case MorestachioOperatorExpression operatorExpression:
                visitor.Visit(operatorExpression);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(morestachioExpression));
            }
        }
Beispiel #30
0
        internal static void WriteExpressionToXml(this XmlWriter writer, IMorestachioExpression morestachioExpression)
        {
            writer.WriteStartElement(ExpressionNodeName);
            switch (morestachioExpression)
            {
            case MorestachioExpression expression1:
                writer.WriteAttributeString(ExpressionKindNodeName, "Expression");
                break;

            case MorestachioExpressionList expressionList:
                writer.WriteAttributeString(ExpressionKindNodeName, "ExpressionList");
                break;

            case MorestachioExpressionString expressionString:
                writer.WriteAttributeString(ExpressionKindNodeName, "ExpressionString");
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(morestachioExpression));
            }
            morestachioExpression.WriteXml(writer);
            writer.WriteEndElement();
        }