diff --git a/Parser/Elements/ExpressionPart.cs b/Parser/Elements/ExpressionPart.cs index d003bb3..a7134f4 100644 --- a/Parser/Elements/ExpressionPart.cs +++ b/Parser/Elements/ExpressionPart.cs @@ -4,11 +4,11 @@ namespace XNeedle.Parser.Elements { public class ExpressionPart : Part { - public required Expression> Expr { get; set; } + public required Expression> Expr { get; set; } - public override void Operate(Context xtx) + public override void Operate(Context ctx) { - Expr.Compile()(); + Expr.Compile()(ctx); } } } \ No newline at end of file diff --git a/Parser/XnParser.cs b/Parser/XnParser.cs index 7c7c741..628ee34 100644 --- a/Parser/XnParser.cs +++ b/Parser/XnParser.cs @@ -13,6 +13,8 @@ namespace XNeedle.Parser { public class XnParser { + static readonly ParameterExpression CtxParam = Expression.Parameter(typeof(Context), "ctx"); + static Parser Operator(string op, ExpressionType opType) { return Parse.String(op).Token().Return(opType); @@ -46,7 +48,7 @@ namespace XNeedle.Parser var ctxMethodInfo = typeof(ContextFunctions).GetTypeInfo().GetMethod(name, parameters.Select(e => e.Type).Prepend(typeof(Context)).ToArray()); if (ctxMethodInfo != null) { - return Expression.Call(ctxMethodInfo, parameters.Prepend(Expression.Constant(ctx)).ToArray()); + return Expression.Call(ctxMethodInfo, parameters.Prepend(CtxParam).ToArray()); } throw new ParseException(string.Format("Function '{0}({1})' does not exist.", name, @@ -114,7 +116,13 @@ namespace XNeedle.Parser static Parser ExprPart(Context ctx) { - return Expr(ctx).Select(body => new ExpressionPart{Expr = Expression.Lambda>(body)}); + return Expr(ctx).Select(body => + { + Expression stringBody = body.Type == typeof(string) + ? body + : Expression.Call(body, typeof(object).GetMethod("ToString", Type.EmptyTypes)!); + return new ExpressionPart { Expr = Expression.Lambda>(stringBody, CtxParam) }; + }); } static readonly Parser XPath = diff --git a/Transformation/ContextFunctions.cs b/Transformation/ContextFunctions.cs index ad100ea..c9a4980 100644 --- a/Transformation/ContextFunctions.cs +++ b/Transformation/ContextFunctions.cs @@ -1,7 +1,4 @@ using System; -using System.IO; -using System.Text; -using System.Xml; using Sprache; using XNeedle.Parser; using XNeedle.Parser.Elements; @@ -16,13 +13,12 @@ namespace XNeedle.Transformation return $"#x{v:X8}"; } - public static int GetLevel(XmlNode node) + public static double GetLevel(Context ctx) { int level = 0; - XmlNode? currentNode = node; - while (null != (currentNode = currentNode.ParentNode)) + System.Xml.Linq.XElement? n = ctx.Node; + while (null != (n = n?.Parent)) level++; - return level; } public static double crc(Context ctx) @@ -51,7 +47,7 @@ namespace XNeedle.Transformation public static string attr(Context ctx, string name, string value) { - if (ctx.Node is null || !ctx.Node.HasAttributes) return ""; + if (ctx.Node is null) return ""; var attr = ctx.Node.Attribute(name); if (attr != null) {