src/Pure/Tools/imports.scala
author wenzelm
Thu Oct 05 16:33:36 2017 +0200 (21 months ago)
changeset 66767 294c2e9a689e
parent 66737 2edc0c42c883
child 66780 bf54ca580bf2
permissions -rw-r--r--
clarified modules;
     1 /*  Title:      Pure/Tools/imports.scala
     2     Author:     Makarius
     3 
     4 Maintain theory imports wrt. session structure.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import java.io.{File => JFile}
    11 
    12 
    13 object Imports
    14 {
    15   /* repository files */
    16 
    17   def repository_files(progress: Progress, start: Path, pred: JFile => Boolean = _ => true)
    18       : List[JFile] =
    19     Mercurial.find_repository(start) match {
    20       case None =>
    21         progress.echo_warning("Ignoring directory " + start + " (no Mercurial repository)")
    22         Nil
    23       case Some(hg) =>
    24         val start_path = start.canonical_file.toPath
    25         for {
    26           name <- hg.known_files()
    27           file = (hg.root + Path.explode(name)).file
    28           if pred(file) && File.canonical(file).toPath.startsWith(start_path)
    29         } yield file
    30     }
    31 
    32 
    33   /* update imports */
    34 
    35   sealed case class Update(range: Text.Range, old_text: String, new_text: String)
    36   {
    37     def edits: List[Text.Edit] =
    38       Text.Edit.replace(range.start, old_text, new_text)
    39 
    40     override def toString: String =
    41       range.toString + ": " + old_text + " -> " + new_text
    42   }
    43 
    44   def update_name(keywords: Keyword.Keywords, pos: Position.T, update: String => String)
    45     : Option[(JFile, Update)] =
    46   {
    47     val file =
    48       pos match {
    49         case Position.File(file) => Path.explode(file).canonical_file
    50         case _ => error("Missing file in position" + Position.here(pos))
    51       }
    52 
    53     val text = File.read(file)
    54 
    55     val range =
    56       pos match {
    57         case Position.Range(symbol_range) => Symbol.Text_Chunk(text).decode(symbol_range)
    58         case _ => error("Missing range in position" + Position.here(pos))
    59       }
    60 
    61     Token.read_name(keywords, range.substring(text)) match {
    62       case Some(tok) =>
    63         val s1 = tok.source
    64         val s2 = Token.quote_name(keywords, update(tok.content))
    65         if (s1 == s2) None else Some((file, Update(range, s1, s2)))
    66       case None => error("Name token expected" + Position.here(pos))
    67     }
    68   }
    69 
    70 
    71   /* collective operations */
    72 
    73   def imports(
    74     options: Options,
    75     operation_imports: Boolean = false,
    76     operation_repository_files: Boolean = false,
    77     operation_update: Boolean = false,
    78     update_message: String = "",
    79     progress: Progress = No_Progress,
    80     selection: Sessions.Selection = Sessions.Selection.empty,
    81     dirs: List[Path] = Nil,
    82     select_dirs: List[Path] = Nil,
    83     verbose: Boolean = false) =
    84   {
    85     val full_sessions = Sessions.load(options, dirs, select_dirs)
    86     val (selected, selected_sessions) = full_sessions.selection(selection)
    87 
    88     val deps =
    89       Sessions.deps(selected_sessions, progress = progress, verbose = verbose,
    90         global_theories = full_sessions.global_theories).check_errors
    91 
    92     val root_keywords = Sessions.root_syntax.keywords
    93 
    94 
    95     if (operation_imports) {
    96       progress.echo("\nPotential session imports:")
    97       selected.flatMap(session_name =>
    98       {
    99         val info = full_sessions(session_name)
   100         val session_resources = new Resources(deps(session_name))
   101 
   102         val declared_imports =
   103           full_sessions.imports_ancestors(session_name).toSet + session_name
   104         val extra_imports =
   105           (for {
   106             (_, a) <- session_resources.session_base.known.theories.iterator
   107             if session_resources.theory_qualifier(a) == info.theory_qualifier
   108             b <- deps.all_known.get_file(a.path.file)
   109             qualifier = session_resources.theory_qualifier(b)
   110             if !declared_imports.contains(qualifier)
   111           } yield qualifier).toSet
   112 
   113         if (extra_imports.isEmpty) None
   114         else Some((session_name, extra_imports.toList.sorted, declared_imports.size))
   115       }).sortBy(_._3).foreach({ case (session_name, extra_imports, _) =>
   116         progress.echo("session " + Token.quote_name(root_keywords, session_name) + ": " +
   117           extra_imports.map(Token.quote_name(root_keywords, _)).mkString(" "))
   118       })
   119     }
   120 
   121     if (operation_repository_files) {
   122       progress.echo("\nMercurial repository check:")
   123       val unused_files =
   124         for {
   125           (_, dir) <- Sessions.directories(dirs, select_dirs)
   126           file <- repository_files(progress, dir, file => file.getName.endsWith(".thy"))
   127           if deps.all_known.get_file(file).isEmpty
   128         } yield file
   129       unused_files.foreach(file => progress.echo("unused file " + quote(file.toString)))
   130     }
   131 
   132     if (operation_update) {
   133       progress.echo("\nUpdate theory imports" + update_message + ":")
   134       val updates =
   135         selected.flatMap(session_name =>
   136         {
   137           val info = full_sessions(session_name)
   138           val session_base = deps(session_name)
   139           val session_resources = new Resources(session_base)
   140           val imports_base = session_base.get_imports
   141           val imports_resources = new Resources(imports_base)
   142 
   143           def standard_import(qualifier: String, dir: String, s: String): String =
   144             imports_resources.standard_import(session_resources, qualifier, dir, s)
   145 
   146           val updates_root =
   147             for {
   148               (_, pos) <- info.theories.flatMap(_._2)
   149               upd <- update_name(root_keywords, pos,
   150                 standard_import(info.theory_qualifier, info.dir.implode, _))
   151             } yield upd
   152 
   153           val updates_theories =
   154             for {
   155               (_, name) <- session_base.known.theories_local.toList
   156               if session_resources.theory_qualifier(name) == info.theory_qualifier
   157               (_, pos) <- session_resources.check_thy(name, Token.Pos.file(name.node)).imports
   158               upd <- update_name(session_base.overall_syntax.keywords, pos,
   159                 standard_import(session_resources.theory_qualifier(name), name.master_dir, _))
   160             } yield upd
   161 
   162           updates_root ::: updates_theories
   163         })
   164 
   165       val file_updates = (Multi_Map.empty[JFile, Update] /: updates)(_ + _)
   166       val conflicts =
   167         file_updates.iterator_list.flatMap({ case (file, upds) =>
   168           Library.duplicates(upds.sortBy(_.range.start),
   169             (x: Update, y: Update) => x.range overlaps y.range) match
   170           {
   171             case Nil => None
   172             case bad => Some((file, bad))
   173           }
   174         })
   175       if (conflicts.nonEmpty)
   176         error(cat_lines(
   177           conflicts.map({ case (file, bad) =>
   178             "Conflicting updates for file " + file + bad.mkString("\n  ", "\n  ", "") })))
   179 
   180       for ((file, upds) <- file_updates.iterator_list.toList.sortBy(p => p._1.toString)) {
   181         progress.echo("file " + quote(file.toString))
   182         val edits =
   183           upds.sortBy(upd => - upd.range.start).flatMap(upd =>
   184             Text.Edit.replace(upd.range.start, upd.old_text, upd.new_text))
   185         val new_text =
   186           (File.read(file) /: edits)({ case (text, edit) =>
   187             edit.edit(text, 0) match {
   188               case (None, text1) => text1
   189               case (Some(_), _) => error("Failed to apply edit " + edit + " to file " + file)
   190             }
   191           })
   192         File.write_backup2(Path.explode(File.standard_path(file)), new_text)
   193       }
   194     }
   195   }
   196 
   197 
   198   /* Isabelle tool wrapper */
   199 
   200   val isabelle_tool =
   201     Isabelle_Tool("imports", "maintain theory imports wrt. session structure", args =>
   202     {
   203       var base_sessions: List[String] = Nil
   204       var select_dirs: List[Path] = Nil
   205       var operation_imports = false
   206       var operation_repository_files = false
   207       var requirements = false
   208       var operation_update = false
   209       var exclude_session_groups: List[String] = Nil
   210       var all_sessions = false
   211       var dirs: List[Path] = Nil
   212       var session_groups: List[String] = Nil
   213       var incremental_update = false
   214       var options = Options.init()
   215       var verbose = false
   216       var exclude_sessions: List[String] = Nil
   217 
   218       val getopts = Getopts("""
   219 Usage: isabelle imports [OPTIONS] [SESSIONS ...]
   220 
   221   Options are:
   222     -B NAME      include session NAME and all descendants
   223     -D DIR       include session directory and select its sessions
   224     -I           operation: report potential session imports
   225     -M           operation: Mercurial repository check for theory files
   226     -R           operate on requirements of selected sessions
   227     -U           operation: update theory imports to use session qualifiers
   228     -X NAME      exclude sessions from group NAME and all descendants
   229     -a           select all sessions
   230     -d DIR       include session directory
   231     -g NAME      select session group NAME
   232     -i           incremental update according to session graph structure
   233     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   234     -v           verbose
   235     -x NAME      exclude session NAME and all descendants
   236 
   237   Maintain theory imports wrt. session structure. At least one operation
   238   needs to be specified (see options -I -M -U).
   239 """,
   240       "B:" -> (arg => base_sessions = base_sessions ::: List(arg)),
   241       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   242       "I" -> (_ => operation_imports = true),
   243       "M" -> (_ => operation_repository_files = true),
   244       "R" -> (_ => requirements = true),
   245       "U" -> (_ => operation_update = true),
   246       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   247       "a" -> (_ => all_sessions = true),
   248       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   249       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   250       "i" -> (_ => incremental_update = true),
   251       "o:" -> (arg => options = options + arg),
   252       "v" -> (_ => verbose = true),
   253       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   254 
   255       val sessions = getopts(args)
   256       if (args.isEmpty || !(operation_imports || operation_repository_files || operation_update))
   257         getopts.usage()
   258 
   259       val selection =
   260         Sessions.Selection(requirements, all_sessions, base_sessions, exclude_session_groups,
   261           exclude_sessions, session_groups, sessions)
   262 
   263       val progress = new Console_Progress(verbose = verbose)
   264 
   265       if (operation_imports || operation_repository_files ||
   266           operation_update && !incremental_update)
   267       {
   268         imports(options, operation_imports = operation_imports,
   269           operation_repository_files = operation_repository_files,
   270           operation_update = operation_update,
   271           progress = progress, selection = selection, dirs = dirs, select_dirs = select_dirs,
   272           verbose = verbose)
   273       }
   274       else if (operation_update && incremental_update) {
   275         val (selected, selected_sessions) =
   276           Sessions.load(options, dirs, select_dirs).selection(selection)
   277         selected_sessions.imports_topological_order.foreach(info =>
   278         {
   279           imports(options, operation_update = operation_update, progress = progress,
   280             update_message = " for session " + quote(info.name),
   281             selection = Sessions.Selection(sessions = List(info.name)),
   282             dirs = dirs ::: select_dirs, verbose = verbose)
   283         })
   284       }
   285     })
   286 }