[英]InvalidOperationException on conversion from F# quotation to Linq Expression
我正在尝试替换 F# Expr
中的类型,然后将其转换为Expression
以供 c# 库使用。 但是在调用LeafExpressionConverter.QuotationToExpression
我收到错误
InvalidOperationException:在翻译上下文中找不到变量“t”
基本上我正在尝试替换相当于
<@ fun (t: Record) -> tA = 10 @>
到
<@ fun (t: Dict) -> t["A"] = 10 @>
这是代码
type Record = {
A: int
}
type Dict () = //this is the type the c# lib wants (a dictionary representation of a type)
inherit Dictionary<string, obj>()
let substitute<'a> (ex: Expr<'a->bool>) =
let replaceVar (v: Var) = if v.Type = typeof<'a> then Var(v.Name, typeof<Dict>) else v
let tEntityItem = typeof<Dict>.GetProperty("Item")
let isATypeShapeVar = function | ShapeVar var -> var.Type = typeof<'a> | _ -> false
let rec substituteExpr =
function
| PropertyGet(exOpt, propOrValInfo, c) ->
match exOpt with
| None -> Expr.PropertyGet(propOrValInfo)
| Some ex ->
let args = c |> List.map substituteExpr
let newex = substituteExpr ex
match isATypeShapeVar ex with
| true ->
let getter = Expr.PropertyGet(newex, tEntityItem, [Expr.Value(propOrValInfo.Name)] )
Expr.Coerce(getter, propOrValInfo.PropertyType)
| false -> Expr.PropertyGet(newex, propOrValInfo, args)
| ShapeVar var -> Expr.Var (var |> replaceVar)
| ShapeLambda (var, expr) -> Expr.Lambda(var |> replaceVar, substituteExpr expr)
| ShapeCombination(shapeComboObject, exprList) ->
RebuildShapeCombination(shapeComboObject, List.map substituteExpr exprList)
substituteExpr ex |> LeafExpressionConverter.QuotationToExpression
substitute<Record> (<@ fun t -> t.A = 10 @>)
我怀疑我在替换中错过了一些东西,但我不知道是什么。
替换后的 F# Expr
的.ToString()
结果为
Lambda (t, Call (None, op_Equality, [Coerce (PropertyGet (Some (t), Item, [Value ("A")]), Int32), Value (10)]))
这看起来是正确的。 除了强制之外,它相当于<@ fun (t: Dict) -> t["A"] = 10 @>.ToString()
为什么QuotationToExpression
失败?
每次调用replaceVar
时,都会返回Var
的不同实例。 因此,当您替换 lambda 参数时,它是Var
的一个实例,稍后,当您替换newex
时,它是Var
的另一个实例。
Lambda (t, Call (None, op_Equality, [Coerce (PropertyGet (Some (t), ... ))
^ ^
| |
---------------------------------------------------------
These are different `t`, unrelated, despite the same name
要完成这项工作,您必须使其相同t
。 最愚蠢,最直接的方法是:
let substitute<'a> (ex: Expr<'a->bool>) =
let newArg = Var("arg", typeof<Dict>)
let replaceVar (v: Var) = if v.Type = typeof<'a> then newArg else v
...
这将使您的特定示例按预期工作,但仍然不可靠,因为您不仅要替换 lambda 参数,还要替换任何相同类型的变量。 这意味着如果表达式恰好包含与参数相同类型的任何变量,您仍然会遇到同样的问题。 例如,尝试转换:
<@ fun t -> let z = { A = 15 } in z.A = 15 && t.A = 10 @>
你会得到一个类似的错误,但这次抱怨变量z
。
更好的方法是在 go 时保持变量替换的 map,在第一次遇到新变量时插入新变量,但在后续遇到时从 map 获取它们。
另一种方法是专门找出 lambda 参数,然后仅替换它,而不是比较变量类型。
但是还有下一级的怪异:您正在将任何属性访问器转换为索引器访问器,但在我上面的示例中,不应该因此转换zA
。 因此,您必须以某种方式认识到属性访问的 object 是否实际上是论点,这可能不是那么微不足道。
如果您愿意满足于tA
的情况并在更复杂的情况下失败,例如(if true then t else t).A
,那么您可以匹配 lambda 参数并传递任何其他表达式:
let substitute<'a> (ex: Expr<'a->bool>) =
let arg =
match ex with
| ShapeLambda (v, _) -> v
| _ -> failwith "This is not a lambda. Shouldn't happen."
let newArg = Var("arg", typeof<Dict>)
let replaceVar (v: Var) = if v = arg then newArg else v
let tEntityItem = typeof<Dict>.GetProperty("Item")
let isATypeShapeVar = function | ShapeVar var -> var.Type = typeof<'a> | _ -> false
let rec substituteExpr =
function
| PropertyGet(Some (ShapeVar a), propOrValInfo, c) when a = arg ->
let getter = Expr.PropertyGet(Expr.Var newArg, tEntityItem, [Expr.Value(propOrValInfo.Name)] )
Expr.Coerce(getter, propOrValInfo.PropertyType)
| ShapeVar var -> Expr.Var (var |> replaceVar)
| ShapeLambda (var, expr) -> Expr.Lambda(var |> replaceVar, substituteExpr expr)
| ShapeCombination(shapeComboObject, exprList) ->
RebuildShapeCombination(shapeComboObject, List.map substituteExpr exprList)
| ex -> ex
substituteExpr ex |> LeafExpressionConverter.QuotationToExpression
> substituteExpr <@ fun t -> let z = { A = 15 } in z.A = 15 && t.A = 10 @>
val it: System.Linq.Expressions.Expression =
ToFSharpFunc(arg => z => ((z.A == 15) AndAlso (Convert(arg.get_Item("A"), Int32) == 10)).Invoke(new Record(15)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.