summaryrefslogtreecommitdiff
path: root/src/library/scala/io/Source.scala
blob: a384af99df8510243b06c6297c64b309a8355a23 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2006, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |                                         **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

// $Id$


package scala.io

import java.io.{File, FileInputStream, PrintStream}

import compat.StringBuilder

/** This object provides convenience methods to create an iterable
 *  representation of a source file.
 *
 *  @author  Burak Emir
 *  @version 1.0, 19/08/2004
 */
object Source {

  /** Creates a <code>Source</code> instance from the given array of bytes,
   *  with empty description.
   *
   *  @param bytes ...
   *  @return      the created <code>Source</code> instance.
   */
  def fromBytes(bytes: Array[Byte]): Source =
    fromString(new String(bytes))

  /** Creates Source from array of bytes with given encoding, with
   *  empty description.
   *
   *  @param bytes ...
   *  @param enc   ...
   *  @return      ...
   */
  def fromBytes(bytes: Array[Byte], enc: String): Source =
    fromString(new String(bytes, enc))

  /** Creates a <code>Source</code> instance from a single character.
   *
   *  @param c ...
   *  @return  the create <code>Source</code> instance.
   */
  def fromChar(c: Char): Source = {
    val it = Iterator.single(c)
    new Source {
      def reset = fromChar(c)
      val iter = it
    }
  }

  /** creates Source from array of characters, with empty description.
   *
   *  @param chars ...
   *  @return      ...
   */
  def fromChars(chars: Array[Char]): Source = {
    val it = Iterator.fromArray(chars)
    new Source {
      def reset = fromChars(chars)
      val iter = it
    }
  }

  /** creates Source from string, with empty description.
   *
   *  @param s ...
   *  @return  ...
   */
  def fromString(s: String): Source = {
    val it = Iterator.fromString(s)
    new Source {
      def reset = fromString(s)
      val iter = it
    }
  }

  /** creates Source from file with given name, setting its description to
   *  filename.
   */
  def fromFile(name: String): Source =
    fromFile(new File(name))

  /** creates Source from file with given name, using given encoding, setting
   *  its description to filename.
   */
  def fromFile(name: String, enc: String): Source =
    fromFile(new File(name), enc)

  /** creates Source from file with given file: URI
   */
  def fromFile(uri: java.net.URI): Source =
    fromFile(new File(uri))

  /** creates Source from file, using default character encoding, setting its
   *  description to filename.
   */
  def fromFile(file: java.io.File): Source = {
    val arr: Array[Byte] = new Array[Byte](file.length().asInstanceOf[Int])
    val is = new FileInputStream(file)
    is.read(arr)
    val s = fromBytes(arr)
    return setFileDescriptor(file, s)
  }

  /** Creates Source from file, using given character encoding, setting its
   *  description to filename.
   *
   *  @param file ...
   *  @param enc  ...
   *  @return     ...
   */
  def fromFile(file: java.io.File, enc: String): Source = {
    val arr: Array[Byte] = new Array[Byte](file.length().asInstanceOf[Int])
    val is = new FileInputStream(file)
    is.read(arr)
    val s = fromBytes(arr, enc)
    s.descr = file.getName()
    return setFileDescriptor(file, s)
  }

  /**
   *  @param file ...
   *  @param s    ...
   *  @return     ...
   */
  def setFileDescriptor(file: File, s: Source): Source = {
    s.descr = new StringBuilder().append( "file:" ).append(file.getAbsolutePath()).toString();
    s
  }

  /**
   *  @param s    ...
   *  @return     ...
   */
  def fromURL(s: String): Source =
    fromURL(new java.net.URL(s))

  /**
   *  @param url  ...
   *  @return     ...
   */
  def fromURL(url: java.net.URL): Source = {
    val it = new Iterator[Char] {
      var data: Int = _
      def hasNext = {data != -1}
      def next = {val x = data.asInstanceOf[char]; data = bufIn.read(); x}
      val in = url.openStream()
      val bufIn = new java.io.BufferedInputStream(in)
      data = bufIn.read()
    }
    val s = new Source {
      def reset = fromURL(url)
      val iter = it
    }
    s.descr = url.toString()
    s
  }

}

/** The class <code>Source</code> implements an iterable representation
 *  of source files. Calling method <code>reset</code> returns an identical,
 *  resetted source.
 *
 *  @author  Burak Emir
 *  @version 1.0
 */
abstract class Source extends Iterator[Char] {

  // ------ protected values

  /** the actual iterator */
  protected val iter: Iterator[Char]

  protected var cline = 1
  protected var ccol = 1

  // ------ public values

  /** position of last character returned by next*/
  var pos = 0

  /** the last character returned by next.
   *  the value before the first call to next is undefined.
   */
  var ch: Char = _

  /** description of this source, default empty */
  var descr: String = ""

  var nerrors = 0
  var nwarnings = 0

  /** default col increment for tabs '\t', set to 4 initially
   */
  var tabinc = 4

  //
  // -- methods
  //

  /** convenience method, returns given line (not including newline)
   *  from Source.
   *
   *  @param line the line index.
   *  @return     the character string of the specified line.
   *  @throws IllegalArgumentException
   */
  def getLine(line: Int): String = {
    val buf = new StringBuffer()
    val it = reset
    var i = 0

    while (it.hasNext && i < (line-1))
      if ('\n' == it.next)
        i = i + 1;

    if (!it.hasNext) // this should not happen
      throw new java.lang.IllegalArgumentException(
        "line "+line+" does not exist?!"
      );

    var ch = it.next
    while (it.hasNext && '\n' != ch) {
      buf.append(ch)
      ch = it.next
    }
    val res = buf.toString()
    buf.setLength(0)
    res
  }
  /** Returns <code>true</code> if this source has more characters.
   */
  def hasNext = iter.hasNext

  /** returns next character and has the following side-effects: updates
   *  position (ccol and cline) and assigns the character to ch
   */
  def next = {
    ch = iter.next
    pos = Position.encode(cline,ccol)
    ch match {
      case '\n' =>
        ccol = 1
        cline = cline + 1
      case '\t' =>
        ccol = ccol + tabinc
      case _ =>
        ccol = ccol + 1
    }
    ch
  }

  /** reports an error message to console.
   *
   *  @param pos ...
   *  @param msg the error message to report
   */
  def reportError(pos: Int, msg: String): Unit =
    report(pos, msg, java.lang.System.out)

  /**
   *  @param pos ...
   *  @param msg the error message to report
   *  @param out ...
   */
  def reportError(pos: Int, msg: String, out: PrintStream): Unit = {
    nerrors = nerrors + 1
    report(pos, msg, java.lang.System.out)
  }

  /**
   *  @param pos ...
   *  @param msg the error message to report
   *  @param out ...
   */
  def report(pos: Int, msg: String, out: PrintStream): Unit = {
    val buf = new StringBuffer
    val line = Position.line(pos)
    val col = Position.column(pos)
    buf.append(descr + ":" + line + ":" + col + ": " + msg)
    buf.append(getLine(line))
    var i = 1
    while (i < col) {
      buf.append(' ')
      i = i + 1
    }
    buf.append('^')
    out.println(buf.toString)
  }

  /** Reports a warning message to <code>java.lang.System.out</code>.
   *
   *  @param pos ...
   *  @param msg the warning message to report
   */
  def reportWarning(pos: Int, msg: String): Unit =
    reportWarning(pos, msg, java.lang.System.out)

  /**
   *  @param pos ...
   *  @param msg the warning message to report
   *  @param out ...
   */
  def reportWarning(pos: Int, msg: String, out: PrintStream): Unit = {
    nwarnings = nwarnings + 1
    report(pos, "warning! "+msg, out)
  }

  /** the actual reset method */
  def reset: Source

}