Spec-Zone.ru › OCaml

Модуль Parsetree

module Parsetree: sig .. end

Дерево абстрактной синтаксической структуры, полученное в результате парсинга

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

type constant = 
| 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 core_type list (*

Ptyp_tuple([T1 ; ... ; Tn]) представляет тип продукта T1 * ... * Tn.

Инвариант: 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].

*)
type package_type = Longident.t Asttypes.loc *       (Longident.t Asttypes.loc * core_type) list 

В качестве типизированных значений Parsetree.package_type:

  • (S, []) представляет (module S),
  • (S, [(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 истинно, если тег содержит константный (пустой) конструктор.
  • & происходит, когда для одного и того же конструктора используются несколько типов (см. 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 pattern list (*

Шаблоны (P1, ..., Pn).

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

*)
| 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 (*

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

  • (module P) когда s равно Some "P"
  • (module _) когда s равно None

Примечание: (module P : S) представлено как Ppat_constraint(Ppat_unpack(Some "P"), Ptyp_package S)

*)
| Ppat_exception of pattern (*

Шаблон exception P

*)
| 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 или тело 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 expression list (*

Выражения (E1, ..., En)

Инвариант: 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_letmodule of string option Asttypes.loc * module_expr * expression (*

let module M = ME in E

*)
| Pexp_letexception of extension_constructor * expression (*

let exception C 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 (*

(module ME).

(module ME : S) представлено как Pexp_constraint(Pexp_pack ME, Ptyp_package S)

*)
| Pexp_open of open_declaration * expression (*

- M.(E)

  • let open M in E
  • let open! M in E
*)
| 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 на enclosing 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), а последующие locs 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 до конца последнего case. Компилятор будет использовать только атрибуты, относящиеся к проверке типов из 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_cstrs : (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 type_kind = 
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list (*

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

*)
| Ptype_open
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-2024 INRIA.
https://ocaml.org/manual/5.2/api/compilerlibref/Parsetree.html

Spec-Zone.ru

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