src/Pure/library.scala
author wenzelm
Sat Nov 04 15:24:40 2017 +0100 (19 months ago)
changeset 67003 49850a679c2c
parent 66351 95847ffa62dc
child 67431 84e143e64336
permissions -rw-r--r--
more robust sorted_entries;
     1 /*  Title:      Pure/library.scala
     2     Author:     Makarius
     3 
     4 Basic library.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import scala.annotation.tailrec
    11 import scala.collection.mutable
    12 import scala.util.matching.Regex
    13 
    14 
    15 object Library
    16 {
    17   /* resource management */
    18 
    19   def using[A <: { def close() }, B](x: A)(f: A => B): B =
    20   {
    21     import scala.language.reflectiveCalls
    22 
    23     try { f(x) }
    24     finally { if (x != null) x.close() }
    25   }
    26 
    27 
    28   /* integers */
    29 
    30   private val small_int = 10000
    31   private lazy val small_int_table =
    32   {
    33     val array = new Array[String](small_int)
    34     for (i <- 0 until small_int) array(i) = i.toString
    35     array
    36   }
    37 
    38   def is_small_int(s: String): Boolean =
    39   {
    40     val len = s.length
    41     1 <= len && len <= 4 &&
    42     s.forall(c => '0' <= c && c <= '9') &&
    43     (len == 1 || s(0) != '0')
    44   }
    45 
    46   def signed_string_of_long(i: Long): String =
    47     if (0 <= i && i < small_int) small_int_table(i.toInt)
    48     else i.toString
    49 
    50   def signed_string_of_int(i: Int): String =
    51     if (0 <= i && i < small_int) small_int_table(i)
    52     else i.toString
    53 
    54 
    55   /* separated chunks */
    56 
    57   def separate[A](s: A, list: List[A]): List[A] =
    58   {
    59     val result = new mutable.ListBuffer[A]
    60     var first = true
    61     for (x <- list) {
    62       if (first) {
    63         first = false
    64         result += x
    65       }
    66       else {
    67         result += s
    68         result += x
    69       }
    70     }
    71     result.toList
    72   }
    73 
    74   def separated_chunks(sep: Char => Boolean, source: CharSequence): Iterator[CharSequence] =
    75     new Iterator[CharSequence] {
    76       private val end = source.length
    77       private def next_chunk(i: Int): Option[(CharSequence, Int)] =
    78       {
    79         if (i < end) {
    80           var j = i; do j += 1 while (j < end && !sep(source.charAt(j)))
    81           Some((source.subSequence(i + 1, j), j))
    82         }
    83         else None
    84       }
    85       private var state: Option[(CharSequence, Int)] = if (end == 0) None else next_chunk(-1)
    86 
    87       def hasNext(): Boolean = state.isDefined
    88       def next(): CharSequence =
    89         state match {
    90           case Some((s, i)) => state = next_chunk(i); s
    91           case None => Iterator.empty.next()
    92         }
    93     }
    94 
    95   def space_explode(sep: Char, str: String): List[String] =
    96     separated_chunks(_ == sep, str).map(_.toString).toList
    97 
    98 
    99   /* lines */
   100 
   101   def terminate_lines(lines: TraversableOnce[String]): String = lines.mkString("", "\n", "\n")
   102 
   103   def cat_lines(lines: TraversableOnce[String]): String = lines.mkString("\n")
   104 
   105   def split_lines(str: String): List[String] = space_explode('\n', str)
   106 
   107   def prefix_lines(prfx: String, str: String): String =
   108     if (str == "") str
   109     else cat_lines(split_lines(str).map(s => prfx + s))
   110 
   111   def first_line(source: CharSequence): String =
   112   {
   113     val lines = separated_chunks(_ == '\n', source)
   114     if (lines.hasNext) lines.next.toString
   115     else ""
   116   }
   117 
   118   def encode_lines(s: String): String = s.replace('\n', '\u000b')
   119   def decode_lines(s: String): String = s.replace('\u000b', '\n')
   120 
   121 
   122   /* strings */
   123 
   124   def make_string(f: StringBuilder => Unit): String =
   125   {
   126     val s = new StringBuilder
   127     f(s)
   128     s.toString
   129   }
   130 
   131   def try_unprefix(prfx: String, s: String): Option[String] =
   132     if (s.startsWith(prfx)) Some(s.substring(prfx.length)) else None
   133 
   134   def try_unsuffix(sffx: String, s: String): Option[String] =
   135     if (s.endsWith(sffx)) Some(s.substring(0, s.length - sffx.length)) else None
   136 
   137   def perhaps_unprefix(prfx: String, s: String): String = try_unprefix(prfx, s) getOrElse s
   138   def perhaps_unsuffix(sffx: String, s: String): String = try_unsuffix(sffx, s) getOrElse s
   139 
   140   def trim_line(s: String): String =
   141     if (s.endsWith("\r\n")) s.substring(0, s.length - 2)
   142     else if (s.endsWith("\r") || s.endsWith("\n")) s.substring(0, s.length - 1)
   143     else s
   144 
   145   def trim_split_lines(s: String): List[String] =
   146     split_lines(trim_line(s)).map(trim_line(_))
   147 
   148   def isolate_substring(s: String): String = new String(s.toCharArray)
   149 
   150 
   151   /* quote */
   152 
   153   def quote(s: String): String = "\"" + s + "\""
   154 
   155   def try_unquote(s: String): Option[String] =
   156     if (s.startsWith("\"") && s.endsWith("\"")) Some(s.substring(1, s.length - 1))
   157     else None
   158 
   159   def perhaps_unquote(s: String): String = try_unquote(s) getOrElse s
   160 
   161   def commas(ss: Iterable[String]): String = ss.iterator.mkString(", ")
   162   def commas_quote(ss: Iterable[String]): String = ss.iterator.map(quote).mkString(", ")
   163 
   164 
   165   /* CharSequence */
   166 
   167   class Reverse(text: CharSequence, start: Int, end: Int) extends CharSequence
   168   {
   169     require(0 <= start && start <= end && end <= text.length)
   170 
   171     def this(text: CharSequence) = this(text, 0, text.length)
   172 
   173     def length: Int = end - start
   174     def charAt(i: Int): Char = text.charAt(end - i - 1)
   175 
   176     def subSequence(i: Int, j: Int): CharSequence =
   177       if (0 <= i && i <= j && j <= length) new Reverse(text, end - j, end - i)
   178       else throw new IndexOutOfBoundsException
   179 
   180     override def toString: String =
   181     {
   182       val buf = new StringBuilder(length)
   183       for (i <- 0 until length)
   184         buf.append(charAt(i))
   185       buf.toString
   186     }
   187   }
   188 
   189   class Line_Termination(text: CharSequence) extends CharSequence
   190   {
   191     def length: Int = text.length + 1
   192     def charAt(i: Int): Char = if (i == text.length) '\n' else text.charAt(i)
   193     def subSequence(i: Int, j: Int): CharSequence =
   194       if (j == text.length + 1) new Line_Termination(text.subSequence(i, j - 1))
   195       else text.subSequence(i, j)
   196     override def toString: String = text.toString + "\n"
   197   }
   198 
   199 
   200   /* regular expressions */
   201 
   202   def make_regex(s: String): Option[Regex] =
   203     try { Some(new Regex(s)) } catch { case ERROR(_) => None }
   204 
   205   def is_regex_meta(c: Char): Boolean = """()[]{}\^$|?*+.<>-=!""".contains(c)
   206 
   207   def escape_regex(s: String): String =
   208     if (s.exists(is_regex_meta(_))) {
   209       (for (c <- s.iterator)
   210        yield { if (is_regex_meta(c)) "\\" + c.toString else c.toString }).mkString
   211     }
   212     else s
   213 
   214 
   215   /* lists */
   216 
   217   def take_prefix[A](pred: A => Boolean, xs: List[A]): (List[A], List[A]) =
   218     (xs.takeWhile(pred), xs.dropWhile(pred))
   219 
   220   def member[A, B](xs: List[A])(x: B): Boolean = xs.contains(x)
   221   def insert[A](x: A)(xs: List[A]): List[A] = if (xs.contains(x)) xs else x :: xs
   222   def remove[A, B](x: B)(xs: List[A]): List[A] = if (member(xs)(x)) xs.filterNot(_ == x) else xs
   223   def update[A](x: A)(xs: List[A]): List[A] = x :: remove(x)(xs)
   224 
   225   def merge[A](xs: List[A], ys: List[A]): List[A] =
   226     if (xs.eq(ys)) xs
   227     else if (xs.isEmpty) ys
   228     else ys.foldRight(xs)(Library.insert(_)(_))
   229 
   230   def distinct[A](xs: List[A], eq: (A, A) => Boolean = (x: A, y: A) => x == y): List[A] =
   231   {
   232     val result = new mutable.ListBuffer[A]
   233     xs.foreach(x => if (!result.exists(y => eq(x, y))) result += x)
   234     result.toList
   235   }
   236 
   237   def duplicates[A](lst: List[A], eq: (A, A) => Boolean = (x: A, y: A) => x == y): List[A] =
   238   {
   239     val result = new mutable.ListBuffer[A]
   240     @tailrec def dups(rest: List[A]): Unit =
   241       rest match {
   242         case Nil =>
   243         case x :: xs =>
   244           if (!result.exists(y => eq(x, y)) && xs.exists(y => eq(x, y))) result += x
   245           dups(xs)
   246       }
   247     dups(lst)
   248     result.toList
   249   }
   250 
   251 
   252   /* proper values */
   253 
   254   def proper[A](x: A): Option[A] =
   255     if (x == null) None else Some(x)
   256 
   257   def proper_string(s: String): Option[String] =
   258     if (s == null || s == "") None else Some(s)
   259 
   260   def proper_list[A](list: List[A]): Option[List[A]] =
   261     if (list == null || list.isEmpty) None else Some(list)
   262 
   263 
   264   /* UUID */
   265 
   266   def UUID(): String = java.util.UUID.randomUUID().toString
   267 }