src/Pure/Tools/imports.scala
author wenzelm
Thu Aug 31 16:30:46 2017 +0200 (21 months ago)
changeset 66571 0fdeb24e535e
parent 66449 1be102db1598
child 66575 191048506504
permissions -rw-r--r--
clarified errors;
     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,
    91         all_known = true).check_errors
    92 
    93     val root_keywords = Sessions.root_syntax.keywords
    94 
    95 
    96     if (operation_imports) {
    97       progress.echo("\nPotential session imports:")
    98       selected.flatMap(session_name =>
    99       {
   100         val info = full_sessions(session_name)
   101         val session_resources = new Resources(deps(session_name))
   102 
   103         val declared_imports =
   104           full_sessions.imports_ancestors(session_name).toSet + session_name
   105         val extra_imports =
   106           (for {
   107             (_, a) <- session_resources.session_base.known.theories.iterator
   108             if session_resources.theory_qualifier(a) == info.theory_qualifier
   109             b <- deps.all_known.get_file(Path.explode(a.node).file)
   110             qualifier = session_resources.theory_qualifier(b)
   111             if !declared_imports.contains(qualifier)
   112           } yield qualifier).toSet
   113 
   114         if (extra_imports.isEmpty) None
   115         else Some((session_name, extra_imports.toList.sorted, declared_imports.size))
   116       }).sortBy(_._3).foreach({ case (session_name, extra_imports, _) =>
   117         progress.echo("session " + Token.quote_name(root_keywords, session_name) + ": " +
   118           extra_imports.map(Token.quote_name(root_keywords, _)).mkString(" "))
   119       })
   120     }
   121 
   122     if (operation_repository_files) {
   123       progress.echo("\nMercurial files check:")
   124       val unused_files =
   125         for {
   126           (_, dir) <- Sessions.directories(dirs, select_dirs)
   127           file <- repository_files(progress, dir, file => file.getName.endsWith(".thy"))
   128           if deps.all_known.get_file(file).isEmpty
   129         } yield file
   130       unused_files.foreach(file => progress.echo("unused file " + quote(file.toString)))
   131     }
   132 
   133     if (operation_update) {
   134       progress.echo("\nUpdate theory imports" + update_message + ":")
   135       val updates =
   136         selected.flatMap(session_name =>
   137         {
   138           val info = full_sessions(session_name)
   139           val session_base = deps(session_name)
   140           val session_resources = new Resources(session_base)
   141           val imports_base = session_base.get_imports
   142           val imports_resources = new Resources(imports_base)
   143 
   144           def standard_import(qualifier: String, dir: String, s: String): String =
   145           {
   146             val name = imports_resources.import_name(qualifier, dir, s)
   147             val s1 =
   148               if (imports_base.loaded_theory(name)) name.theory
   149               else {
   150                 imports_base.known.get_file(Path.explode(name.node).file) match {
   151                   case Some(name1) if session_resources.theory_qualifier(name1) != qualifier =>
   152                     name1.theory
   153                   case Some(name1) if Thy_Header.is_base_name(s) =>
   154                     name1.theory_base_name
   155                   case _ => s
   156                 }
   157               }
   158             val name2 = imports_resources.import_name(qualifier, dir, s1)
   159             if (name.node == name2.node) s1 else s
   160           }
   161 
   162           val updates_root =
   163             for {
   164               (_, pos) <- info.theories.flatMap(_._2)
   165               upd <- update_name(root_keywords, pos,
   166                 standard_import(info.theory_qualifier, info.dir.implode, _))
   167             } yield upd
   168 
   169           val updates_theories =
   170             for {
   171               (_, name) <- session_base.known.theories_local.toList
   172               if session_resources.theory_qualifier(name) == info.theory_qualifier
   173               (_, pos) <- session_resources.check_thy(name, Token.Pos.file(name.node)).imports
   174               upd <- update_name(session_base.syntax.keywords, pos,
   175                 standard_import(session_resources.theory_qualifier(name), name.master_dir, _))
   176             } yield upd
   177 
   178           updates_root ::: updates_theories
   179         })
   180 
   181       val file_updates = (Multi_Map.empty[JFile, Update] /: updates)(_ + _)
   182       val conflicts =
   183         file_updates.iterator_list.flatMap({ case (file, upds) =>
   184           Library.duplicates(upds.sortBy(_.range.start),
   185             (x: Update, y: Update) => x.range overlaps y.range) match
   186           {
   187             case Nil => None
   188             case bad => Some((file, bad))
   189           }
   190         })
   191       if (conflicts.nonEmpty)
   192         error(cat_lines(
   193           conflicts.map({ case (file, bad) =>
   194             "Conflicting updates for file " + file + bad.mkString("\n  ", "\n  ", "") })))
   195 
   196       for ((file, upds) <- file_updates.iterator_list.toList.sortBy(p => p._1.toString)) {
   197         progress.echo("file " + quote(file.toString))
   198         val edits =
   199           upds.sortBy(upd => - upd.range.start).flatMap(upd =>
   200             Text.Edit.replace(upd.range.start, upd.old_text, upd.new_text))
   201         val new_text =
   202           (File.read(file) /: edits)({ case (text, edit) =>
   203             edit.edit(text, 0) match {
   204               case (None, text1) => text1
   205               case (Some(_), _) => error("Failed to apply edit " + edit + " to file " + file)
   206             }
   207           })
   208         File.write_backup2(Path.explode(File.standard_path(file)), new_text)
   209       }
   210     }
   211   }
   212 
   213 
   214   /* Isabelle tool wrapper */
   215 
   216   val isabelle_tool =
   217     Isabelle_Tool("imports", "maintain theory imports wrt. session structure", args =>
   218     {
   219       var select_dirs: List[Path] = Nil
   220       var operation_imports = false
   221       var operation_repository_files = false
   222       var requirements = false
   223       var operation_update = false
   224       var exclude_session_groups: List[String] = Nil
   225       var all_sessions = false
   226       var dirs: List[Path] = Nil
   227       var session_groups: List[String] = Nil
   228       var incremental_update = false
   229       var options = Options.init()
   230       var verbose = false
   231       var exclude_sessions: List[String] = Nil
   232 
   233       val getopts = Getopts("""
   234 Usage: isabelle imports [OPTIONS] [SESSIONS ...]
   235 
   236   Options are:
   237     -D DIR       include session directory and select its sessions
   238     -I           operation: report potential session imports
   239     -M           operation: Mercurial files check for imported theory files
   240     -R           operate on requirements of selected sessions
   241     -U           operation: update theory imports to use session qualifiers
   242     -X NAME      exclude sessions from group NAME and all descendants
   243     -a           select all sessions
   244     -d DIR       include session directory
   245     -g NAME      select session group NAME
   246     -i           incremental update according to session graph structure
   247     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   248     -v           verbose
   249     -x NAME      exclude session NAME and all descendants
   250 
   251   Maintain theory imports wrt. session structure. At least one operation
   252   needs to be specified (see options -I -M -U).
   253 """,
   254       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   255       "I" -> (_ => operation_imports = true),
   256       "M" -> (_ => operation_repository_files = true),
   257       "R" -> (_ => requirements = true),
   258       "U" -> (_ => operation_update = true),
   259       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   260       "a" -> (_ => all_sessions = true),
   261       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   262       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   263       "i" -> (_ => incremental_update = true),
   264       "o:" -> (arg => options = options + arg),
   265       "v" -> (_ => verbose = true),
   266       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   267 
   268       val sessions = getopts(args)
   269       if (args.isEmpty || !(operation_imports || operation_repository_files || operation_update))
   270         getopts.usage()
   271 
   272       val selection =
   273         Sessions.Selection(requirements, all_sessions, exclude_session_groups,
   274           exclude_sessions, session_groups, sessions)
   275 
   276       val progress = new Console_Progress(verbose = verbose)
   277 
   278       if (operation_imports || operation_repository_files ||
   279           operation_update && !incremental_update)
   280       {
   281         imports(options, operation_imports = operation_imports,
   282           operation_repository_files = operation_repository_files,
   283           operation_update = operation_update,
   284           progress = progress, selection = selection, dirs = dirs, select_dirs = select_dirs,
   285           verbose = verbose)
   286       }
   287       else if (operation_update && incremental_update) {
   288         val (selected, selected_sessions) =
   289           Sessions.load(options, dirs, select_dirs).selection(selection)
   290         selected_sessions.imports_topological_order.foreach(info =>
   291         {
   292           imports(options, operation_update = operation_update, progress = progress,
   293             update_message = " for session " + quote(info.name),
   294             selection = Sessions.Selection(sessions = List(info.name)),
   295             dirs = dirs ::: select_dirs, verbose = verbose)
   296         })
   297       }
   298     })
   299 }