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