[英]OCaml AST record type representation
我正在嘗試了解有關OCaml擴展點的更多信息,並且我無法跟蹤AST中記錄類型的表示。
我在這篇博客文章中竊取了以下示例:
http://whitequark.org/blog/2014/04/16/a-guide-to-extension-points-in-ocaml/
使用源文件(foo.ml):
let _ = [%getenv "USER"]
並輸出ocamlc -dparsetree fool.ml:
[
structure_item (test.ml[1,0+0]..[1,0+24])
Pstr_eval
expression (test.ml[1,0+8]..[1,0+24])
Pexp_extension "getenv"
[
structure_item (test.ml[1,0+17]..[1,0+23])
Pstr_eval
expression (test.ml[1,0+17]..[1,0+23])
Pexp_constant Const_string("USER",None)
]
]
從asttypes.mli和parsetree.mli我可以遵循該行的解析樹模式匹配
Pexp_constant Const_string("USER",None)
但是,當解析樹表示記錄類型時,我無法再跟蹤發生的情況。 似乎記錄字段的表示順序與它們在類型定義中出現的順序不同,並且解析樹中不需要(或顯示)所有字段。
來自parsetree.mli:
type expression = {
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_attributes: attributes;
}
解析樹輸出似乎只顯示位置和有效負載,但我可能讀錯了。
如何正確讀取記錄類型的AST? 對於類型表達式應該是:
(* record type declaration and pexp_loc field *)
expression (test.ml[1,0+8]..[1,0+24])
(* pexp_desc field *)
Pexp_extension "getenv"
[
...
]
您似乎缺少研究AST和使用擴展點的基本工具。 這些工具是Alain Frisch編寫的ppx_tools 。 其中一個工具正是為了探索AST的具體表現而設計的,它的名字是dumpast
。 我們將它應用於以下文件ast_record.mli
:
type card = {
name: string;
address: string;
age: int;
}
輸出是
ocamlfind ppx_tools/dumpast ast_record.mli
ast_record.mli
==>
[{psig_desc =
Psig_type
[{ptype_name = {txt = "card"}; ptype_params = []; ptype_cstrs = [];
ptype_kind =
Ptype_record
[{pld_name = {txt = "name"}; pld_mutable = Immutable;
pld_type = {ptyp_desc = Ptyp_constr ({txt = Lident "string"}, [])}};
{pld_name = {txt = "address"}; pld_mutable = Immutable;
pld_type = {ptyp_desc = Ptyp_constr ({txt = Lident "string"}, [])}};
{pld_name = {txt = "age"}; pld_mutable = Immutable;
pld_type = {ptyp_desc = Ptyp_constr ({txt = Lident "int"}, [])}}];
ptype_private = Public; ptype_manifest = None}]}]
=========
這證實了記錄標簽的順序得以保留。
順便提一下,我建議你研究這些ppx_tools的源代碼,也可能是Lwt附帶的ppx擴展。 它們非常簡短,寫得非常好,是一個值得推薦的靈感來源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.