src/Tools/Code/code_namespace.ML
author haftmann
Fri May 02 21:18:50 2014 +0200 (2014-05-02)
changeset 56826 ba18bd41e510
parent 55776 7dd1971b39c1
child 57428 47c8475e7864
permissions -rw-r--r--
enforce case of identifiers only to accomodate strict language requirements (or clear separation of constructors from variables in the case of SML)
     1 (*  Title:      Tools/Code/code_namespace.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Mastering target language namespaces.
     5 *)
     6 
     7 signature CODE_NAMESPACE =
     8 sig
     9   datatype export = Private | Opaque | Public
    10   val is_public: export -> bool
    11   val not_private: export -> bool
    12   val join_exports: export list -> export
    13 
    14   type flat_program
    15   val flat_program: Proof.context
    16     -> { module_prefix: string, module_name: string,
    17     reserved: Name.context, identifiers: Code_Target.identifier_data, empty_nsp: 'a,
    18     namify_stmt: Code_Thingol.stmt -> string -> 'a -> string * 'a,
    19     modify_stmt: Code_Thingol.stmt -> Code_Thingol.stmt option }
    20       -> Code_Symbol.T list -> Code_Thingol.program
    21       -> { deresolver: string -> Code_Symbol.T -> string,
    22            flat_program: flat_program }
    23 
    24   datatype ('a, 'b) node =
    25       Dummy
    26     | Stmt of export * 'a
    27     | Module of ('b * (string * ('a, 'b) node) Code_Symbol.Graph.T)
    28   type ('a, 'b) hierarchical_program
    29   val hierarchical_program: Proof.context
    30     -> { module_name: string,
    31     reserved: Name.context, identifiers: Code_Target.identifier_data,
    32     empty_nsp: 'c, namify_module: string -> 'c -> string * 'c,
    33     namify_stmt: Code_Thingol.stmt -> string -> 'c -> string * 'c,
    34     cyclic_modules: bool,
    35     class_transitive: bool, class_relation_public: bool,
    36     empty_data: 'b, memorize_data: Code_Symbol.T -> 'b -> 'b,
    37     modify_stmts: (Code_Symbol.T * (export * Code_Thingol.stmt)) list -> (export * 'a) option list }
    38       -> Code_Symbol.T list -> Code_Thingol.program
    39       -> { deresolver: string list -> Code_Symbol.T -> string,
    40            hierarchical_program: ('a, 'b) hierarchical_program }
    41   val print_hierarchical: { print_module: string list -> string -> 'b -> 'c list -> 'c,
    42     print_stmt: string list -> Code_Symbol.T * (export * 'a) -> 'c,
    43     lift_markup: (Pretty.T -> Pretty.T) -> 'c -> 'c }
    44       -> ('a, 'b) hierarchical_program -> 'c list
    45 end;
    46 
    47 structure Code_Namespace : CODE_NAMESPACE =
    48 struct
    49 
    50 (** export **)
    51 
    52 datatype export = Private | Opaque | Public;
    53 
    54 fun is_public Public = true
    55   | is_public _ = false;
    56 
    57 fun not_private Public = true
    58   | not_private Opaque = true
    59   | not_private _ = false;
    60 
    61 fun mark_export Public _ = Public
    62   | mark_export _ Public = Public
    63   | mark_export Opaque _ = Opaque
    64   | mark_export _ Opaque = Opaque
    65   | mark_export _ _ = Private;
    66 
    67 fun join_exports exports = fold mark_export exports Private;
    68 
    69 fun dependent_exports { program = program, class_transitive = class_transitive } =
    70   let
    71     fun is_datatype_or_class (Code_Symbol.Type_Constructor _) = true
    72       | is_datatype_or_class (Code_Symbol.Type_Class _) = true
    73       | is_datatype_or_class _ = false;
    74     fun is_relevant (Code_Symbol.Class_Relation _) = true
    75       | is_relevant sym = is_datatype_or_class sym;
    76     val proto_gr = Code_Symbol.Graph.restrict is_relevant program;
    77     val gr =
    78       proto_gr
    79       |> Code_Symbol.Graph.fold
    80           (fn (sym, (_, (_, deps))) =>
    81             if is_relevant sym
    82             then I
    83             else
    84               Code_Symbol.Graph.new_node (sym, Code_Thingol.NoStmt)
    85               #> Code_Symbol.Graph.Keys.fold
    86                (fn sym' =>
    87                 if is_relevant sym'
    88                 then Code_Symbol.Graph.add_edge (sym, sym')
    89                 else I) deps) program
    90       |> class_transitive ?
    91           Code_Symbol.Graph.fold (fn (sym as Code_Symbol.Type_Class _, _) =>
    92             fold (curry Code_Symbol.Graph.add_edge sym)
    93               ((remove (op =) sym o Code_Symbol.Graph.all_succs proto_gr) [sym]) | _ => I) proto_gr
    94     fun deps_of sym =
    95       let
    96         val succs = Code_Symbol.Graph.Keys.dest o Code_Symbol.Graph.imm_succs gr;
    97         val deps1 = succs sym;
    98         val deps2 = [] |> fold (union (op =)) (map succs deps1) |> subtract (op =) deps1
    99       in (deps1, deps2) end;
   100   in
   101     { is_datatype_or_class = is_datatype_or_class,
   102       deps_of = deps_of }
   103   end;
   104 
   105 fun mark_exports_aux { program = program, prefix_of = prefix_of, map_export = map_export,
   106     is_datatype_or_class = is_datatype_or_class, deps_of = deps_of,
   107     class_relation_public = class_relation_public } prefix sym =
   108   let
   109     val export = (if is_datatype_or_class sym then Opaque else Public);
   110     val (dependent_export1, dependent_export2) =
   111       case Code_Symbol.Graph.get_node program sym of
   112           Code_Thingol.Fun _ => (SOME Opaque, NONE)
   113         | Code_Thingol.Classinst _ => (SOME Opaque, NONE)
   114         | Code_Thingol.Datatypecons _ => (SOME Public, SOME Opaque)
   115         | Code_Thingol.Classparam _ => (SOME Public, SOME Opaque)
   116         | Code_Thingol.Class _ => (SOME Opaque, NONE)
   117         | Code_Thingol.Classrel _ =>
   118            (if class_relation_public
   119             then (SOME Public, SOME Opaque)
   120             else (SOME Opaque, NONE))
   121         | _ => (NONE, NONE);
   122     val dependent_exports =
   123       case dependent_export1 of
   124         SOME export1 => (case dependent_export2 of
   125           SOME export2 =>
   126             let
   127               val (deps1, deps2) = deps_of sym
   128             in map (rpair export1) deps1 @ map (rpair export2) deps2 end
   129         | NONE => map (rpair export1) (fst (deps_of sym)))
   130       | NONE => [];
   131   in 
   132     map_export prefix sym (mark_export export)
   133     #> fold (fn (sym, export) => map_export (prefix_of sym) sym (mark_export export))
   134       dependent_exports
   135   end;
   136 
   137 fun mark_exports { program = program, prefix_of = prefix_of, map_export = map_export,
   138     class_transitive = class_transitive, class_relation_public = class_relation_public } =
   139   let
   140     val { is_datatype_or_class, deps_of } =
   141       dependent_exports { program = program, class_transitive = class_transitive };
   142   in
   143     mark_exports_aux { program = program, prefix_of = prefix_of, map_export = map_export,
   144       is_datatype_or_class = is_datatype_or_class, deps_of = deps_of,
   145       class_relation_public = class_relation_public }
   146   end;
   147 
   148 
   149 (** fundamental module name hierarchy **)
   150 
   151 fun module_fragments' { identifiers, reserved } name =
   152   case Code_Symbol.lookup_module_data identifiers name of
   153       SOME (fragments, _) => fragments
   154     | NONE => map (fn fragment => fst (Name.variant fragment reserved)) (Long_Name.explode name);
   155 
   156 fun module_fragments { module_name, identifiers, reserved } =
   157   if module_name = ""
   158   then module_fragments' { identifiers = identifiers, reserved = reserved }
   159   else K (Long_Name.explode module_name);
   160 
   161 fun build_module_namespace ctxt enforce_upper { module_prefix, module_name, identifiers, reserved } program =
   162   let
   163     val module_names = Code_Symbol.Graph.fold (insert (op =) o Code_Symbol.default_prefix ctxt o fst) program [];
   164     val module_fragments' = module_fragments
   165       { module_name = module_name, identifiers = identifiers, reserved = reserved };
   166     val adjust_case = if enforce_upper then map (Name.enforce_case true) else I;
   167   in
   168     fold (fn name => Symtab.update (name, adjust_case (Long_Name.explode module_prefix @ module_fragments' name)))
   169       module_names Symtab.empty
   170   end;
   171 
   172 fun prep_symbol ctxt { module_namespace, force_module, identifiers } sym =
   173   case Code_Symbol.lookup identifiers sym of
   174       NONE => ((the o Symtab.lookup module_namespace o Code_Symbol.default_prefix ctxt) sym,
   175         Code_Symbol.default_base sym)
   176     | SOME prefix_name => if null force_module then prefix_name
   177         else (force_module, snd prefix_name);
   178 
   179 fun has_priority identifiers = is_some o Code_Symbol.lookup identifiers;
   180 
   181 fun build_proto_program { empty, add_stmt, add_dep } program =
   182   empty
   183   |> Code_Symbol.Graph.fold (fn (sym, (stmt, _)) => add_stmt sym stmt) program
   184   |> Code_Symbol.Graph.fold (fn (sym, (_, (_, syms))) =>
   185       Code_Symbol.Graph.Keys.fold (add_dep sym) syms) program;
   186 
   187 fun prioritize has_priority = uncurry append o List.partition has_priority;
   188 
   189 
   190 (** flat program structure **)
   191 
   192 type flat_program = ((string * (export * Code_Thingol.stmt) option) Code_Symbol.Graph.T * (string * Code_Symbol.T list) list) Graph.T;
   193 
   194 fun flat_program ctxt { module_prefix, module_name, reserved,
   195     identifiers, empty_nsp, namify_stmt, modify_stmt } exports program =
   196   let
   197 
   198     (* building module name hierarchy *)
   199     val module_namespace = build_module_namespace ctxt true { module_prefix = module_prefix,
   200       module_name = module_name, identifiers = identifiers, reserved = reserved } program;
   201     val prep_sym = prep_symbol ctxt { module_namespace = module_namespace,
   202       force_module = Long_Name.explode module_name, identifiers = identifiers }
   203       #>> Long_Name.implode;
   204     val sym_priority = has_priority identifiers;
   205 
   206     (* distribute statements over hierarchy *)
   207     val mark_exports = mark_exports { program = program, prefix_of = fst o prep_sym,
   208       map_export = fn module_name => fn sym =>
   209         Graph.map_node module_name o apfst o Code_Symbol.Graph.map_node sym o apsnd o apfst,
   210         class_transitive = false, class_relation_public = false };
   211     fun add_stmt sym stmt =
   212       let
   213         val (module_name, base) = prep_sym sym;
   214       in
   215         Graph.default_node (module_name, (Code_Symbol.Graph.empty, []))
   216         #> (Graph.map_node module_name o apfst)
   217           (Code_Symbol.Graph.new_node (sym, (base, (if null exports then Public else Private, stmt))))
   218       end;
   219     fun add_dep sym sym' =
   220       let
   221         val (module_name, _) = prep_sym sym;
   222         val (module_name', _) = prep_sym sym';
   223       in if module_name = module_name'
   224         then (Graph.map_node module_name o apfst) (Code_Symbol.Graph.add_edge (sym, sym'))
   225         else (Graph.map_node module_name o apsnd)
   226           (AList.map_default (op =) (module_name', []) (insert (op =) sym'))
   227           #> mark_exports module_name' sym'
   228       end;
   229     val proto_program = build_proto_program
   230       { empty = Graph.empty, add_stmt = add_stmt, add_dep = add_dep } program
   231       |> fold (fn sym => mark_exports ((fst o prep_sym) sym) sym) exports;
   232 
   233     (* name declarations and statement modifications *)
   234     fun declare sym (base, (_, stmt)) (gr, nsp) = 
   235       let
   236         val (base', nsp') = namify_stmt stmt base nsp;
   237         val gr' = (Code_Symbol.Graph.map_node sym o apfst) (K base') gr;
   238       in (gr', nsp') end;
   239     fun declarations gr = (gr, empty_nsp)
   240       |> fold (fn sym => declare sym (Code_Symbol.Graph.get_node gr sym))
   241           (prioritize sym_priority (Code_Symbol.Graph.keys gr))
   242       |> fst
   243       |> Code_Symbol.Graph.map_strong_conn (fn syms_bases_exports_stmts =>
   244         map snd syms_bases_exports_stmts
   245         |> (map o apsnd) (fn (export, stmt) => Option.map (pair export) (modify_stmt stmt)));
   246     val flat_program = proto_program
   247       |> (Graph.map o K o apfst) declarations;
   248 
   249     (* qualified and unqualified imports, deresolving *)
   250     fun base_deresolver sym = fst (Code_Symbol.Graph.get_node
   251       (fst (Graph.get_node flat_program (fst (prep_sym sym)))) sym);
   252     fun classify_names gr imports =
   253       let
   254         val import_tab = maps
   255           (fn (module_name, syms) => map (rpair module_name) syms) imports;
   256         val imported_syms = map fst import_tab;
   257         val here_syms = Code_Symbol.Graph.keys gr;
   258       in
   259         Code_Symbol.Table.empty
   260         |> fold (fn sym => Code_Symbol.Table.update (sym, base_deresolver sym)) here_syms
   261         |> fold (fn sym => Code_Symbol.Table.update (sym,
   262             Long_Name.append (the (AList.lookup (op =) import_tab sym))
   263               (base_deresolver sym))) imported_syms
   264       end;
   265     val deresolver_tab = Symtab.make (AList.make
   266       (uncurry classify_names o Graph.get_node flat_program)
   267         (Graph.keys flat_program));
   268     fun deresolver "" sym =
   269           Long_Name.append (fst (prep_sym sym)) (base_deresolver sym)
   270       | deresolver module_name sym =
   271           the (Code_Symbol.Table.lookup (the (Symtab.lookup deresolver_tab module_name)) sym)
   272           handle Option.Option => error ("Unknown statement name: "
   273             ^ Code_Symbol.quote ctxt sym);
   274 
   275   in { deresolver = deresolver, flat_program = flat_program } end;
   276 
   277 
   278 (** hierarchical program structure **)
   279 
   280 datatype ('a, 'b) node =
   281     Dummy
   282   | Stmt of export * 'a
   283   | Module of ('b * (string * ('a, 'b) node) Code_Symbol.Graph.T);
   284 
   285 type ('a, 'b) hierarchical_program = (string * ('a, 'b) node) Code_Symbol.Graph.T;
   286 
   287 fun the_stmt (Stmt (export, stmt)) = (export, stmt);
   288 
   289 fun map_module_content f (Module content) = Module (f content);
   290 
   291 fun map_module [] = I
   292   | map_module (name_fragment :: name_fragments) =
   293       apsnd o Code_Symbol.Graph.map_node (Code_Symbol.Module name_fragment) o apsnd o map_module_content
   294         o map_module name_fragments;
   295 
   296 fun map_module_stmts f_module f_stmts sym_base_nodes =
   297   let
   298     val some_modules =
   299       sym_base_nodes
   300       |> map (fn (_, (base, Module content)) => SOME (base, content) | _ => NONE)
   301       |> (burrow_options o map o apsnd) f_module;
   302     val some_export_stmts =
   303       sym_base_nodes
   304       |> map (fn (sym, (base, Stmt export_stmt)) => SOME ((sym, export_stmt), base) | _ => NONE)
   305       |> (burrow_options o burrow_fst) (fn [] => [] | xs => f_stmts xs)
   306   in
   307     map2 (fn SOME (base, content) => (K (base, Module content))
   308       | NONE => fn SOME (some_export_stmt, base) =>
   309           (base, case some_export_stmt of SOME export_stmt => Stmt export_stmt | NONE => Dummy))
   310       some_modules some_export_stmts
   311   end;
   312 
   313 fun hierarchical_program ctxt { module_name, reserved, identifiers, empty_nsp,
   314       namify_module, namify_stmt, cyclic_modules,
   315       class_transitive, class_relation_public,
   316       empty_data, memorize_data, modify_stmts }
   317       exports program =
   318   let
   319 
   320     (* building module name hierarchy *)
   321     val module_namespace = build_module_namespace ctxt false { module_prefix = "",
   322       module_name = module_name, identifiers = identifiers, reserved = reserved } program;
   323     val prep_sym = prep_symbol ctxt { module_namespace = module_namespace,
   324       force_module = Long_Name.explode module_name, identifiers = identifiers }
   325     val sym_priority = has_priority identifiers;
   326 
   327     (* building empty module hierarchy *)
   328     val empty_module = (empty_data, Code_Symbol.Graph.empty);
   329     fun ensure_module name_fragment (data, nodes) =
   330       if can (Code_Symbol.Graph.get_node nodes) (Code_Symbol.Module name_fragment) then (data, nodes)
   331       else (data,
   332         nodes |> Code_Symbol.Graph.new_node (Code_Symbol.Module name_fragment, (name_fragment, Module empty_module)));
   333     fun allocate_module [] = I
   334       | allocate_module (name_fragment :: name_fragments) =
   335           ensure_module name_fragment
   336           #> (apsnd o Code_Symbol.Graph.map_node (Code_Symbol.Module name_fragment) o apsnd o map_module_content o allocate_module) name_fragments;
   337     val empty_program =
   338       empty_module
   339       |> Symtab.fold (fn (_, fragments) => allocate_module fragments) module_namespace
   340       |> Code_Symbol.Graph.fold (allocate_module o these o Option.map fst
   341           o Code_Symbol.lookup identifiers o fst) program;
   342 
   343     (* distribute statements over hierarchy *)
   344     val mark_exports = mark_exports { program = program, prefix_of = fst o prep_sym,
   345       map_export = fn name_fragments => fn sym => fn f =>
   346         (map_module name_fragments o apsnd o Code_Symbol.Graph.map_node sym o apsnd)
   347           (fn Stmt (export, stmt) => Stmt (f export, stmt)),
   348       class_transitive = class_transitive, class_relation_public = class_relation_public };
   349     fun add_stmt sym stmt =
   350       let
   351         val (name_fragments, base) = prep_sym sym;
   352       in
   353         (map_module name_fragments o apsnd)
   354           (Code_Symbol.Graph.new_node (sym, (base, Stmt (if null exports then Public else Private, stmt))))
   355       end;
   356     fun add_edge_acyclic_error error_msg dep gr =
   357       Code_Symbol.Graph.add_edge_acyclic dep gr
   358         handle Graph.CYCLES _ => error (error_msg ())
   359     fun add_dep sym sym' =
   360       let
   361         val (name_fragments, _) = prep_sym sym;
   362         val (name_fragments', _) = prep_sym sym';
   363         val (name_fragments_common, (diff, diff')) =
   364           chop_prefix (op =) (name_fragments, name_fragments');
   365         val is_cross_module = not (null diff andalso null diff');
   366         val dep = pairself hd (map Code_Symbol.Module diff @ [sym], map Code_Symbol.Module diff' @ [sym']);
   367         val add_edge = if is_cross_module andalso not cyclic_modules
   368           then add_edge_acyclic_error (fn _ => "Dependency "
   369             ^ Code_Symbol.quote ctxt sym ^ " -> "
   370             ^ Code_Symbol.quote ctxt sym'
   371             ^ " would result in module dependency cycle") dep
   372           else Code_Symbol.Graph.add_edge dep;
   373       in
   374         (map_module name_fragments_common o apsnd) add_edge
   375         #> (if is_cross_module then mark_exports name_fragments' sym' else I)
   376       end;
   377     val proto_program = build_proto_program
   378       { empty = empty_program, add_stmt = add_stmt, add_dep = add_dep } program
   379       |> fold (fn sym => mark_exports ((fst o prep_sym) sym) sym) exports;
   380 
   381     (* name declarations, data and statement modifications *)
   382     fun make_declarations nsps (data, nodes) =
   383       let
   384         val (module_fragments, stmt_syms) =
   385           Code_Symbol.Graph.keys nodes
   386           |> List.partition
   387               (fn sym => case Code_Symbol.Graph.get_node nodes sym
   388                 of (_, Module _) => true | _ => false)
   389           |> pairself (prioritize sym_priority)
   390         fun declare namify sym (nsps, nodes) =
   391           let
   392             val (base, node) = Code_Symbol.Graph.get_node nodes sym;
   393             val (base', nsps') = namify node base nsps;
   394             val nodes' = Code_Symbol.Graph.map_node sym (K (base', node)) nodes;
   395           in (nsps', nodes') end;
   396         val (nsps', nodes') = (nsps, nodes)
   397           |> fold (declare (K namify_module)) module_fragments
   398           |> fold (declare (namify_stmt o snd o the_stmt)) stmt_syms;
   399         fun modify_stmts' syms_stmts =
   400           let
   401             val stmts' = modify_stmts syms_stmts
   402           in stmts' @ replicate (length syms_stmts - length stmts') NONE end;
   403         val nodes'' =
   404           nodes'
   405           |> Code_Symbol.Graph.map_strong_conn (map_module_stmts (make_declarations nsps') modify_stmts');
   406         val data' = fold memorize_data stmt_syms data;
   407       in (data', nodes'') end;
   408     val (_, hierarchical_program) = make_declarations empty_nsp proto_program;
   409 
   410     (* deresolving *)
   411     fun deresolver prefix_fragments sym =
   412       let
   413         val (name_fragments, _) = prep_sym sym;
   414         val (_, (_, remainder)) = chop_prefix (op =) (prefix_fragments, name_fragments);
   415         val nodes = fold (fn name_fragment => fn nodes => case Code_Symbol.Graph.get_node nodes (Code_Symbol.Module name_fragment)
   416          of (_, Module (_, nodes)) => nodes) name_fragments hierarchical_program;
   417         val (base', _) = Code_Symbol.Graph.get_node nodes sym;
   418       in Long_Name.implode (remainder @ [base']) end
   419         handle Code_Symbol.Graph.UNDEF _ => error ("Unknown statement name: "
   420           ^ Code_Symbol.quote ctxt sym);
   421 
   422   in { deresolver = deresolver, hierarchical_program = hierarchical_program } end;
   423 
   424 fun print_hierarchical { print_module, print_stmt, lift_markup } =
   425   let
   426     fun print_node _ (_, Dummy) =
   427           NONE
   428       | print_node prefix_fragments (sym, Stmt stmt) =
   429           SOME (lift_markup (Code_Printer.markup_stmt sym)
   430             (print_stmt prefix_fragments (sym, stmt)))
   431       | print_node prefix_fragments (Code_Symbol.Module name_fragment, Module (data, nodes)) =
   432           let
   433             val prefix_fragments' = prefix_fragments @ [name_fragment]
   434           in
   435             Option.map (print_module prefix_fragments'
   436               name_fragment data) (print_nodes prefix_fragments' nodes)
   437           end
   438     and print_nodes prefix_fragments nodes =
   439       let
   440         val xs = (map_filter (fn sym => print_node prefix_fragments
   441           (sym, snd (Code_Symbol.Graph.get_node nodes sym))) o rev o flat o Code_Symbol.Graph.strong_conn) nodes
   442       in if null xs then NONE else SOME xs end;
   443   in these o print_nodes [] end;
   444 
   445 end;