text
stringlengths
0
601k
let cell cell = string ( Symbol . print false ( symbol cell ) ) ^^ slash ^^ bit ( holds_state cell )
let sharpcell c = space ^^ at ^^ space ^^ cell c
let final final = match final with | None -> string " < undetermined " > | Some nt -> string ( Nonterminal . print false nt )
let cells cells = cells |> to_list |> map cell |> separate space
let block_type bty = nl ^^ string " #### Stack : " ^^ cells bty . stack ^^ nl ^^ string " #### Final : " ^^ final bty . final
let states states = string " #### States " : ^^ Tag . Map . fold ( fun t bty doc -> nl ^^ string " | State " ^^ tag t ^^ nest 2 ( block_type bty ) ^^ doc ) states nl ^^ nl
let pattern p = match p with | PWildcard -> underscore | PReg r -> register r
let patterns ps = OCaml . tuple ( map pattern ps )
let primitive prim = match prim with | PrimLexerCall [ lexer ; lexbuf ] -> value lexer ^^ parens ( value lexbuf ) | PrimLexerCall _ -> assert false | PrimOCamlFieldAccess ( v , f ) -> value v ^^ dot ^^ string f | PrimOCamlAction ( bs , _prod , _action ) -> if Bindings . is_empty bs then string " < semantic action " > e...
let trace s = OCaml . string s
let tok_single tok r = utf8format " % s % s " ( Terminal . print tok ) ( Reg . export r )
let tok_wildcard tok = utf8format " % s _ " ( Terminal . print tok )
let tokpat pat = match pat with | TokSingle ( tok , r ) -> tok_single tok r | TokMultiple toks -> toks |> TerminalSet . elements |> map tok_wildcard |> flow ( break 1 ^^ bar ^^ space )
let tagpat ( TagSingle t ) = tag t
let branch ( guard , body ) = nl ^^ bar ^^ space ^^ guard ^^ string " " -> ^^ nest 4 body
let registers rs = let rs = Reg . Set . elements rs in align ( flow ( comma ^^ break 1 ) ( map register rs ) )
let needed rs = nl ^^ string " #### Needs : " ^^ registers rs
let rec typed_block tblock = block_type tblock . block_type ^^ needed tblock . needed ^^ block tblock . block match b with | IPush ( vs , c , _ ) -> string " PUSH " ^^ values vs ^^ sharpcell c | IPop ( ps , c , _ ) -> string " POP " ^^ patterns ps ^^ sharpcell c | IPeek ( ps , c , _ ) -> string " PEEK " ^^ patterns ps ...
let entry_comment entry l = match Label . Map . find l entry with | nt -> utf8format " #### Entry point for the start symbol % s " nt ^^ nl | exception Not_found -> empty
let routine entry ( l , tblock ) = entry_comment entry l ^^ label l ^^ colon ^^ nest 2 ( typed_block tblock ) ^^ nl ^^ nl
let reverse ( m : label StringMap . t ) : string Label . Map . t = StringMap . fold ( fun k x accu -> Label . Map . add x k accu ) m Label . Map . empty
let cfg program = program . cfg |> Label . Map . bindings |> map ( routine ( reverse program . entry ) ) |> concat
let program program = states program . states ^^ cfg program
module ToChannel = struct type ' a printer = out_channel -> ' a -> unit let to_channel f channel x = let doc = f x in ToChannel . pretty rfrac width channel doc let instruction = to_channel instruction let block = to_channel block let typed_block = to_channel typed_block let states = to_channel states let program = to_...
module ToString = struct type ' a printer = ' a -> string let to_string f x = let doc = f x in let buffer = Buffer . create 32 in ToBuffer . pretty rfrac width buffer doc ; Buffer . contents buffer let final = to_string final let values = to_string values let patterns = to_string patterns end
type outcome = | Accepted | Rejected | Overshoot | Crash of exn | TraceTooLong of int
let print_outcome = function | Accepted -> " accepts this sentence " | Rejected -> " rejects this sentence " | Overshoot -> " reads past the end of the input stream " | Crash e -> sprintf " fails ( % s ) " ( Printexc . to_string e ) | TraceTooLong bound -> sprintf " logs more than % d lines " bound
let run_reference nt sentence : outcome * int = let lexer , lexbuf = Interpret . stream sentence in let count = ref 0 in let module Log = Logging . Make ( struct let show = Settings . trace let count = count end ) in let log = ( module Log : Logging . LOG ) in let outcome = match ReferenceInterpreter . interpret nt log...
let run_candidate candidate bound sentence : outcome * int = let lexer , lexbuf = Interpret . stream sentence in let count = ref 0 in let log s = if Settings . trace then prerr_string s ; incr count ; if bound < ! count then raise BoundExceeded in let outcome = match candidate log lexer lexbuf with | StackLangInterpret...
let test m program nt sentence = if debug then eprintf " StackLangTester : About to test this sentence :\ n % s " %! ( Sentence . print ` Abstract ( Some nt , sentence ) ) ; if debug then eprintf " StackLangTester : Running the reference interpreter . . . \ n " ; %! let reference , bound = run_reference nt sentence in ...
let k , threshold = ( 2 , 10000 )
let test program nt = if debug then eprintf " StackLangTester : about to test start symbol % s . . . \ n " %! ( Nonterminal . print false nt ) ; let m = StackLangMeasure . zero ( ) in let count , size = ref 0 , ref 10 in let prev = ref ! size in let total = ref 0 in while ! size < threshold do for _ = 1 to k do let sen...
let test program = Lr1 . entry |> ProductionMap . iter begin fun _prod s -> let nt = Lr1 . nt_of_entry s in test program nt end ; Time . tick " Testing the StackLang program "
module P = struct include Grammar . TerminalSet let diff xs ys = fold remove ys xs type property = t let leq_join = union end
let rec exec ( jump : label -> env -> unit ) env block = match block with | IPrim ( p , PrimLexerCall _ , block ) -> assert ( p = PReg token ) ; let env = P . universe in exec jump env block | IJump label -> jump label env | ICaseToken ( r , branches , odefault ) -> assert ( r = token ) ; List . iter ( exec_tokbranch j...
let analyze program : label -> env option = let module G = struct type variable = label type property = env let foreach_root jump = program . entry |> StringMap . iter begin fun _name label -> jump label P . empty end let foreach_successor label env jump = let block = ( lookup program label ) . block in exec jump env b...
let no_assigns tokpat = match tokpat with | TokSingle ( _tok , _r ) -> false | TokMultiple _toks -> true
let make_exhaustive branches odefault = if exhaustive branches then begin assert ( odefault = None ) ; odefault end else match odefault with | Some _ -> odefault | None -> Some ( IDead ` Dynamic )
let comment env block = let msg = if P . is_singleton env then sprintf " The current token is % s . " ( P . print env ) else let c = P . cardinal env in if c <= threshold then sprintf " The current token is among % s . " ( P . print env ) else sprintf " The current token is among a set of cardinality % d ( not shown ) ...
let rec map env block : block = match block with | ICaseToken ( r , branches , odefault ) -> map_casetok env r branches odefault | IPrim ( p , PrimLexerCall vs , block ) -> let env = P . universe in IPrim ( p , PrimLexerCall vs , map env block ) | IPush _ | IPop _ | IPeek _ | IDef _ | IPrim _ | ITrace _ | IComment _ | ...
let map_tblock env tblock = { tblock with block = map env tblock . block }
let transform program : program = let analysis : label -> env option = analyze program in let cfg = Label . Map . mapi ( fun label tblock -> match analysis label with | Some env -> map_tblock env tblock | None -> tblock ) program . cfg in Time . tick " StackLang : simplifying case analyses on the current token " ; { pr...
let map , length = List . ( map , length )
let take , drop = MList . ( take , drop )
let no_info format = ikfprintf ( fun ( ) x -> x ) ( ) format
let info = if decorate then fun format -> ksprintf ( fun s block -> IComment ( s , block ) ) format else no_info
let kinfo = if decorate then fun format -> ksprintf ( fun s ( x , y , block ) -> x , y , IComment ( s , block ) ) format else no_info
let cells i = match i with | 0 -> " 0 cell " | 1 -> " 1 cell " | _ -> sprintf " % d cells " i
module Specialize ( X : sig val program : program end ) = struct open X
let can_specialize label = let tblock = lookup program label in match tblock . spec with | SpecAllowed -> Reg . Set . mem state tblock . needed | SpecDisallowed -> false
let can_inline_when_known_state label = let tblock = lookup program label in match tblock . hint with | Always | OnlyIfKnownState | IfCells 0 -> true | IfCells _ | NoHint -> false
let can_inline_when_known_stack label = let tblock = lookup program label in match tblock . hint with | Always | IfCells 1 -> true | IfCells _ | OnlyIfKnownState | NoHint -> false
let cfg = ref Label . Map . empty
let queue : ( label * tag ) Queue . t = Queue . create ( )
module LTSet = Set . Make ( struct type t = label * tag let compare ( label1 , tag1 ) ( label2 , tag2 ) = let c = Label . compare label1 label2 in if c <> 0 then c else Tag . compare tag1 tag2 end )
let inserted = ref LTSet . empty
let labels = ref Label . Set . empty
let enqueue label tag = let pair = ( label , tag ) in if not ( LTSet . mem pair ! inserted ) then begin Queue . add pair queue ; inserted := LTSet . add pair ! inserted ; labels := Label . Set . add label ! labels end
let spec_label label tag : label = sprintf " % s_spec_ % s " ( Label . export label ) ( print tag ) |> Label . import
let spec_block_type tag block_type = let tag_type = invariant program tag in match Invariant . meet block_type . stack tag_type . stack , Final . lub block_type . final tag_type . final with | Some stack , Some final -> { stack ; final } | None , _ | _ , None -> assert false
type env = { stack : tag option ; state : tag option ; incasetag : bool ; }
let print_tag_option otag = match otag with | None -> " < unknown " > | Some tag -> Tag . print tag
let print_env env = sprintf " stack : % s ; state : % s " ( print_tag_option env . stack ) ( print_tag_option env . state )
let apply env v = match env . state with | None -> v | Some tag -> let bs = Bindings . assign [ PReg state ] [ VTag tag ] in Bindings . apply bs v
let materialize env block = match env . state , env . incasetag with | None , _ | _ , true -> block | Some tag , false -> let bs = Bindings . assign [ PReg state ] [ VTag tag ] in Block . def bs block
let rec spec_block env block = match block with | IPush ( vs , cell , block ) -> let env , vs = if Value . occurs state vs then begin assert ( Invariant . holds_state cell ) ; assert ( vs <> [ ] && List . hd vs = VReg state ) ; { env with stack = env . state } , map ( apply env ) vs end else { env with stack = None } ,...
let spec_tblock tag tblock = assert ( Reg . Set . mem state tblock . needed ) ; let env = { stack = None ; state = Some tag ; incasetag = false } in let block = spec_block env tblock . block in let block = IDef ( Bindings . assign [ PReg state ] [ VTag tag ] , block ) in let needed = Reg . Set . remove state tblock . n...
let spec_routine ( label , tag ) = let block = spec_tblock tag ( lookup program label ) in cfg := Label . Map . add ( spec_label label tag ) block ! cfg
let inspect_tblock tblock = let env = { stack = None ; state = None ; incasetag = false } in let block = spec_block env tblock . block in { tblock with block }
let inspect_routine _label tblock = inspect_tblock tblock
let program = cfg := Label . Map . mapi inspect_routine program . cfg ; Misc . qiter spec_routine queue ; { program with cfg = ! cfg }
let ( ) = Error . logC 1 ( fun f -> fprintf f " % d specialized copies of % d functions have been created . \ n " ( LTSet . cardinal ! inserted ) ( Label . Set . cardinal ! labels ) )
let specialize program = let module S = Specialize ( struct let program = program end ) in Time . tick " StackLang : specialization " ; S . program
module CommutePushes ( X : sig val program : program end ) = struct open X
let discovered : Label . Set . t ref = ref Label . Set . empty
let waiting : label Queue . t = Queue . create ( )
let discover label = if not ( Label . Set . mem label ! discovered ) then begin discovered := Label . Set . add label ! discovered ; Queue . add label waiting end
type wagon = values * cell
type train = wagon list
let rec pushes_vanish block = match block with | IDead _ | IStop _ -> true | IComment ( _ , block ) | IDef ( _ , block ) | IPush ( _ , _ , block ) | ITrace ( _ , block ) -> pushes_vanish block | _ -> false
let materialize ( pushes : train ) block = if pushes_vanish block then info " ( optm ) Some push instructions have vanished here " block else List . fold_left ( fun block ( vs , cell ) -> info " ( optm ) Re - materializing push " ( IPush ( vs , cell , block ) ) ) block pushes
let occurs_in_wagon r wagon = let ( vs , _cell ) = wagon in Value . occurs r vs
let occurs_in_train r wagons = List . exists ( occurs_in_wagon r ) wagons
let current_state_is_known bs = match Bindings . apply bs ( VReg state ) with | VTag _ -> true | VReg _ -> false | _ -> assert false
type env = { path : Label . Set . t ; pushes : train ; bs : bindings ; fresh : unit -> int ; }
let rename env ( r : register ) : register = Reg . import ( sprintf " % s_ % d " ( Reg . export r ) ( env . fresh ( ) ) )
let transform_assignment_to_reg env r = if occurs_in_train r env . pushes then let r ' = rename env r in let bs ' = Bindings . ( seq env . bs ( assign [ PReg r ] [ VReg r ' ] ) ) in { env with bs = bs ' } , r ' else let bs = Bindings . remove env . bs ( Reg . Set . singleton r ) in let env = { env with bs } in env , r
let transform_assignment_to_pat env p = match p with | PReg r -> let env , r = transform_assignment_to_reg env r in env , PReg r | PWildcard -> env , p
let transform_assignment_to_tokpat env tokpat = match tokpat with | TokSingle ( tok , r ) -> let env , r = transform_assignment_to_reg env r in env , TokSingle ( tok , r ) | TokMultiple _ -> env , tokpat
let do_not_transform_block env block : int * int * block = Block . successors discover block ; 0 , 0 , IDef ( env . bs , block )
let rec transform_block env block : int * int * block = match block with | IPush ( _vs , _cell , block ) when pushes_vanish block -> kinfo " ( optm ) Some push instructions have vanished here " ( do_not_transform_block env block ) | IPush ( vs , cell , block ) -> let vs = map ( Bindings . apply env . bs ) vs in let wag...
let transform_tblock label tblock = let path = Label . Set . singleton label in let pushes = [ ] and bs = Bindings . empty and fresh = Misc . mkgensym ( ) in let env = { path ; pushes ; bs ; fresh } in let k , _happiness , block = transform_block env tblock . block in assert ( k = 0 ) ; { tblock with block }
let program = let cfg = ref Label . Map . empty in program . entry |> StringMap . iter begin fun _ label -> discover label end ; waiting |> Misc . qiter begin fun label -> assert ( Label . Set . mem label ! discovered ) ; assert ( not ( Label . Map . mem label ! cfg ) ) ; let tblock = lookup program label in let tblock...
let commute_pushes program = let module CP = CommutePushes ( struct let program = program end ) in Time . tick " StackLang : moving PUSHes " ; CP . program
let in_degree program = let queue : label Queue . t = Queue . create ( ) and degree : int Label . Map . t ref = ref Label . Map . empty in let tick incasetag label = let d = try Label . Map . find label ! degree with Not_found -> Queue . add label queue ; 0 in let delta = if incasetag then 2 else 1 in degree := Label ....
let remove_unreachable_blocks program = let degree = in_degree program in let cfg = Label . Map . fold ( fun label block accu -> if Label . Map . mem label degree then Label . Map . add label block accu else accu ) program . cfg Label . Map . empty in Time . tick " StackLang : removing unreachable blocks " ; { program ...
module Inline ( X : sig val cautious : bool val program : program
let degree = in_degree program
let discovered : Label . Set . t ref = ref Label . Set . empty
let waiting : label Queue . t = Queue . create ( )