1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081letis_internal=reffalseletinternal_prefix=ref""letcheck_internal()=!is_internalmoduleParsetree=Ppxlib.ParsetreemoduleAsttypes=Ppxlib.AsttypesmoduleLongident=Ppxlib.LongidentmoduleLocation=Ppxlib.LocationopenPpxlib.AstopenPpxlib.Ast_helper(** Various misc functions *)letmkloctxtloc={txt;loc}letmkloc_opt?(loc=!default_loc)x=mklocxlocletunit?loc?attrs()=Exp.construct?loc?attrs(mkloc_opt?loc(Longident.Lident"()"))Noneletsequence?loc?attrs=function|[]->unit?loc?attrs()|hd::tl->List.fold_left(fune1e2->Exp.sequence?loc?attrse1e2)hdtlletstr?loc?attrss=Exp.constant?loc?attrs(Const.strings)letint?loc?attrss=Exp.constant?loc?attrs(Const.ints)letstr_option~loc=function|None->[%exprNone]|Somes->[%exprSome[%estrs]]letpunit?loc?attrs()=Pat.construct?loc?attrs(mkloc_opt?loc(Longident.Lident"()"))Noneletget_extension=function|{pexp_desc=Pexp_extension({txt;_},_);_}->txt|_->invalid_arg"Eliom ppx: Should be an extension."letin_contextcrefcfx=letold=!crefincref:=c;letres=fxincref:=old;reslet(%)fgx=f(gx)letexp_add_attrsattre={ewithpexp_attributes=attr}leteid{Location.txt;loc}=Exp.ident~loc{loc;txt=Longident.Lidenttxt}(** Build a Longident for an Eliom module path.
Without [-internal], prepends [Eliom.] to the path.
E.g. [eliom_lid "Syntax.client_value"] gives
[Eliom.Syntax.client_value] in user code. *)leteliom_lidpath=letlid=Longident.parsepathinifcheck_internal()thenlidelseletrecprepend=function|Longident.Lidents->Longident.Ldot(Longident.Lident"Eliom",s)|Longident.Ldot(p,s)->Longident.Ldot(prependp,s)|Longident.Lapply(p1,p2)->Longident.Lapply(prependp1,p2)inprependlid(** Build an expression referencing an Eliom module path. *)leteliom_expr~locpath=Exp.ident~loc{loc;txt=eliom_lidpath}(** Build a type constructor referencing an Eliom module path. *)leteliom_type~locpathargs=Typ.constr~loc{loc;txt=eliom_lidpath}argsletformat_args=function[]->unit()|[e]->e|l->Exp.tuplelletpat_args=function[]->punit()|[p]->p|l->Pat.tuplel(* We use a strong hash (MD5) of the file name.
We only keep the first 36 bit, which should be well enough: with
256 files, the likelihood of a collision is about one in two
millions.
These bits are encoded using an OCaml-compatible variant of Base
64, as the hash is used to generate OCaml identifiers. *)letfile_hashloc=lets=Digest.string(Filename.basenameloc.Location.loc_start.pos_fname)inlete="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'"inleto=Bytes.create6inletgp=Char.codes.[p]infori=0to5doletp=i*6/8inletd=10-(i*6mod8)inBytes.setoie.[(((gplsl8)+g(p+1))lsrd)land63]done;fori=0to4do(* Prevent problematic '_ pattern. This confuses our sed
invocation in eliomc. Simply replacing the pattern here is
easier than tightening the sed expression. *)ifBytes.getoi='\''&&Bytes.geto(i+1)='_'thenBytes.setoi'Z'done;Bytes.to_stringoletid_file_hashloc=letprefix="__eliom__compilation_unit_id__"in{Location.loc;txt=prefix^file_hashloc}(** [let __eliom__compilation_unit_id__HASH = "HASH"]
We hoist the file hash at the beginning of each eliom file.
This makes the generated javascript code smaller.
*)letmodule_hash_declarationloc=letid=Pat.var~loc@@id_file_hashlocinStr.value~locNonrecursive[Vb.mk~locid@@str@@file_hashloc](** The first position in a file, if it exists.
We avoid {!Location.input_name}, as it's unreliable when reading multiple files.
*)letfile_positionstr=matchstrwith|{pstr_loc;_}::_->Location.in_file@@pstr_loc.loc_start.pos_fname|[]->Location.none(** Cross-tier Eliom processing applies only to [.eliom]/[.eliomi] files.
Plain [.ml]/[.mli] files are ordinary (server- or client-only) OCaml and
must be left untouched: wrapping them in [set_global] would make e.g.
[Eliom_service.create] allocate an orphan client value ([no_client_fun])
that no client code ever consumes (reported by [check_global_data]). *)letis_plain_ocamlpos_fname=matchFilename.extensionpos_fnamewith".ml"|".mli"->true|_->falseletlexing_position~locl=[%expr{Lexing.pos_fname=[%estrl.Lexing.pos_fname];Lexing.pos_lnum=[%eint@@l.Lexing.pos_lnum];Lexing.pos_bol=[%eint@@l.Lexing.pos_bol];Lexing.pos_cnum=[%eint@@l.Lexing.pos_cnum]}]letpositionloc=letstart=loc.Location.loc_startinletstop=loc.Location.loc_endinExp.tuple~loc[lexing_position~locstart;lexing_position~locstop]letis_annotationtxtl=List.exists(funs->txt=s||txt="eliom."^s)l(** Identifiers generation. *)moduleName=structletescaped_ident_fmt:_format6="_eliom_escaped_ident_%Ld"letfragment_ident_fmt:_format6="_eliom_fragment_%s"letinjected_ident_fmt:_format6="_eliom_injected_ident_%6s%d"(* Identifiers for the closure representing a fragment. *)letfragment_num_count=ref0letfragment_num_loc=incrfragment_num_count;Printf.sprintf"%s%d"(file_hash_loc)!fragment_num_countletfragment_identid=Printf.sprintffragment_ident_fmtid(* Globaly unique ident for escaped expression *)(* It's used for type inference and as argument name for the
closure representing the surrounding fragment. *)(* Inside a fragment, same ident share the global ident. *)letescaped_idents=ref[]letreset_escaped_ident()=escaped_idents:=[]letescaped_expr,escaped_ident=letr=ref0Linletmake()=r:=Int64.(addone)!r;Printf.sprintfescaped_ident_fmt!rinletfor_exprloc=mkloc(make())locinletfor_idlocid=lettxt=tryList.associd!escaped_identswithNot_found->letgen_id=make()inescaped_idents:=(id,gen_id)::!escaped_idents;gen_idin{Location.txt;loc}infor_expr,for_idletinjected_expr,injected_ident,reset_injected_ident=letinjected_idents=ref[]inletr=ref0inletgen_identloc=lethash=file_hashlocinincrr;lets=Printf.sprintfinjected_ident_fmthash!rin{Location.txt=s;loc}inletgen_injected_identloc(s:string)=tryList.assocs!injected_identswithNot_found->letgen_id=gen_identlocininjected_idents:=(s,gen_id)::!injected_idents;gen_idandreset()=injected_idents:=[]ingen_ident,gen_injected_ident,resetend(* WARNING: if you change this, also change inferred_type_prefix in
tools/eliomc.ml *)letinferred_type_prefix="eliom_inferred_type_"moduleMli=structlettype_file=refNoneletget_type_file()=match!type_filewith|None->Filename.chop_extension!Ocaml_common.Location.input_name^".type_mli"|Somef->fletexists()=Option.is_some!type_fileletsuppress_underscore=letrename=letc=ref0infuns->incrc;Printf.sprintf"an_%s_%d"s!candhas_pfix=funs->String.starts_with~prefix:inferred_type_prefixsinobjectinheritPpxlib.Ast_traverse.mapassupermethod!core_typety=matchty.ptyp_descwith|Ptyp_varvarwhenhas_pfixvar->super#core_type{tywithptyp_desc=Ptyp_var(renamevar)}|_->super#core_typetyend#core_typeletis_injected_identid=tryScanf.sscanfidName.injected_ident_fmt(fun__->true)withScanf.Scan_failure_->falseletis_escaped_identid=tryScanf.sscanfidName.escaped_ident_fmt(fun_->true)withScanf.Scan_failure_->falseletis_fragment_identid=tryScanf.sscanfidName.fragment_ident_fmt(fun_->true)withScanf.Scan_failure_->falseletget_injected_ident_infoid=Scanf.sscanfidName.injected_ident_fmt(funun->u,n)letget_fragment_type=function|[%type:[%t?typ]Client_value.fragment]|[%type:[%t?typ]Client_value.t]|[%type:[%t?typ]Eliom__.Client_value.fragment]|[%type:[%t?typ]Eliom__.Client_value.t]|[%type:[%t?typ]Eliom.Client_value.fragment]|[%type:[%t?typ]Eliom.Client_value.t]->Sometyp|_->Noneletget_bindingsig_item=matchsig_item.psig_descwith|Psig_value{pval_name={txt;_};pval_type=[%type:[%t?typ]optionref];_}->ifis_injected_identtxt||is_escaped_identtxtthenSome(txt,suppress_underscoretyp)elseifis_fragment_identtxtthenmatchget_fragment_typetypwith|Sometyp->Some(txt,suppress_underscoretyp)|None->NoneelseNone|_->Noneletload_filefile=tryletch=open_infileinletitems=Ppxlib.Parse.interface(Lexing.from_channelch)inclose_inch;leth=Hashtbl.create17inletfitem=matchget_bindingitemwith|Some(s,typ)->Hashtbl.addhstyp|None->()inList.iterfitems;hwithSys_errors->Location.raise_errorf~loc:(Location.in_filefile)"Eliom: Error while loading types: %s"sletinferred_sig=lazy(load_file(get_type_file()))letfinderr{Location.txt;loc}=tryHashtbl.find(Lazy.forceinferred_sig)txtwithNot_found->Typ.extension~loc@@Location.Error.to_extension@@Location.Error.make~loc~sub:[](Printf.sprintf"Error: Inferred type of %s not found. You need to regenerate %s."err(get_type_file()))letfind_escaped_ident=find"escaped ident"letfind_injected_ident=find"injected ident"letfind_fragment=find"client value"endmoduleCmo=structletfile=refNoneletexists()=!file<>Noneletrecord_eventseventsevl=letopenInstructinList.iter(funev->matchevwith|{ev_loc={loc_start={Lexing.pos_fname;pos_cnum;_};loc_end={Lexing.pos_cnum=pos_cnum';_};_};ev_kind=Event_afterty;_}->ifpos_cnum'=pos_cnum+1thenHashtbl.addevents(pos_fname,pos_cnum)ty|_->())evlletget_file()=match!filewithSomef->f|None->assertfalseletload()=letfile=get_file()inmatchopen_infilewith|exceptionSys_errors->Location.raise_errorf~loc:(Location.in_filefile)"Eliom: Error while loading types: %s"s|ic->letopenCmo_formatinletbuffer=tryreally_input_stringic(String.lengthConfig.cmo_magic_number)withEnd_of_file->""inifbuffer<>Config.cmo_magic_numberthenLocation.raise_errorf~loc:(Location.in_filefile)"Eliom: Error while loading types: not an object file";letcu_pos=input_binary_inticinseek_iniccu_pos;letcu=(input_valueic:compilation_unit)inifcu.cu_debug=0thenLocation.raise_errorf~loc:(Location.in_filefile)"Eliom: Error while loading types: no debugging information";seek_iniccu.cu_debug;letevl=(input_valueic:Instruct.debug_eventlist)inletevents=Hashtbl.create100inrecord_eventseventsevl;close_inic;eventsletevents=lazy(load())let[@ocaml.warning"-32"]label_of_strings=ifs=""thenAsttypes.Nolabelelseifs.[0]='?'thenAsttypes.Optional(String.subs1(String.lengths-1))elseAsttypes.Labelledsletrecident_of_out_identid=letopenOutcometreeinletopenLongidentinletstrip_wrapperlid=(* Strip wrapper module prefixes from type paths read from the server
.cmo, since the client modules are siblings in the same wrapped
library.
- [-internal]: strips "Eliom." (for compiling Eliom itself)
- [-internal-prefix Os]: strips "Os." (for compiling ocsigen-start) *)matchlidwith|Ldot(Lident"Eliom",nm)whencheck_internal()->Lidentnm|Ldot(Lidentw,nm)when!internal_prefix<>""&&w=!internal_prefix->Lidentnm|_->lidinmatchidwith|Oide_apply(id,id')->Lapply(ident_of_out_identid,ident_of_out_identid')|Oide_dot(id,nm)->Ldot(strip_wrapper(ident_of_out_identid),nm)|Oide_ident{printed_name=nm}->Lident(tryString.subnm0(String.indexnm'/')withNot_found->nm)(* The type of the alias name follows the ppxlib AST, not the compiler. *)lettyp_alias~loctyalias=Typ.alias~locty(mklocaliasloc)[@@ifast_version>=502]lettyp_alias~loctyalias=Typ.alias~loctyalias[@@ifast_version<502]letcounter=ref0(* Collect all variable names referenced by Otyp_var nodes. *)letcollect_varsty=letopenOutcometreeinletmoduleS=Set.Make(String)inletrecgoacc=function|Otyp_var(_,name)->S.addnameacc|((Otyp_alias{aliased;_})[@ifocaml_version>=(5,1,0)])->goaccaliased|((Otyp_alias(ty,_))[@ifocaml_version<(5,1,0)])->goaccty|Otyp_arrow(_,ty1,ty2)->go(goaccty1)ty2|((Otyp_tupletyl)[@ifocaml_version>=(5,4,0)])->List.fold_left(funacc(_,ty)->goaccty)acctyl|((Otyp_tupletyl)[@ifocaml_version<(5,4,0)])->List.fold_leftgoacctyl|Otyp_constr(_,tyl)->List.fold_leftgoacctyl|((Otyp_object{fields;_})[@ifocaml_version>=(5,1,0)])->List.fold_left(funacc(_,ty)->goaccty)accfields|((Otyp_object(fields,_))[@ifocaml_version<(5,1,0)])->List.fold_left(funacc(_,ty)->goaccty)accfields|((Otyp_class(_,tyl))[@ifocaml_version>=(5,1,0)])->List.fold_leftgoacctyl|((Otyp_class(_,_,tyl))[@ifocaml_version<(5,1,0)])->List.fold_leftgoacctyl|((Otyp_variant(Ovar_typty,_,_))[@ifocaml_version>=(5,1,0)])->goaccty|((Otyp_variant(_,Ovar_typty,_,_))[@ifocaml_version<(5,1,0)])->goaccty|((Otyp_variant(Ovar_fieldslst,_,_))[@ifocaml_version>=(5,1,0)])->List.fold_left(funacc(_,_,tyl)->List.fold_leftgoacctyl)acclst|((Otyp_variant(_,Ovar_fieldslst,_,_))[@ifocaml_version<(5,1,0)])->List.fold_left(funacc(_,_,tyl)->List.fold_leftgoacctyl)acclst|Otyp_poly(_,ty)->goaccty|_->accingoS.emptyty(* We use the same location for all nodes of the constructed type,
which is an approximation but sufficient for error reporting. *)lettype_of_out_type?(loc=Location.none)ty=letopenOutcometreeinletopenParsetreeinletmoduleS=Set.Make(String)inletused_vars=collect_varstyinletmap=Hashtbl.create1inletvarx=tryHashtbl.findmapxwithNot_found->letx'=Printf.sprintf"%s%s_%d"inferred_type_prefixx!counterinincrcounter;Hashtbl.addmapxx';x'inletrectype_of_out_typety=matchtywith|Otyp_var(_,s)->Typ.var~loc(vars)|((Otyp_arrow(lab,ty1,ty2))[@ifocaml_version>=(5,2,0)])->letlab=matchlabwith|Nolabel->Nolabel|Labelledlab->Labelledlab|Optionallab->OptionallabinTyp.arrow~loclab(type_of_out_typety1)(type_of_out_typety2)|((Otyp_arrow(lab,ty1,ty2))[@ifocaml_version<(5,2,0)])->Typ.arrow~loc(label_of_stringlab)(type_of_out_typety1)(type_of_out_typety2)|((Otyp_tupletyl)[@ifocaml_version>=(5,4,0)])->Typ.tuple~loc(List.map(fun(_,ty)->type_of_out_typety)tyl)|((Otyp_tupletyl)[@ifocaml_version<(5,4,0)])->Typ.tuple~loc(List.maptype_of_out_typetyl)|Otyp_constr(id,tyl)->Typ.constr~loc(mkloc(ident_of_out_identid)loc)(List.maptype_of_out_typetyl)|((Otyp_object{fields;row})[@ifocaml_version>=(5,5,0)])->letfields=List.map(fun(label,ty)->{pof_desc=Otag(mkloclabelloc,type_of_out_typety);pof_loc=loc;pof_attributes=[]})fieldsinTyp.object_~locfields(matchrowwithOrow_closed->Closed|_->Open)|((Otyp_object{fields;open_row})[@ifocaml_version>=(5,1,0)&&ocaml_version<(5,5,0)])->letfields=List.map(fun(label,ty)->{pof_desc=Otag(mkloclabelloc,type_of_out_typety);pof_loc=loc;pof_attributes=[]})fieldsinTyp.object_~locfields(ifopen_rowthenOpenelseClosed)|((Otyp_object(fields,rest))[@ifocaml_version<(5,1,0)])->letfields=List.map(fun(label,ty)->{pof_desc=Otag(mkloclabelloc,type_of_out_typety);pof_loc=loc;pof_attributes=[]})fieldsinTyp.object_~locfields(ifrest=NonethenClosedelseOpen)|((Otyp_class(id,tyl))[@ifocaml_version>=(5,1,0)])->Typ.class_~loc(mkloc(ident_of_out_identid)loc)(List.maptype_of_out_typetyl)|((Otyp_class(_,id,tyl))[@ifocaml_version<(5,1,0)])->Typ.class_~loc(mkloc(ident_of_out_identid)loc)(List.maptype_of_out_typetyl)|((Otyp_alias{aliased;alias;_})[@ifocaml_version>=(5,1,0)])->ifS.memaliasused_varsthentyp_alias~loc(type_of_out_typealiased)(varalias)elsetype_of_out_typealiased|((Otyp_alias(ty,s))[@ifocaml_version<(5,1,0)])->ifS.memsused_varsthentyp_alias~loc(type_of_out_typety)(vars)elsetype_of_out_typety|((Otyp_variant(Ovar_typty,closed,tags))[@ifocaml_version>=(5,1,0)])->Typ.variant~loc[Rf.mk~loc(Rinherit(type_of_out_typety))](ifclosedthenClosedelseOpen)tags|((Otyp_variant(_,Ovar_typty,closed,tags))[@ifocaml_version<(5,1,0)])->Typ.variant~loc[Rf.mk~loc(Rinherit(type_of_out_typety))](ifclosedthenClosedelseOpen)tags|((Otyp_variant(Ovar_fieldslst,closed,tags))[@ifocaml_version>=(5,1,0)])->letrow_fields=List.map(fun(label,const,tyl)->Rf.mk~loc(Rtag(mkloclabelloc,const,List.maptype_of_out_typetyl)))lstinTyp.variant~locrow_fields(ifclosedthenClosedelseOpen)tags|((Otyp_variant(_,Ovar_fieldslst,closed,tags))[@ifocaml_version<(5,1,0)])->letrow_fields=List.map(fun(label,const,tyl)->Rf.mk~loc(Rtag(mkloclabelloc,const,List.maptype_of_out_typetyl)))lstinTyp.variant~locrow_fields(ifclosedthenClosedelseOpen)tags|Otyp_poly(sl,ty)->Typ.poly~loc(List.map(funv->mkloc(varv)loc)sl)(type_of_out_typety)|((Otyp_external_)[@ifocaml_version>=(5,5,0)])->assertfalse|((Otyp_functor_)[@ifocaml_version>=(5,5,0)])->assertfalse|Otyp_abstract|Otyp_open|Otyp_sum_|Otyp_manifest_|Otyp_record_|Otyp_module_|Otyp_attribute_|Otyp_stuff_->assertfalseintype_of_out_typetylettyp?locty=letty=Out_type.prepare_for_printing[ty];Out_type.tree_of_typexpType_schemetyintype_of_out_type?locty[@@ifocaml_version>=(5,3,0)]lettyp?locty=letty=Printtyp.tree_of_type_schemetyintype_of_out_type?locty[@@ifocaml_version<(5,3,0)]letlookuploc=let{Lexing.pos_fname;pos_cnum;_}=loc.Location.loc_startinOption.map(typ~loc)(Hashtbl.find_opt(Lazy.forceevents)(pos_fname,pos_cnum))letnot_founderrloc=Typ.extension~loc@@Location.Error.to_extension@@Location.Error.make~loc~sub:[](Printf.sprintf"Error: Inferred type of %s not found. You need to regenerate %s."err(get_file()))letfinderrloc=matchlookuplocwithSomety->ty|None->not_founderrlocletfind_escaped_ident=find"escaped ident"letfind_injected_ident=find"injected ident"letfind_fragmentloc=matchlookuplocwith|None->not_found"client value"loc|Somety->(matchMli.get_fragment_typetywith|Somety->ty|None->failwith(Format.asprintf"find_fragment: unexpected type: %a"Ppxlib.Pprintast.core_typety))end(** Context convenience module. *)moduleContext=structtypeserver=[`Server|`Shared]typeclient=[`Client|`Shared]letof_string=function|"server"|"server.start"|"eliom.server"|"eliom.server.start"->`Server|"shared"|"shared.start"|"eliom.shared"|"eliom.shared.start"->`Shared|"client"|"client.start"|"eliom.client"|"eliom.client.start"->`Client|_->invalid_arg"Eliom ppx: Not a context"typeescape_inject=[`Escaped_valueofserver|`Injectionofclient]typet=[`Server(* [%%server ... ] *)|`Client(* [%%client ... ] *)|`Shared(* [%%shared ... ] *)|`Fragmentofserver*bool(* [%client ... ] *)|`Escaped_valueofserver(* [%shared ~%( ... ) ] *)|`Injectionofclient(* [%%client ~%( ... ) ] *)]endletdriver_args=[("-type",Arg.String(funtype_file->Mli.type_file:=Sometype_file),"FILE Load inferred types from FILE.");("-notype",Arg.Unit(fun()->Mli.type_file:=None)," Unset explicitly set path from which to load inferred types.");("-server-cmo",Arg.String(funfile->Cmo.file:=Somefile),"FILE Load inferred types from server cmo file FILE.");("-internal",Arg.Setis_internal," Use short module names (for compiling Eliom itself).");("-internal-prefix",Arg.String(funs->internal_prefix:=s),"PREFIX Strip PREFIX. wrapper prefix from .cmo type paths (for compiling wrapped libraries that depend on Eliom).")]let()=List.iter(fun(key,spec,doc)->Ppxlib.Driver.add_argkeyspec~doc)driver_args(** Signature of specific code of a preprocessor. *)moduletypePass=sig(** How to handle "client", "shared" and "server" sections for top level structure items. *)valshared_str:bool->structure_item->structure_itemlistvalserver_str:bool->structure_item->structure_itemlistvalclient_str:structure_item->structure_itemlist(** How to handle "client", "shared" and "server" sections for top level signature items. *)valshared_sig:signature_item->signature_itemlistvalclient_sig:signature_item->signature_itemlistvalserver_sig:signature_item->signature_itemlistvalfragment:loc:Location.t->?typ:core_type->context:Context.server->num:string->id:stringLocation.loc->unsafe:bool->expression->expression(** How to handle "[\%client ...]" and "[\%shared ...]" expr. *)valescape_inject:loc:Location.t->?ident:string->context:Context.escape_inject->id:stringLocation.loc->unsafe:bool->expression->expression(** How to handle escaped "~%ident" inside a fragment. *)valprelude:loc->structurevalpostlude:loc->structureend(** These functions try to guess if a given expression will lead to a fragment evaluation
This is not possible in general, this criteria is only syntactic
If the expression cannot have fragments, we don't need to use sections.
Consequently, this function should *never* return false positive.
*)moduleCannot_have_fragment=structletopt_forallp=functionNone->true|Somex->pxletvb_forallpl=letpx=px.pvb_exprinList.for_allplletreclongident=function|Longident.Lident_->true|Longident.Ldot(x,_)->longidentx|Longident.Lapply(_,_)->falseletrecexpressione=matche.pexp_descwith|Pexp_ident_|Pexp_constant_|Pexp_function_|Pexp_lazy_->true|((Pexp_fun_)[@ifast_version<502])->true|Pexp_newtype(_,e)|Pexp_asserte|Pexp_field(e,_)|Pexp_constraint(e,_)|Pexp_coerce(e,_,_)|Pexp_poly(e,_)|Pexp_try(e,_)->expressione|Pexp_ifthenelse(b,e1,e2)->expressionb&&expressione1&&opt_forallexpressione2|Pexp_sequence(e1,e2)|Pexp_setfield(e1,_,e2)->expressione1&&expressione2|Pexp_arrayl|Pexp_tuplel->List.for_allexpressionl|Pexp_record(l,e)->letpx=expression@@sndxinopt_forallexpressione&&List.for_allpl|Pexp_construct(_,e)|Pexp_variant(_,e)->opt_forallexpressione|Pexp_let(_,l,e)->vb_forallexpressionl&&expressione|Pexp_open(i,e)->module_expri.popen_expr&&expressione|Pexp_letmodule(_,me,e)->module_exprme&&expressione(* We could be more precise on those constructs *)|Pexp_object_|Pexp_while_|Pexp_for_|Pexp_match_|Pexp_pack_->false(* We can't say more using syntactic information. *)|Pexp_extension_|Pexp_send_|Pexp_new_|Pexp_setinstvar_|Pexp_override_|Pexp_apply_|_->falseandmodule_exprx=matchx.pmod_descwith|Pmod_identl->longidentl.txt|Pmod_functor_->true|Pmod_unpacke->expressione|Pmod_constraint(e,_)->module_expre|Pmod_structurel->List.for_allstructure_iteml|Pmod_apply_|_->falseandmodule_bindingm=module_exprm.pmb_exprandstructure_itemx=matchx.pstr_descwith|Pstr_type_|Pstr_typext_|Pstr_exception_|Pstr_modtype_|Pstr_class_|Pstr_class_type_->true|Pstr_eval(e,_)->expressione|Pstr_value(_,vb)->vb_forallexpressionvb|Pstr_primitive_->true|Pstr_modulemb->module_bindingmb|Pstr_recmodulembl->List.for_allmodule_bindingmbl|Pstr_openx->module_exprx.popen_expr|Pstr_includex->module_exprx.pincl_mod|_->falseend(**
Replace shared expression by the equivalent pair.
[ [%share
let x = ... %s ... in
[%client ... %x ... ]
] ]
≡
[ let x = ... s ... in
[%client ... %x ... ]
,
[%client
let x = ... %s ... in
... x ...
]
]
*)moduleShared=structletserver=objectinheritPpxlib.Ast_traverse.mapassupermethod!expressionexpr=matchexprwith|[%expr[%client[%e?_]]]->expr|[%expr[%client.unsafe[%e?_]]]->expr|[%expr~%[%e?injection_expr]]->injection_expr|_->super#expressionexprend#expressionletclientexpr=letcontext=ref`Topinobject(self)inheritPpxlib.Ast_traverse.mapassupermethod!expressionexpr=matchexprwith|[%expr[%client[%e?fragment_expr]]]|[%expr[%client.unsafe[%e?fragment_expr]]]->in_contextcontext`Fragmentself#expressionfragment_expr|[%expr~%[%e?injection_expr]]->(match!contextwith`Top->expr|`Fragment->injection_expr)|_->super#expressionexprend#expressionexprletexprloc~unsafeexpr=letserver_expr=serverexprinletclient_expr=clientexprinletshared_create=Exp.ident~loc{loc;txt=eliom_lid"Shared.Value.create"}inifunsafethen[%expr[%eshared_create][%eserver_expr][%client.unsafe[%eclient_expr]]]else[%expr[%eshared_create][%eserver_expr][%client[%eclient_expr]]]endmoduleMake(Pass:Pass)=structleteliom_mappercontext=letcontext=ref(context:>Context.t)inobject(self)inheritPpxlib.Ast_traverse.mapassupermethod!expressionexpr=letloc=expr.pexp_locinletattr=expr.pexp_attributesinmatchexpr,!contextwith|{pexp_desc=Pexp_extension({txt;_},_);_},`Clientwhenis_annotationtxt["client";"shared";"client.unsafe";"shared.unsafe"]->letside=get_extensionexprinExp.extension@@Location.Error.to_extension@@Location.Error.make~loc~sub:[](Printf.sprintf"The syntax [%%%s ...] is not allowed inside client code."side)|({pexp_desc=Pexp_extension({txt;_},_);_},(`Fragment_|`Escaped_value_|`Injection_))whenis_annotationtxt["client";"shared";"client.unsafe";"shared.unsafe"]->letside=get_extensionexprinExp.extension@@Location.Error.to_extension@@Location.Error.make~loc~sub:[](Printf.sprintf"The syntax [%%%s ...] can not be nested."side)(* [%shared ... ] *)|({pexp_desc=Pexp_extension({txt;_},PStr[{pstr_desc=Pstr_eval(side_val,attr');_}]);_},(`Server|`Shared))whenis_annotationtxt["shared";"shared.unsafe"]->letunsafe=is_annotationtxt["shared.unsafe"]inlete=Shared.exprloc~unsafeside_valinself#expression@@exp_add_attrs(attr@attr')e(* [%client ... ] *)|({pexp_desc=Pexp_extension({txt;_},PStr[{pstr_desc=Pstr_eval(side_val,attr);_}]);_},((`Server|`Shared)asc))whenis_annotationtxt["client";"client.unsafe"]->Name.reset_escaped_ident();letside_val,typ=matchside_valwith|[%expr([%e?cval]:[%t?typ])]->cval,Sometyp|_->side_val,Noneinletnum=Name.fragment_numside_val.pexp_locinletid=mkloc(Name.fragment_identnum)side_val.pexp_locinletunsafe=is_annotationtxt["client.unsafe"]inin_contextcontext(`Fragment(c,unsafe))(Pass.fragment~loc?typ~context:c~num~id~unsafe%self#expression)(exp_add_attrsattrside_val)(* ~%( ... ) ] *)|[%expr~%[%e?inj]],_->(letident=matchinj.pexp_descwith|Pexp_identi->Some(String.concat"_"@@Longident.flatten_exni.txt)|_->Noneinmatch!contextwith|(`Client|`Shared)asc->letid=matchidentwith|Someid->Name.injected_identlocid|None->Name.injected_exprlocinletnew_context=`Injectioncinin_contextcontextnew_context(Pass.escape_inject~loc?ident~context:new_context~id~unsafe:false%self#expression)inj|`Fragment(c,unsafe)->letid=matchidentwith|None->Name.escaped_exprloc|Someid->Name.escaped_identlocidinletnew_context=`Escaped_valuecinin_contextcontextnew_context(Pass.escape_inject~loc?ident~context:new_context~id~unsafe%self#expression)inj|`Server->Location.raise_errorf~loc"The syntax ~%% ... is not allowed inside server code."|`Escaped_value_|`Injection_->Location.raise_errorf~loc"The syntax ~%% ... can not be nested.")|_->super#expressionexprmethod!structure_itemstr=letloc=str.pstr_locinmatchstr.pstr_descwith|Pstr_extension(({txt="server"|"shared"|"client";_},_),_)->Location.raise_errorf~loc"Sections are only allowed at toplevel."|_->super#structure_itemstrmethod!signature_itemsig_=letloc=sig_.psig_locinmatchsig_.psig_descwith|Psig_extension(({txt="server"|"shared"|"client";_},_),_)->Location.raise_errorf~loc"Sections are only allowed at toplevel."|_->super#signature_itemsig_end(** Toplevel translation *)(** Switch the current context when encountering [%%server] (resp. shared, client)
annotations. Call the eliom mapper and [Pass.server_str] (resp ..) on each
structure item.
*)letdispatch_strcontextstri=(* We must do this before any transformation on the structure. *)letno_fragment=Cannot_have_fragment.structure_itemstriinletf=matchcontextwith|`Server->Pass.server_strno_fragment|`Shared->Pass.shared_strno_fragment|`Client->Pass.client_strinletm=eliom_mappercontextinf@@m#structure_itemstriletdispatch_sigcontextsigi=letf=matchcontextwith|`Server->Pass.server_sig|`Shared->Pass.shared_sig|`Client->Pass.client_siginletm=eliom_mappercontextinf@@m#signature_itemsigiletempty_sectiontxt=Printf.sprintf"Empty [%%%%%s] extension. Did you mean [%%%%%s.start] ?"txttxtlettoplevel_structurecontextstructs=letrecfpstr=letloc=pstr.pstr_locandmaybe_reset_injected_idents=function|`Client|`Shared->Name.reset_injected_ident()|_->()inmatchpstr.pstr_descwith|Pstr_extension(({txt;_},PStrstrs),_)whenis_annotationtxt["shared.start";"client.start";"server.start"]->ifstrs<>[]then[Str.extension~loc@@Location.Error.to_extension@@Location.Error.make~loc~sub:[](Printf.sprintf"The %%%%%s extension doesn't accept arguments."txt)]else(maybe_reset_injected_idents!context;context:=Context.of_stringtxt;[])|Pstr_extension(({txt;_},PStrstrs),_)whenis_annotationtxt["shared";"client";"server"]->ifstrs=[]then[Str.extension~loc@@Location.Error.to_extension@@Location.Error.make~loc~sub:[](empty_sectiontxt)]elseletc=Context.of_stringtxtinletl=List.concat_map(dispatch_strc)strsinmaybe_reset_injected_identsc;l|Pstr_include{pincl_mod={pmod_desc=Pmod_structurel;pmod_attributes=[];_};pincl_attributes=[];_}->List.concat_mapfl|_->dispatch_str!contextpstrinletloc={(file_positionstructs)withloc_ghost=true}in(module_hash_declarationloc::Pass.preludeloc)@List.concat_mapfstructs@Pass.postludeloclettoplevel_signaturecontextsigs=letfpsig=letloc=psig.psig_locinmatchpsig.psig_descwith|Psig_extension(({txt;_},PStrstrs),_)whenis_annotationtxt["shared.start";"client.start";"server.start"]->ifstrs<>[]then[Sig.extension~loc@@Location.Error.to_extension@@Location.Error.make~loc~sub:[](Printf.sprintf"The %%%%%s extension doesn't accept arguments."txt)]else(context:=Context.of_stringtxt;[])|Psig_extension(({txt;_},PSigsigs),_)whenis_annotationtxt["shared";"client";"server"]->letc=Context.of_stringtxtinList.concat_map(dispatch_sigc)sigs|Psig_extension(({txt;_},PStrstrs),_)whenis_annotationtxt["shared";"client";"server"]->letmsg=ifstrs=[]thenempty_sectiontxtelsePrintf.sprintf"In an interface, a section takes a signature: [%%%%%s: ...]."txtin[Sig.extension~loc@@Location.Error.to_extension@@Location.Error.make~loc~sub:[]msg]|_->dispatch_sig!contextpsiginList.concat_mapfsigsletmapper=letc=ref`ServerinobjectinheritPpxlib.Ast_traverse.mapmethod!structures=matchswith(* An empty file has no location to inspect, and transforming it
would only inject a useless preamble: leave it untouched. *)|[]->s|{pstr_loc;_}::_whenis_plain_ocamlpstr_loc.loc_start.pos_fname->s|_->toplevel_structurecsmethod!signatures=matchswith|[]->s|{psig_loc;_}::_whenis_plain_ocamlpsig_loc.loc_start.pos_fname->s|_->toplevel_signaturecsendend