/// <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()); }
/// <inheritdoc /> public IfExpressionScopeDocumentItem(CharacterLocation location, IMorestachioExpression value, IEnumerable <ITokenOption> tagCreationOptions, bool inverted) : base(location, value, tagCreationOptions) { Inverted = inverted; }
/// <inheritdoc /> public IsolationScopeDocumentItem(CharacterLocation location, IsolationOptions isolationOptions, IMorestachioExpression morestachioExpression, IEnumerable <ITokenOption> tagCreationOptions) : base(location, tagCreationOptions) { Isolation = isolationOptions; ScopeIsolationExpression = morestachioExpression; }
/// <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); }
/// <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(); }
/// <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) { }
/// <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)); }
/// <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; }
/// <inheritdoc /> public MorestachioLocalizationDocumentItem(CharacterLocation location, IMorestachioExpression value, IMorestachioExpression explicitCulture, IEnumerable <ITokenOption> tagCreationOptions) : base(location, tagCreationOptions) { ExplicitCulture = explicitCulture; MorestachioExpression = value; }
/// <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) { }
/// <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; }
/// <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(); } }
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); }
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(); } }
/// <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)); }
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())); }
/// <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); }
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); }
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); }
/// <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)); } }
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(); }