Spec-Zone.ru › OCaml

Модуль Parsetree

module Parsetree: sig .. end

Абстрактное синтаксическое дерево, полученное при разборе

Предупреждение: этот модуль нестабилен и входит в состав compiler-libs.

type constant = {
pconst_desc : constant_desc;
pconst_loc : Location.t;
}
type constant_desc = 
| Pconst_integer of string * char option (*

Целочисленные константы, например 3 3l 3L 3n.

Парсер принимает суффиксы [g-z][G-Z]. Суффиксы, кроме 'l', 'L' и 'n', отклоняются проверкой типов.

*)
| Pconst_char of char (*

Символ, например 'c'.

*)
| Pconst_string of string * Location.t * string option (*

Строковая константа, например "constant" или {delim|other constant|delim}.

Диапазон расположения охватывает содержимое строки без разделителей.

*)
| Pconst_float of string * char option (*

Константа с плавающей точкой, например 3.4, 2e5 или 1.4e-4.

Парсер принимает суффиксы g-zG-Z. Проверка типов отклоняет суффиксы.

*)
type location_stack = Location.t list 

Точки расширения

type attribute = {
attr_name : string Asttypes.loc;
attr_payload : payload;
attr_loc : Location.t;
}

Атрибуты, например [@id ARG] и [@@id ARG].

Контейнеры метаданных, передаваемые внутри AST. Компилятор игнорирует неизвестные атрибуты.

type extension = string Asttypes.loc * payload 

Точки расширения, например [%id ARG] and [%%id ARG].

Заполнитель подъязыка — отклоняется проверкой типов.

type attributes = attribute list 
type payload = 
| PStr of structure
| PSig of signature (*

: SIG в атрибуте или точке расширения

*)
| PTyp of core_type (*

: T в атрибуте или точке расширения

*)
| PPat of pattern * expression option (*

? P или ? P when E, в атрибуте или точке расширения

*)

Основной язык

Выражения типов

type core_type = {
ptyp_desc : core_type_desc;
ptyp_loc : Location.t;
ptyp_loc_stack : location_stack;
ptyp_attributes : attributes; (*

... [@id1] [@id2]

*)
}
type core_type_desc = 
| Ptyp_any (*

_

*)
| Ptyp_var of string (*

Переменная типа, например 'a

*)
| Ptyp_arrow of Asttypes.arg_label * core_type * core_type (*

Ptyp_arrow(lbl, T1, T2) означает:

  • T1 -> T2, если lbl — Nolabel,
  • ~l:T1 -> T2, если lbl — Labelled,
  • ?l:T1 -> T2, если lbl — Optional.
*)
| Ptyp_tuple of (string option * core_type) list (*

Ptyp_tuple(tl) представляет тип-произведение:

  • T1 * ... * Tn, если tl — (None, T1); ...; (None, Tn)
  • L1:T1 * ... * Ln:Tn, если tl — (Some L1, T1); ...; (Some Ln, Tn)
  • Смешанный вариант, например L1:T1 * T2, если tl — (Some L1, T1); (None, T2)

Инвариант: n >= 2.

*)
| Ptyp_constr of Longident.t Asttypes.loc * core_type list (*

Ptyp_constr(lident, l) означает:

  • tconstr, если l=[],
  • T tconstr, если l=[T],
  • (T1, ..., Tn) tconstr, если l=[T1 ; ... ; Tn].
*)
| Ptyp_object of object_field list * Asttypes.closed_flag (*

Ptyp_object([ l1:T1; ...; ln:Tn ], flag) означает:

  • < l1:T1; ...; ln:Tn >, если flag — Closed,
  • < l1:T1; ...; ln:Tn; .. >, если flag — Open.
*)
| Ptyp_class of Longident.t Asttypes.loc * core_type list (*

Ptyp_class(tconstr, l) означает:

  • #tconstr, если l=[],
  • T #tconstr, если l=[T],
  • (T1, ..., Tn) #tconstr, если l=[T1 ; ... ; Tn].
*)
| Ptyp_alias of core_type * string Asttypes.loc (*

T as 'a.

*)
| Ptyp_variant of row_field list * Asttypes.closed_flag * Asttypes.label list option (*

Ptyp_variant([`A;`B], flag, labels) означает:

  • [ `A|`B ], если flag — Closed, а labels — None,
  • [> `A|`B ], если flag — Open, а labels — None,
  • [< `A|`B ], если flag — Closed, а labels — Some [],
  • [< `A|`B > `X `Y ], если flag — Closed, а labels — Some ["X";"Y"].
*)
| Ptyp_poly of string Asttypes.loc list * core_type (*

'a1 ... 'an. T

Может встречаться только в следующих контекстах:

  • В качестве Parsetree.core_type узла Ppat_constraint, соответствующего ограничению привязки let:
    let x : 'a1 ... 'an. T = e ...
  • Под Cfk_virtual для методов (не значений).
  • В качестве Parsetree.core_type узла Pctf_method.
  • В качестве Parsetree.core_type узла Pexp_poly.
  • В качестве поля pld_type узла Parsetree.label_declaration.
  • В качестве Parsetree.core_type узла Ptyp_object.
  • В качестве поля pval_type узла Parsetree.value_description.
*)
| Ptyp_package of package_type (*

(module S).

*)
| Ptyp_open of Longident.t Asttypes.loc * core_type (*

M.(T)

*)
| Ptyp_extension of extension (*

[%id].

*)
| Ptyp_functor of Asttypes.arg_label * string Asttypes.loc * package_type
* core_type
(*

(module M : S) -> ... : стрелка, зависящая от модуля

*)
type package_type = {
ppt_path : Longident.t Asttypes.loc;
ppt_constraints : (Longident.t Asttypes.loc * core_type) list;
ppt_loc : Location.t;
ppt_attrs : attributes;
}

Типизированные значения Parsetree.package_type:

  • {ppt_path: S; ppt_constraints: []} представляет (module S),
  • {ppt_path: S; ppt_constraints: [(t1, T1) ; ... ; (tn, Tn)]} представляет (module S with type t1 = T1 and ... and tn = Tn).
type row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
type row_field_desc = 
| Rtag of Asttypes.label Asttypes.loc * bool * core_type list (*

Rtag(`A, b, l) означает:

  • `A, если b — true, а l — [],
  • `A of T, если b — false, а l — [T],
  • `A of T1 & .. & Tn, если b — false, а l — [T1;...Tn],
  • `A of & T1 & .. & Tn, если b — true, а l — [T1;...Tn].
  • Поле bool имеет значение true, если тег содержит конструктор-константу (пустой конструктор).
  • & возникает, когда для одного конструктора используются несколько типов (см. раздел 4.2 руководства).
*)
| Rinherit of core_type (*

[ | t ]

*)
type object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
type object_field_desc = 
| Otag of Asttypes.label Asttypes.loc * core_type
| Oinherit of core_type

Шаблоны

type pattern = {
ppat_desc : pattern_desc;
ppat_loc : Location.t;
ppat_loc_stack : location_stack;
ppat_attributes : attributes; (*

... [@id1] [@id2]

*)
}
type pattern_desc = 
| Ppat_any (*

Шаблон _.

*)
| Ppat_var of string Asttypes.loc (*

Переменный шаблон, например x

*)
| Ppat_alias of pattern * string Asttypes.loc (*

Шаблон с псевдонимом, например P as 'a

*)
| Ppat_constant of constant (*

Шаблоны, например 1, 'a', "true", 1.0, 1l, 1L, 1n

*)
| Ppat_interval of constant * constant (*

Шаблоны, например 'a'..'z'.

Другие формы интервала распознаются парсером, но отвергаются средством проверки типов.

*)
| Ppat_tuple of (string option * pattern) list * Asttypes.closed_flag (*

Ppat_tuple(pl, Closed) представляет

  • (P1, ..., Pn), когда pl имеет значение (None, P1); ...; (None, Pn)
  • (~L1:P1, ..., ~Ln:Pn), когда pl имеет значение (Some L1, P1); ...; (Some Ln, Pn)
  • Смешанный вариант, например (~L1:P1, P2), когда pl имеет значение (Some L1, P1); (None, P2)

Ppat_tuple(pl, Open) похож, но указывает, что шаблон дополнительно заканчивается на ...

Инвариант:

  • Если Closed, n >= 2.
  • Если Open, n >= 1.
*)
| Ppat_construct of Longident.t Asttypes.loc
* (string Asttypes.loc list * pattern) option
(*

Ppat_construct(C, args) представляет:

  • C, когда args имеет значение None,
  • C P, когда args имеет значение Some ([], P)
  • C (P1, ..., Pn), когда args имеет значение Some ([], Ppat_tuple [P1; ...; Pn])
  • C (type a b) P, когда args имеет значение Some ([a; b], P)
*)
| Ppat_variant of Asttypes.label * pattern option (*

Ppat_variant(`A, pat) представляет:

  • `A, когда pat имеет значение None,
  • `A P, когда pat имеет значение Some P
*)
| Ppat_record of (Longident.t Asttypes.loc * pattern) list * Asttypes.closed_flag (*

Ppat_record([(l1, P1) ; ... ; (ln, Pn)], flag) представляет:

  • { l1=P1; ...; ln=Pn }, когда flag имеет значение Closed
  • { l1=P1; ...; ln=Pn; _}, когда flag имеет значение Open

Инвариант: n > 0

*)
| Ppat_array of pattern list (*

Шаблон [| P1; ...; Pn |]

*)
| Ppat_or of pattern * pattern (*

Шаблон P1 | P2

*)
| Ppat_constraint of pattern * core_type (*

Шаблон (P : T)

*)
| Ppat_type of Longident.t Asttypes.loc (*

Шаблон #tconst

*)
| Ppat_lazy of pattern (*

Шаблон lazy P

*)
| Ppat_unpack of string option Asttypes.loc * package_type option (*

Ppat_unpack(s, ptyp) представляет:

  • (module P : S), когда s имеет значение Some "P", а ptyp имеет значение Some "S"
  • (module _ : S), когда s имеет значение None, а ptyp имеет значение Some "S"
  • (module P), когда s имеет значение Some "P", а ptyp имеет значение None
  • (module _), когда s имеет значение None, а ptyp имеет значение None
*)
| Ppat_exception of pattern (*

Шаблон exception P

*)
| Ppat_effect of pattern * pattern
| Ppat_extension of extension (*

Шаблон [%id]

*)
| Ppat_open of Longident.t Asttypes.loc * pattern (*

Шаблон M.(P)

*)

Выражения значений

type expression = {
pexp_desc : expression_desc;
pexp_loc : Location.t;
pexp_loc_stack : location_stack;
pexp_attributes : attributes; (*

... [@id1] [@id2]

*)
}
type expression_desc = 
| Pexp_ident of Longident.t Asttypes.loc (*

Идентификаторы, такие как x и M.x

*)
| Pexp_constant of constant (*

Константные выражения, например 1, 'a', "true", 1.0, 1l, 1L, 1n

*)
| Pexp_let of Asttypes.rec_flag * value_binding list * expression (*

Pexp_let(flag, [(P1,E1) ; ... ; (Pn,En)], E) представляет:

  • let P1 = E1 and ... and Pn = EN in E, когда flag имеет значение Nonrecursive,
  • let rec P1 = E1 and ... and Pn = EN in E, когда flag имеет значение Recursive.
*)
| Pexp_function of function_param list * type_constraint option
* function_body
(*

Pexp_function ([P1; ...; Pn], C, body) представляет любую конструкцию с участием fun или function, включая:

  • fun P1 ... Pn -> E, когда body = Pfunction_body E
  • fun P1 ... Pn -> function p1 -> e1 | ... | pm -> em, когда body = Pfunction_cases [ p1 -> e1; ...; pm -> em ]

C представляет ограничение типа или приведение типа, размещённое непосредственно перед стрелкой, например fun P1 ... Pn : ty -> ..., когда C = Some (Pconstraint ty).

Функция должна иметь параметры: в Pexp_function (params, _, body), если params не содержит Pparam_val _, body должно иметь значение Pfunction_cases _.

*)
| Pexp_apply of expression * (Asttypes.arg_label * expression) list (*

Pexp_apply(E0, [(l1, E1) ; ... ; (ln, En)]) представляет E0 ~l1:E1 ... ~ln:En

li может быть Nolabel (аргумент без метки), Labelled (аргументы с метками) или Optional (необязательный аргумент).

Инвариант: n > 0

*)
| Pexp_match of expression * case list (*

match E0 with P1 -> E1 | ... | Pn -> En

*)
| Pexp_try of expression * case list (*

try E0 with P1 -> E1 | ... | Pn -> En

*)
| Pexp_tuple of (string option * expression) list (*

Pexp_tuple(el) представляет

  • (E1, ..., En), когда el имеет значение (None, E1); ...; (None, En)
  • (~L1:E1, ..., ~Ln:En), когда el имеет значение (Some L1, E1); ...; (Some Ln, En)
  • Смешанный вариант, например (~L1:E1, E2), когда el имеет значение (Some L1, E1); (None, E2)

Инвариант: n >= 2

*)
| Pexp_construct of Longident.t Asttypes.loc * expression option (*

Pexp_construct(C, exp) представляет:

  • C, когда exp имеет значение None,
  • C E, когда exp имеет значение Some E,
  • C (E1, ..., En), когда exp имеет значение Some (Pexp_tuple[E1;...;En])
*)
| Pexp_variant of Asttypes.label * expression option (*

Pexp_variant(`A, exp) представляет

  • `A, когда exp имеет значение None
  • `A E, когда exp имеет значение Some E
*)
| Pexp_record of (Longident.t Asttypes.loc * expression) list
* expression option
(*

Pexp_record([(l1,P1) ; ... ; (ln,Pn)], exp0) представляет

  • { l1=P1; ...; ln=Pn }, когда exp0 имеет значение None
  • { E0 with l1=P1; ...; ln=Pn }, когда exp0 имеет значение Some E0

Инвариант: n > 0

*)
| Pexp_field of expression * Longident.t Asttypes.loc (*

E.l

*)
| Pexp_setfield of expression * Longident.t Asttypes.loc * expression (*

E1.l <- E2

*)
| Pexp_array of expression list (*

[| E1; ...; En |]

*)
| Pexp_ifthenelse of expression * expression * expression option (*

if E1 then E2 else E3

*)
| Pexp_sequence of expression * expression (*

E1; E2

*)
| Pexp_while of expression * expression (*

while E1 do E2 done

*)
| Pexp_for of pattern * expression * expression
* Asttypes.direction_flag * expression
(*

Pexp_for(i, E1, E2, direction, E3) представляет:

  • for i = E1 to E2 do E3 done, когда direction имеет значение Upto
  • for i = E1 downto E2 do E3 done, когда direction имеет значение Downto
*)
| Pexp_constraint of expression * core_type (*

(E : T)

*)
| Pexp_coerce of expression * core_type option * core_type (*

Pexp_coerce(E, from, T) представляет

  • (E :> T), когда from имеет значение None,
  • (E : T0 :> T), когда from имеет значение Some T0.
*)
| Pexp_send of expression * Asttypes.label Asttypes.loc (*

E # m

*)
| Pexp_new of Longident.t Asttypes.loc (*

new M.c

*)
| Pexp_setinstvar of Asttypes.label Asttypes.loc * expression (*

x <- 2

*)
| Pexp_override of (Asttypes.label Asttypes.loc * expression) list (*

{< x1 = E1; ...; xn = En >}

*)
| Pexp_struct_item of structure_item * expression (*

let SI in E

*)
| Pexp_assert of expression (*

assert E.

Примечание: assert false обрабатывается средством проверки типов особым образом.

*)
| Pexp_lazy of expression (*

lazy E

*)
| Pexp_poly of expression * core_type option (*

Используется для тел методов.

Может использоваться только как выражение внутри Cfk_concrete для методов (но не значений).

*)
| Pexp_object of class_structure (*

object ... end

*)
| Pexp_newtype of string Asttypes.loc * expression (*

fun (type t) -> E

*)
| Pexp_pack of module_expr * package_type option (*

(module ME) или (module ME : S).

*)
| Pexp_letop of letop (*

- let* P = E0 in E1

  • let* P0 = E00 and* P1 = E01 in E1
*)
| Pexp_extension of extension (*

[%id]

*)
| Pexp_unreachable (*

.

*)
type case = {
pc_lhs : pattern;
pc_guard : expression option;
pc_rhs : expression;
}

Значения типа Parsetree.case представляют (P -> E) или (P when E0 -> E)

type letop = {
let_ : binding_op;
ands : binding_op list;
body : expression;
}
type binding_op = {
pbop_op : string Asttypes.loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
type function_param_desc = 
| Pparam_val of Asttypes.arg_label * expression option * pattern (*

Pparam_val (lbl, exp0, P) представляет параметр:

  • P, когда lbl — Nolabel, а exp0 — None
  • ~l:P, когда lbl — Labelled l, а exp0 — None
  • ?l:P, когда lbl — Optional l, а exp0 — None
  • ?l:(P = E0), когда lbl — Optional l, а exp0 — Some E0

Примечание: если задан E0, разрешён только Optional.

*)
| Pparam_newtype of string Asttypes.loc (*

Pparam_newtype x представляет параметр (type x). x содержит позицию идентификатора, тогда как pparam_loc во внешнем узле function_param указывает позицию (type x) целиком.

Несколько параметров (type a b c) представлены несколькими узлами Pparam_newtype, например:

 [ { pparam_kind = Pparam_newtype a; pparam_loc = loc1 };
           { pparam_kind = Pparam_newtype b; pparam_loc = loc2 };
           { pparam_kind = Pparam_newtype c; pparam_loc = loc3 };
         ]
      

Здесь первая позиция loc loc1 — это позиция (type a b c), а следующие позиции loc loc2 и loc3 совпадают с loc1, но помечены как призрачные позиции. Позиции в a, b, c соответствуют переменным a, b и c в исходном коде.

*)
type function_param = {
pparam_loc : Location.t;
pparam_desc : function_param_desc;
}
type function_body = 
| Pfunction_body of expression
| Pfunction_cases of case list * Location.t * attributes (*

В Pfunction_cases (_, loc, attrs) позиция охватывает диапазон от начала ключевого слова function до конца последнего случая. Компилятор использует из attrs только атрибуты, связанные с проверкой типов, например включающие или отключающие предупреждение.

*)

См. комментарий к Pexp_function.

type type_constraint = 
| Pconstraint of core_type
| Pcoerce of core_type option * core_type (*

См. комментарий к Pexp_function.

*)

Описания значений

type value_description = {
pval_name : string Asttypes.loc;
pval_type : core_type;
pval_prim : string list;
pval_attributes : attributes; (*

... [@@id1] [@@id2]

*)
pval_loc : Location.t;
}

Значения типа Parsetree.value_description представляют:

  • val x: T, если pval_prim — []
  • external x: T = "s1" ... "sn", если pval_prim — ["s1";..."sn"]

Объявления типов

type type_declaration = {
ptype_name : string Asttypes.loc;
ptype_params : (core_type * (Asttypes.variance * Asttypes.injectivity)) list; (*

('a1,...'an) t

*)
ptype_constraints : (core_type * core_type * Location.t) list; (*

... constraint T1=T1'  ... constraint Tn=Tn'

*)
ptype_kind : type_kind;
ptype_private : Asttypes.private_flag; (*

для = private ...

*)
ptype_manifest : core_type option; (*

представляет = T

*)
ptype_attributes : attributes; (*

... [@@id1] [@@id2]

*)
ptype_loc : Location.t;
}

Ниже приведены объявления типов и их представления для различных значений ptype_kind и ptype_manifest:

  • type t, если type_kind — Ptype_abstract, а manifest — None,
  • type t = T0, если type_kind — Ptype_abstract, а manifest — Some T0,
  • type t = C of T | ..., если type_kind — Ptype_variant, а manifest — None,
  • type t = T0 = C of T | ..., если type_kind — Ptype_variant, а manifest — Some T0,
  • type t = {l: T; ...}, если type_kind — Ptype_record, а manifest — None,
  • type t = T0 = {l : T; ...}, если type_kind — Ptype_record, а manifest — Some T0,
  • type t = .., если type_kind — Ptype_open, а manifest — None.
  • type t = external "gmp", если type_kind — Ptype_external("gmp"), а manifest — None.
type type_kind = 
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list (*

Инвариант: непустой список

*)
| Ptype_open
| Ptype_external of string
type label_declaration = {
pld_name : string Asttypes.loc;
pld_mutable : Asttypes.mutable_flag;
pld_type : core_type;
pld_loc : Location.t;
pld_attributes : attributes; (*

l : T [@id1] [@id2]

*)
}

- { ...; l: T; ... }, если pld_mutable — Immutable,

  • { ...; mutable l: T; ... }, если pld_mutable — Mutable.

Примечание: T может быть Ptyp_poly.

type constructor_declaration = {
pcd_name : string Asttypes.loc;
pcd_vars : string Asttypes.loc list;
pcd_args : constructor_arguments;
pcd_res : core_type option;
pcd_loc : Location.t;
pcd_attributes : attributes; (*

C of ... [@id1] [@id2]

*)
}
type constructor_arguments = 
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list (*

Значения типа Parsetree.constructor_declaration представляют аргументы конструктора для:

  • C of T1 * ... * Tn, когда res = None, и args = Pcstr_tuple [T1; ... ; Tn],
  • C: T0, когда res = Some T0, и args = Pcstr_tuple [],
  • C: T1 * ... * Tn -> T0, когда res = Some T0, и args = Pcstr_tuple [T1; ... ; Tn],
  • C of {...}, когда res = None, и args = Pcstr_record [...],
  • C: {...} -> T0, когда res = Some T0, и args = Pcstr_record [...].
*)
type type_extension = {
ptyext_path : Longident.t Asttypes.loc;
ptyext_params : (core_type * (Asttypes.variance * Asttypes.injectivity)) list;
ptyext_constructors : extension_constructor list;
ptyext_private : Asttypes.private_flag;
ptyext_loc : Location.t;
ptyext_attributes : attributes; (*

... @@id1 @@id2

*)
}

Определение новых конструкторов расширений для обширного типа-суммы t (type t += ...).

type extension_constructor = {
pext_name : string Asttypes.loc;
pext_kind : extension_constructor_kind;
pext_loc : Location.t;
pext_attributes : attributes; (*

C of ... [@id1] [@id2]

*)
}
type type_exception = {
ptyexn_constructor : extension_constructor;
ptyexn_loc : Location.t;
ptyexn_attributes : attributes; (*

... [@@id1] [@@id2]

*)
}

Определение нового исключения (exception E).

type extension_constructor_kind = 
| Pext_decl of string Asttypes.loc list * constructor_arguments
* core_type option
(*

Pext_decl(existentials, c_args, t_opt) описывает новый конструктор расширения. Он может быть:

  • C of T1 * ... * Tn, если:
    • existentials — [],
    • c_args — [T1; ...; Tn],
    • t_opt — None
  • C: T0, если
    • existentials — [],
    • c_args — [],
    • t_opt — Some T0.
  • C: T1 * ... * Tn -> T0, если
    • existentials — [],
    • c_args — [T1; ...; Tn],
    • t_opt — Some T0.
  • C: 'a... . T1 * ... * Tn -> T0, если
    • existentials — ['a;...],
    • c_args — [T1; ... ; Tn],
    • t_opt — Some T0.
*)
| Pext_rebind of Longident.t Asttypes.loc (*

Pext_rebind(D) повторно экспортируют конструктор D под новым именем C

*)

Язык классов

Выражения типов для языка классов

type class_type = {
pcty_desc : class_type_desc;
pcty_loc : Location.t;
pcty_attributes : attributes; (*

... [@id1] [@id2]

*)
}
type class_type_desc = 
| Pcty_constr of Longident.t Asttypes.loc * core_type list (*

- c

  • ['a1, ..., 'an] c
*)
| Pcty_signature of class_signature (*

object ... end

*)
| Pcty_arrow of Asttypes.arg_label * core_type * class_type (*

Pcty_arrow(lbl, T, CT) представляет:

  • T -> CT, когда lbl — Nolabel,
  • ~l:T -> CT, когда lbl — Labelled l,
  • ?l:T -> CT, когда lbl — Optional l.
*)
| Pcty_extension of extension (*

%id

*)
| Pcty_open of open_description * class_type (*

let open M in CT

*)
type class_signature = {
pcsig_self : core_type;
pcsig_fields : class_type_field list;
}

Значения типа class_signature представляют:

  • object('selfpat) ... end
  • object ... end, если pcsig_self — Ptyp_any
type class_type_field = {
pctf_desc : class_type_field_desc;
pctf_loc : Location.t;
pctf_attributes : attributes; (*

... [@@id1] [@@id2]

*)
}
type class_type_field_desc = 
| Pctf_inherit of class_type (*

inherit CT

*)
| Pctf_val of (Asttypes.label Asttypes.loc * Asttypes.mutable_flag *
Asttypes.virtual_flag * core_type)
(*

val x: T

*)
| Pctf_method of (Asttypes.label Asttypes.loc * Asttypes.private_flag *
Asttypes.virtual_flag * core_type)
(*

method x: T

Примечание: T может быть Ptyp_poly.

*)
| Pctf_constraint of (core_type * core_type) (*

constraint T1 = T2

*)
| Pctf_attribute of attribute (*

[@@@id]

*)
| Pctf_extension of extension (*

[%%id]

*)
type 'a class_infos = {
pci_virt : Asttypes.virtual_flag;
pci_params : (core_type * (Asttypes.variance * Asttypes.injectivity)) list;
pci_name : string Asttypes.loc;
pci_expr : 'a;
pci_loc : Location.t;
pci_attributes : attributes; (*

... [@@id1] [@@id2]

*)
}

Значения типа class_expr class_infos представляют:

  • class c = ...
  • class ['a1,...,'an] c = ...
  • class virtual c = ...

Они также используются для объявления «типа класса».

type class_description = class_type class_infos 
type class_type_declaration = class_type class_infos 

Выражения значений для языка классов

type class_expr = {
pcl_desc : class_expr_desc;
pcl_loc : Location.t;
pcl_attributes : attributes; (*

... [@id1] [@id2]

*)
}
type class_expr_desc = 
| Pcl_constr of Longident.t Asttypes.loc * core_type list (*

c и ['a1, ..., 'an] c

*)
| Pcl_structure of class_structure (*

object ... end

*)
| Pcl_fun of Asttypes.arg_label * expression option * pattern
* class_expr
(*

Pcl_fun(lbl, exp0, P, CE) представляет:

  • fun P -> CE, если lbl — Nolabel, а exp0 — None,
  • fun ~l:P -> CE, если lbl — Labelled l, а exp0 — None,
  • fun ?l:P -> CE, если lbl — Optional l, а exp0 — None,
  • fun ?l:(P = E0) -> CE, если lbl — Optional l, а exp0 — Some E0.
*)
| Pcl_apply of class_expr * (Asttypes.arg_label * expression) list (*

Pcl_apply(CE, [(l1,E1) ; ... ; (ln,En)]) представляет CE ~l1:E1 ... ~ln:En. li может быть пустым (аргумент без метки) или начинаться с ? (необязательный аргумент).

Инвариант: n > 0

*)
| Pcl_let of Asttypes.rec_flag * value_binding list * class_expr (*

Pcl_let(rec, [(P1, E1); ... ; (Pn, En)], CE) представляет:

  • let P1 = E1 and ... and Pn = EN in CE, если rec — Nonrecursive,
  • let rec P1 = E1 and ... and Pn = EN in CE, если rec — Recursive.
*)
| Pcl_constraint of class_expr * class_type (*

(CE : CT)

*)
| Pcl_extension of extension (*

[%id]

*)
| Pcl_open of open_description * class_expr (*

let open M in CE

*)
type class_structure = {
pcstr_self : pattern;
pcstr_fields : class_field list;
}

Значения типа Parsetree.class_structure представляют:

  • object(selfpat) ... end
  • object ... end, если pcstr_self — Ppat_any
type class_field = {
pcf_desc : class_field_desc;
pcf_loc : Location.t;
pcf_attributes : attributes; (*

... [@@id1] [@@id2]

*)
}
type class_field_desc = 
| Pcf_inherit of Asttypes.override_flag * class_expr * string Asttypes.loc option (*

Pcf_inherit(flag, CE, s) представляет:

  • inherit CE, если flag — Fresh, а s — None,
  • inherit CE as x, если flag — Fresh, а s — Some x,
  • inherit! CE, если flag — Override, а s — None,
  • inherit! CE as x, если flag — Override, а s — Some x
*)
| Pcf_val of (Asttypes.label Asttypes.loc * Asttypes.mutable_flag *
class_field_kind)
(*

Pcf_val(x,flag, kind) представляет:

  • val x = E, если flag — Immutable, а kind — Cfk_concrete(Fresh, E)
  • val virtual x: T, если flag — Immutable, а kind — Cfk_virtual(T)
  • val mutable x = E, если flag — Mutable, а kind — Cfk_concrete(Fresh, E)
  • val mutable virtual x: T, если flag — Mutable, а kind — Cfk_virtual(T)
*)
| Pcf_method of (Asttypes.label Asttypes.loc * Asttypes.private_flag *
class_field_kind)
(*

- method x = E (E может быть Pexp_poly)

  • method virtual x: T (T может быть Ptyp_poly)
*)
| Pcf_constraint of (core_type * core_type) (*

constraint T1 = T2

*)
| Pcf_initializer of expression (*

initializer E

*)
| Pcf_attribute of attribute (*

[@@@id]

*)
| Pcf_extension of extension (*

[%%id]

*)
type class_field_kind = 
| Cfk_virtual of core_type
| Cfk_concrete of Asttypes.override_flag * expression
type class_declaration = class_expr class_infos 

Язык модулей

Выражения типов для языка модулей

type module_type = {
pmty_desc : module_type_desc;
pmty_loc : Location.t;
pmty_attributes : attributes; (*

... [@id1] [@id2]

*)
}
type module_type_desc = 
| Pmty_ident of Longident.t Asttypes.loc (*

Pmty_ident(S) представляет S

*)
| Pmty_signature of signature (*

sig ... end

*)
| Pmty_functor of functor_parameter * module_type (*

functor(X : MT1) -> MT2

*)
| Pmty_with of module_type * with_constraint list (*

MT with ...

*)
| Pmty_typeof of module_expr (*

module type of ME

*)
| Pmty_extension of extension (*

[%id]

*)
| Pmty_alias of Longident.t Asttypes.loc (*

(module M)

*)
type functor_parameter = 
| Unit (*

()

*)
| Named of string option Asttypes.loc * module_type (*

Named(name, MT) представляет:

  • (X : MT), если name — Some X,
  • (_ : MT), если name — None
*)
type signature = signature_item list 
type signature_item = {
psig_desc : signature_item_desc;
psig_loc : Location.t;
}
type signature_item_desc = 
| Psig_value of value_description (*

- val x: T

  • external x: T = "s1" ... "sn"
*)
| Psig_type of Asttypes.rec_flag * type_declaration list (*

type t1 = ... and ... and tn  = ...

*)
| Psig_typesubst of type_declaration list (*

type t1 := ... and ... and tn := ...

*)
| Psig_typext of type_extension (*

type t1 += ...

*)
| Psig_exception of type_exception (*

exception C of T

*)
| Psig_module of module_declaration (*

module X = M и module X : MT

*)
| Psig_modsubst of module_substitution (*

module X := M

*)
| Psig_recmodule of module_declaration list (*

module rec X1 : MT1 and ... and Xn : MTn

*)
| Psig_modtype of module_type_declaration (*

module type S = MT и module type S

*)
| Psig_modtypesubst of module_type_declaration (*

module type S :=  ...

*)
| Psig_open of open_description (*

open X

*)
| Psig_include of include_description (*

include MT

*)
| Psig_class of class_description list (*

class c1 : ... and ... and cn : ...

*)
| Psig_class_type of class_type_declaration list (*

class type ct1 = ... and ... and ctn = ...

*)
| Psig_attribute of attribute (*

[@@@id]

*)
| Psig_extension of extension * attributes (*

[%%id]

*)
type module_declaration = {
pmd_name : string option Asttypes.loc;
pmd_type : module_type;
pmd_attributes : attributes; (*

... [@@id1] [@@id2]

*)
pmd_loc : Location.t;
}

Значения типа module_declaration представляют S : MT

type module_substitution = {
pms_name : string Asttypes.loc;
pms_manifest : Longident.t Asttypes.loc;
pms_attributes : attributes; (*

... [@@id1] [@@id2]

*)
pms_loc : Location.t;
}

Значения типа module_substitution представляют S := M

type module_type_declaration = {
pmtd_name : string Asttypes.loc;
pmtd_type : module_type option;
pmtd_attributes : attributes; (*

... [@@id1] [@@id2]

*)
pmtd_loc : Location.t;
}

Значения типа module_type_declaration представляют:

  • S = MT,
  • S для объявления абстрактного типа модуля, когда pmtd_type имеет значение None.
type 'a open_infos = {
popen_expr : 'a;
popen_override : Asttypes.override_flag;
popen_loc : Location.t;
popen_attributes : attributes;
}

Значения типа 'a open_infos представляют:

  • open! X, когда popen_override имеет значение Override (подавляет предупреждение «затенение используемого идентификатора»)
  • open  X, когда popen_override имеет значение Fresh
type open_description = Longident.t Asttypes.loc open_infos 

Значения типа open_description представляют:

  • open M.N
  • open M(N).O
type open_declaration = module_expr open_infos 

Значения типа open_declaration представляют:

  • open M.N
  • open M(N).O
  • open struct ... end
type 'a include_infos = {
pincl_mod : 'a;
pincl_loc : Location.t;
pincl_attributes : attributes;
}
type include_description = module_type include_infos 

Значения типа include_description представляют include MT

type include_declaration = module_expr include_infos 

Значения типа include_declaration представляют include ME

type with_constraint = 
| Pwith_type of Longident.t Asttypes.loc * type_declaration (*

with type X.t = ...

Примечание: последний компонент longident должен совпадать с именем type_declaration.

*)
| Pwith_module of Longident.t Asttypes.loc * Longident.t Asttypes.loc (*

with module X.Y = Z

*)
| Pwith_modtype of Longident.t Asttypes.loc * module_type (*

with module type X.Y = Z

*)
| Pwith_modtypesubst of Longident.t Asttypes.loc * module_type (*

with module type X.Y := sig end

*)
| Pwith_typesubst of Longident.t Asttypes.loc * type_declaration (*

with type X.t := ..., same format as [Pwith_type]

*)
| Pwith_modsubst of Longident.t Asttypes.loc * Longident.t Asttypes.loc (*

with module X.Y := Z

*)

Выражения-значения для языка модулей

type module_expr = {
pmod_desc : module_expr_desc;
pmod_loc : Location.t;
pmod_attributes : attributes; (*

... [@id1] [@id2]

*)
}
type module_expr_desc = 
| Pmod_ident of Longident.t Asttypes.loc (*

X

*)
| Pmod_structure of structure (*

struct ... end

*)
| Pmod_functor of functor_parameter * module_expr (*

functor(X : MT1) -> ME

*)
| Pmod_apply of module_expr * module_expr (*

ME1(ME2)

*)
| Pmod_apply_unit of module_expr (*

ME1()

*)
| Pmod_constraint of module_expr * module_type (*

(ME : MT)

*)
| Pmod_unpack of expression (*

(val E)

*)
| Pmod_extension of extension (*

[%id]

*)
type structure = structure_item list 
type structure_item = {
pstr_desc : structure_item_desc;
pstr_loc : Location.t;
}
type structure_item_desc = 
| Pstr_eval of expression * attributes (*

E

*)
| Pstr_value of Asttypes.rec_flag * value_binding list (*

Pstr_value(rec, [(P1, E1 ; ... ; (Pn, En))]) представляет:

  • let P1 = E1 and ... and Pn = EN, когда rec имеет значение Nonrecursive,
  • let rec P1 = E1 and ... and Pn = EN , когда rec имеет значение Recursive.
*)
| Pstr_primitive of value_description (*

- val x: T

  • external x: T = "s1" ... "sn" 
*)
| Pstr_type of Asttypes.rec_flag * type_declaration list (*

type t1 = ... and ... and tn = ...

*)
| Pstr_typext of type_extension (*

type t1 += ...

*)
| Pstr_exception of type_exception (*

- exception C of T

  • exception C = M.X
*)
| Pstr_module of module_binding (*

module X = ME

*)
| Pstr_recmodule of module_binding list (*

module rec X1 = ME1 and ... and Xn = MEn

*)
| Pstr_modtype of module_type_declaration (*

module type S = MT

*)
| Pstr_open of open_declaration (*

open X

*)
| Pstr_class of class_declaration list (*

class c1 = ... and ... and cn = ...

*)
| Pstr_class_type of class_type_declaration list (*

class type ct1 = ... and ... and ctn = ...

*)
| Pstr_include of include_declaration (*

include ME

*)
| Pstr_attribute of attribute (*

[@@@id]

*)
| Pstr_extension of extension * attributes (*

[%%id]

*)
type value_constraint = 
| Pvc_constraint of {
locally_abstract_univars : string Asttypes.loc list;
typ : core_type;
}
| Pvc_coercion of {
ground : core_type option;
coercion : core_type;
}
(*

- Pvc_constraint { locally_abstract_univars=[]; typ} — это простое ограничение типа для связывания значения:  let x : typ

  • В более общем случае в Pvc_constraint { locally_abstract_univars; typ} locally_abstract_univars — это список локально абстрактных переменных типа в  let x: type a ... . typ 
  • Pvc_coercion { ground=None; coercion } представляет let x :> typ
  • Pvc_coercion { ground=Some g; coercion } представляет let x : g :> typ
*)
type value_binding = {
pvb_pat : pattern;
pvb_expr : expression;
pvb_constraint : value_constraint option;
pvb_attributes : attributes;
pvb_loc : Location.t;
}

let pat : type_constraint = exp

type module_binding = {
pmb_name : string option Asttypes.loc;
pmb_expr : module_expr;
pmb_attributes : attributes;
pmb_loc : Location.t;
}

Значения типа module_binding представляют module X = ME

Верхний уровень

Фразы верхнего уровня

type toplevel_phrase = 
| Ptop_def of structure
| Ptop_dir of toplevel_directive (*

#use, #load ...

*)
type toplevel_directive = {
pdir_name : string Asttypes.loc;
pdir_arg : directive_argument option;
pdir_loc : Location.t;
}
type directive_argument = {
pdira_desc : directive_argument_desc;
pdira_loc : Location.t;
}
type directive_argument_desc = 
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool

© 1995-2026 INRIA.
https://ocaml.org/manual/5.5/api/compilerlibref/Parsetree.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API