Just enough cleaning to get rid of all those warnings.
Pull-Request: #921
Reviewed-by: Jean Privat <jean@pryen.org>
Reviewed-by: Lucas Bajolet <r4pass@hotmail.com>
Reviewed-by: Alexis Laferrière <alexis.laf@xymus.net>
--- /dev/null
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Introduce base classes and services for JSON handling.
+module jsonable
+
+import standard
+private import json::json_parser
+private import json::json_lexer
+
+# Something that can be translated to JSON
+interface Jsonable
+ # Get the JSON representation of `self`
+ fun to_json: String is abstract
+end
+
+redef class String
+ super Jsonable
+
+ redef fun to_json do
+ var res = new FlatBuffer
+ res.add '\"'
+ for i in [0..self.length[ do
+ var char = self[i]
+ if char == '\\' then
+ res.append("\\\\")
+ continue
+ else if char == '\"' then
+ res.append("\\\"")
+ continue
+ else if char == '\/' then
+ res.append("\\/")
+ continue
+ else if char == '\n' then
+ res.append("\\n")
+ continue
+ else if char == '\r' then
+ res.append("\\r")
+ continue
+ else if char == '\t' then
+ res.append("\\t")
+ continue
+ end
+ res.add char
+ end
+ res.add '\"'
+ return res.write_to_string
+ end
+end
+
+redef class Int
+ super Jsonable
+
+ redef fun to_json do return self.to_s
+end
+
+redef class Float
+ super Jsonable
+
+ redef fun to_json do return self.to_s
+end
+
+redef class Bool
+ super Jsonable
+
+ redef fun to_json do return self.to_s
+end
+
+# A JSON Object representation that behaves like a `Map`
+class JsonObject
+ super Jsonable
+ super Map[String, nullable Jsonable]
+
+ private var map = new HashMap[String, nullable Jsonable]
+
+ # Create an empty `JsonObject`
+ #
+ # var obj = new JsonObject
+ # assert obj.is_empty
+ init do end
+
+ # Init the JSON Object from a Nit `Map`
+ #
+ # var map = new HashMap[String, String]
+ # map["foo"] = "bar"
+ # map["goo"] = "baz"
+ # var obj = new JsonObject.from(map)
+ # assert obj.length == 2
+ # assert obj["foo"] == "bar"
+ # assert obj["goo"] == "baz"
+ init from(items: Map[String, nullable Jsonable]) do
+ for k, v in items do map[k] = v
+ end
+
+ redef fun [](key) do return map[key]
+ redef fun []=(key, value) do map[key] = value
+ redef fun clear do map.clear
+ redef fun has_key(key) do return map.has_key(key)
+ redef fun is_empty do return map.is_empty
+ redef fun iterator do return map.iterator
+ redef fun keys do return map.keys
+ redef fun values do return map.values
+ redef fun length do return map.length
+
+ # Advanced query to get a value within `self` or its children.
+ #
+ # A query is composed of the keys to each object seperated by '.'.
+ #
+ # REQUIRE `self.has_key(query)`
+ #
+ # var obj1 = new JsonObject
+ # obj1["baz"] = "foobarbaz"
+ # var obj2 = new JsonObject
+ # obj2["bar"] = obj1
+ # var obj3 = new JsonObject
+ # obj3["foo"] = obj2
+ # assert obj3.get("foo.bar.baz") == "foobarbaz"
+ fun get(query: String): nullable Jsonable do
+ var keys = query.split(".").reversed
+ var key = keys.pop
+
+ assert has_key(key)
+ var node = self[key]
+
+ while not keys.is_empty do
+ key = keys.pop
+ assert node isa JsonObject and node.has_key(key)
+ node = node[key]
+ end
+ return node
+ end
+
+ # Create an empty `JsonObject`
+ #
+ # var obj = new JsonObject
+ # obj["foo"] = "bar"
+ # assert obj.to_json == "\{\"foo\": \"bar\"\}"
+ redef fun to_json do
+ var tpl = new Array[String]
+ tpl.add "\{"
+ var vals = new Array[String]
+ for k, v in self do
+ if v == null then
+ vals.add "{k.to_json}: null"
+ else
+ vals.add "{k.to_json}: {v.to_json}"
+ end
+ end
+ tpl.add vals.join(",")
+ tpl.add "\}"
+ return tpl.join("")
+ end
+
+ redef fun to_s do return to_json
+end
+
+# A JSON Array representation that behaves like a `Sequence`
+class JsonArray
+ super Jsonable
+ super Sequence[nullable Jsonable]
+
+ private var array = new Array[nullable Jsonable]
+
+ init do end
+
+ # init the JSON Array from a Nit `Collection`
+ init from(items: Collection[nullable Jsonable]) do
+ array.add_all(items)
+ end
+
+ redef fun [](key) do return array[key]
+ redef fun []=(key, value) do array[key] = value
+ redef fun clear do array.clear
+ redef fun insert(item, index) do array.insert(item, index)
+ redef fun is_empty do return array.is_empty
+ redef fun iterator do return array.iterator
+ redef fun length do return array.length
+ redef fun pop do return array.pop
+ redef fun push(value) do array.push(value)
+ redef fun remove_at(index) do array.remove_at(index)
+ redef fun shift do return array.shift
+ redef fun unshift(e) do array.unshift(e)
+
+ redef fun to_json do
+ var tpl = new Array[String]
+ tpl.add "["
+ var vals = new Array[String]
+ for v in self do
+ if v == null then
+ vals.add "null"
+ else
+ vals.add v.to_json
+ end
+ end
+ tpl.add vals.join(",")
+ tpl.add "]"
+ return tpl.join("")
+ end
+
+ redef fun to_s do return to_json
+end
+
+# An error in JSON format that can be returned by tools using JSON like parsers.
+#
+# var error = new JsonError("ErrorCode", "ErrorMessage")
+# assert error.to_s == "ErrorCode: ErrorMessage"
+# assert error.to_json == "\{\"error\": \"ErrorCode\", \"message\": \"ErrorMessage\"\}"
+class JsonError
+ super Jsonable
+
+ # The error code
+ var error: String
+
+ # The error message
+ var message: String
+
+ redef fun to_json do
+ var tpl = new Array[String]
+ tpl.add "\{"
+ tpl.add "\"error\": {error.to_json}, "
+ tpl.add "\"message\": {message.to_json}"
+ tpl.add "\}"
+ return tpl.join("")
+ end
+
+ redef fun to_s do return "{error}: {message}"
+end
+
+# Redef parser
+
+redef class Nvalue
+ private fun to_nit_object: nullable Jsonable is abstract
+end
+
+redef class Nvalue_number
+ redef fun to_nit_object
+ do
+ var text = n_number.text
+ if text.chars.has('.') or text.chars.has('e') or text.chars.has('E') then return text.to_f
+ return text.to_i
+ end
+end
+
+redef class Nvalue_string
+ redef fun to_nit_object do return n_string.to_nit_string
+end
+
+redef class Nvalue_true
+ redef fun to_nit_object do return true
+end
+
+redef class Nvalue_false
+ redef fun to_nit_object do return false
+end
+
+redef class Nvalue_null
+ redef fun to_nit_object do return null
+end
+
+redef class Nstring
+ # FIXME support \n, etc.
+ fun to_nit_string: String do
+ var res = new FlatBuffer
+ var skip = false
+ for i in [1..text.length-2] do
+ if skip then
+ skip = false
+ continue
+ end
+ var char = text[i]
+ if char == '\\' and i < text.length - 2 then
+ if text[i + 1] == '\\' then
+ res.add('\\')
+ skip = true
+ continue
+ end
+ if text[i + 1] == '\"' then
+ res.add('\"')
+ skip = true
+ continue
+ end
+ if text[i + 1] == '/' then
+ res.add('\/')
+ skip = true
+ continue
+ end
+ if text[i + 1] == 'n' then
+ res.add('\n')
+ skip = true
+ continue
+ end
+ if text[i + 1] == 'r' then
+ res.add('\r')
+ skip = true
+ continue
+ end
+ if text[i + 1] == 't' then
+ res.add('\t')
+ skip = true
+ continue
+ end
+ end
+ res.add char
+ end
+ return res.write_to_string
+ end
+end
+
+redef class Nvalue_object
+ redef fun to_nit_object
+ do
+ var obj = new JsonObject
+ var members = n_members
+ if members != null then
+ var pairs = members.pairs
+ for pair in pairs do obj[pair.name] = pair.value
+ end
+ return obj
+ end
+end
+
+redef class Nmembers
+ fun pairs: Array[Npair] is abstract
+end
+
+redef class Nmembers_tail
+ redef fun pairs
+ do
+ var arr = n_members.pairs
+ arr.add n_pair
+ return arr
+ end
+end
+
+redef class Nmembers_head
+ redef fun pairs do return [n_pair]
+end
+
+redef class Npair
+ fun name: String do return n_string.to_nit_string
+ fun value: nullable Jsonable do return n_value.to_nit_object
+end
+
+redef class Nvalue_array
+ redef fun to_nit_object
+ do
+ var arr = new JsonArray
+ var elements = n_elements
+ if elements != null then
+ var items = elements.items
+ for item in items do arr.add(item.to_nit_object)
+ end
+ return arr
+ end
+end
+
+redef class Nelements
+ fun items: Array[Nvalue] is abstract
+end
+
+redef class Nelements_tail
+ redef fun items
+ do
+ var items = n_elements.items
+ items.add(n_value)
+ return items
+ end
+end
+
+redef class Nelements_head
+ redef fun items do return [n_value]
+end
+
+redef class Text
+ # Parse a JSON String as Jsonable entities
+ #
+ # Example with `JsonObject`"
+ #
+ # var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".to_jsonable
+ # assert obj isa JsonObject
+ # assert obj["foo"] isa JsonObject
+ # assert obj["foo"].as(JsonObject)["bar"] == true
+ #
+ # Example with `JsonArray`
+ #
+ # var arr = "[1, 2, 3]".to_jsonable
+ # assert arr isa JsonArray
+ # assert arr.length == 3
+ # assert arr.first == 1
+ # assert arr.last == 3
+ #
+ # Example with `String`
+ #
+ # var str = "\"foo, bar, baz\"".to_jsonable
+ # assert str isa String
+ # assert str == "foo, bar, baz"
+ #
+ # Malformed JSON input returns a `JsonError` object
+ #
+ # var bad = "\{foo: \"bar\"\}".to_jsonable
+ # assert bad isa JsonError
+ # assert bad.error == "JsonLexerError"
+ fun to_jsonable: nullable Jsonable
+ do
+ var lexer = new Lexer_json(to_s)
+ var parser = new Parser_json
+ var tokens = lexer.lex
+ parser.tokens.add_all(tokens)
+ var root_node = parser.parse
+ if root_node isa NStart then
+ return root_node.n_0.to_nit_object
+ else if root_node isa NLexerError then
+ var pos = root_node.position
+ var msg = "{root_node.message} at {pos or else "<unknown>"} for {root_node}"
+ return new JsonError("JsonLexerError", msg)
+ else if root_node isa NParserError then
+ var pos = root_node.position
+ var msg = "{root_node.message} at {pos or else "<unknown>"} for {root_node}"
+ return new JsonError("JsonParsingError", msg)
+ else abort
+ end
+end
+
redef var is_ok: Bool = true
- private var container: Container[E]
+ var container: Container[E]
end
# Items can be removed from this collection
return nhs
end
+ # Returns a new instance of `Set`.
+ #
+ # Depends on the subclass, mainly used for copy services
+ # like `union` or `intersection`.
protected fun new_set: Set[E] is abstract
end
_iter.next
end
- private var iter: Iterator[Couple[K,V]]
+ var iter: Iterator[Couple[K,V]]
end
# Some tools ###################################################################
redef var index = 0
- private var array: AbstractArrayRead[E]
+ var array: AbstractArrayRead[E]
end
private class ArrayReverseIterator[E]
redef fun item: E do return _iter.item
- private var iter: ArrayIterator[E]
+ var iter: ArrayIterator[E]
end
fun length: Int is intern
# Use `self` to initialize a standard Nit Array.
fun to_a: Array[E] do return new Array[E].with_native(self, length)
+
+ # Get item at `index`.
fun [](index: Int): E is intern
+
+ # Set `item` at `index`.
fun []=(index: Int, item: E) is intern
+
+ # Copy `length` items to `dest`.
fun copy_to(dest: NativeArray[E], length: Int) is intern
#fun =(o: NativeArray[E]): Bool is intern
#fun !=(o: NativeArray[E]): Bool is intern
import union_find
redef class Sequence[E]
+
+ # Copy the content of `self` between `start` and `len` to a new Array.
fun subarray(start, len: Int): Array[E]
do
var a = new Array[E].with_capacity(len)
private abstract class HashCollection[K: Object]
type N: HashNode[K]
- private var array: nullable NativeArray[nullable N] = null # Used to store items
- private var capacity: Int = 0 # Size of _array
- private var the_length: Int = 0 # Number of items in the map
+ var array: nullable NativeArray[nullable N] = null # Used to store items
+ var capacity: Int = 0 # Size of _array
+ var the_length: Int = 0 # Number of items in the map
- private var first_item: nullable N = null # First added item (used to visit items in nice order)
- private var last_item: nullable N = null # Last added item (same)
+ var first_item: nullable N = null # First added item (used to visit items in nice order)
+ var last_item: nullable N = null # Last added item (same)
# The last key accessed (used for cache)
- private var last_accessed_key: nullable K = null
+ var last_accessed_key: nullable K = null
# The last node accessed (used for cache)
- private var last_accessed_node: nullable N = null
+ var last_accessed_node: nullable N = null
# Return the index of the key k
fun index_at(k: K): Int
end
private abstract class HashNode[K: Object]
- private var key: K
+ var key: K
type N: HashNode[K]
- private var next_item: nullable N = null
- private var prev_item: nullable N = null
- private var prev_in_bucklet: nullable N = null
- private var next_in_bucklet: nullable N = null
+ var next_item: nullable N = null
+ var prev_item: nullable N = null
+ var prev_in_bucklet: nullable N = null
+ var next_in_bucklet: nullable N = null
end
# A map implemented with a hash table.
private class HashMapNode[K: Object, V]
super HashNode[K]
redef type N: HashMapNode[K, V]
- private var value: V
+ var value: V
end
+# A `MapIterator` over a `HashMap`.
class HashMapIterator[K: Object, V]
super MapIterator[K, V]
redef fun is_ok do return _node != null
end
# The set to iterate on
- private var set: HashSet[E]
+ var set: HashSet[E]
# The position in the internal map storage
- private var node: nullable HashSetNode[E] = null
+ var node: nullable HashSetNode[E] = null
init
do
super IndexedIterator[E]
redef fun item do return _node.item
+ # Set item `e` at self `index`.
fun item=(e: E) do _node.item = e
redef fun is_ok do return not _node == null
# Get the element after the last one.
var after: E
+ # assert [1..10].has(5)
+ # assert [1..10].has(10)
+ # assert not [1..10[.has(10)
redef fun has(item) do return item >= first and item <= last
+ # assert [1..1].has_only(1)
+ # assert not [1..10].has_only(1)
redef fun has_only(item) do return first == item and item == last or is_empty
+ # assert [1..10].count(1) == 1
+ # assert [1..10].count(0) == 0
redef fun count(item)
do
if has(item) then
redef fun iterator do return new IteratorRange[E](self)
+ # assert [1..10].length == 10
+ # assert [1..10[.length == 9
+ # assert [1..1].length == 1
+ # assert [1..-10].length == 0
redef fun length
do
+ if is_empty then return 0
var nb = first.distance(after)
if nb > 0 then
return nb
end
end
+ # assert not [1..10[.is_empty
+ # assert not [1..1].is_empty
+ # assert [1..-10].is_empty
redef fun is_empty do return first >= after
# Create a range [`from`, `to`].
- # The syntax `[from..to[` is equivalent.
- init(from: E, to: E)
- do
+ # The syntax `[from..to]` is equivalent.
+ #
+ # var a = [10..15]
+ # var b = new Range[Int] (10,15)
+ # assert a == b
+ # assert a.to_a == [10, 11, 12, 13, 14, 15]
+ init(from: E, to: E) is old_style_init do
first = from
last = to
after = to.successor(1)
# Create a range [`from`, `to`[.
# The syntax `[from..to[` is equivalent.
+ #
+ # var a = [10..15[
+ # var b = new Range[Int].without_last(10,15)
+ # assert a == b
+ # assert a.to_a == [10, 11, 12, 13, 14]
init without_last(from: E, to: E)
do
first = from
last = to.predecessor(1)
after = to
end
+
+ # Two ranges are equals if they have the same first and last elements.
+ #
+ # var a = new Range[Int](10, 15)
+ # var b = new Range[Int].without_last(10, 15)
+ # assert a == [10..15]
+ # assert a == [10..16[
+ # assert not a == [10..15[
+ # assert b == [10..15[
+ # assert b == [10..14]
+ # assert not b == [10..15]
+ redef fun ==(o) do
+ return o isa Range[E] and self.first == o.first and self.last == o.last
+ end
+
+ # var a = new Range[Int](10, 15)
+ # assert a.hash == 455
+ # var b = new Range[Int].without_last(10, 15)
+ # assert b.hash == 432
+ redef fun hash do
+ # 11 and 23 are magic numbers empirically determined to be not so bad.
+ return first.hash * 11 + last.hash * 23
+ end
end
private class IteratorRange[E: Discrete]
# Iterator on ranges.
super Iterator[E]
- private var range: Range[E]
+ var range: Range[E]
redef var item is noinit
redef fun is_ok do return _item < _range.after
var arguments: nullable Array[String]
# Launch a command with some arguments
- init(command: String, arguments: String...)
- do
+ init(command: String, arguments: String...) is old_style_init do
self.command = command
self.arguments = arguments
execute
class IProcess
super Process
super IStream
+
+ # File Descriptor used for the input.
var stream_in: FDIStream is noinit
redef fun close do stream_in.close
class OProcess
super Process
super OStream
+
+ # File Descriptor used for the output.
var stream_out: OStream is noinit
redef fun close do stream_out.close
end
redef class NativeString
+ # Execute self as a shell command.
+ #
+ # See the posix function system(3).
fun system: Int is extern "string_NativeString_NativeString_system_0"
end
# The FILE *.
private var file: nullable NativeFile = null
+ # The status of a file. see POSIX stat(2).
fun file_stat: FileStat do return _file.file_stat
# File descriptor of this file
redef fun close
do
- var i = _file.io_close
+ _file.io_close
_buffer.clear
end_reached = true
end
redef fun close
do
- var i = _file.io_close
+ _file.io_close
_is_writable = false
end
###############################################################################
+# Standard input stream.
class Stdin
super IFStream
redef fun poll_in: Bool is extern "file_stdin_poll_in"
end
+# Standard output stream.
class Stdout
super OFStream
init do
end
end
+# Standard error stream.
class Stderr
super OFStream
init do
redef fun -(i) is intern
redef fun *(i) is intern
redef fun /(i) is intern
+
+ # Modulo of `self` with `i`.
+ #
+ # Finds the remainder of division of `self` by `i`.
+ #
+ # assert 5 % 2 == 1
+ # assert 10 % 2 == 0
fun %(i: Int): Int is intern
redef fun zero do return 0
end
redef class Float
+
+ # Returns the non-negative square root of `self`.
+ #
+ # assert 9.0.sqrt == 3.0
+ # #assert 3.0.sqrt == 1.732
+ # assert 1.0.sqrt == 1.0
+ # assert 0.0.sqrt == 0.0
fun sqrt: Float is extern "kernel_Float_Float_sqrt_0"
+
+ # Computes the cosine of `self` (expressed in radians).
+ #
+ # #assert pi.cos == -1.0
fun cos: Float is extern "kernel_Float_Float_cos_0"
+
+ # Computes the sine of `self` (expressed in radians).
+ #
+ # #assert pi.sin == 0.0
fun sin: Float is extern "kernel_Float_Float_sin_0"
+
+ # Computes the cosine of x (expressed in radians).
+ #
+ # #assert 0.0.tan == 0.0
fun tan: Float is extern "kernel_Float_Float_tan_0"
+
+ # Computes the arc cosine of `self`.
+ #
+ # #assert 0.0.acos == pi / 2.0
fun acos: Float is extern "kernel_Float_Float_acos_0"
+
+ # Computes the arc sine of `self`.
+ #
+ # #assert 1.0.asin == pi / 2.0
fun asin: Float is extern "kernel_Float_Float_asin_0"
+
+ # Computes the arc tangent of `self`.
+ #
+ # #assert 0.0.tan == 0.0
fun atan: Float is extern "kernel_Float_Float_atan_0"
+
+ # Returns the absolute value of `self`.
+ #
+ # assert 12.0.abs == 12.0
+ # assert (-34.56).abs == 34.56
+ # assert -34.56.abs == -34.56
fun abs: Float `{ return fabs(recv); `}
+ # Returns `self` raised at `e` power.
+ #
+ # #assert 2.0.pow(0.0) == 1.0
+ # #assert 2.0.pow(3.0) == 8.0
+ # #assert 0.0.pow(9.0) == 0.0
fun pow(e: Float): Float is extern "kernel_Float_Float_pow_1"
+
+ # Returns the logarithm of `self`.
+ #
+ # assert 0.0.log.is_inf == -1
+ # #assert 1.0.log == 0.0
fun log: Float is extern "kernel_Float_Float_log_0"
+
+ # Returns **e** raised to `self`.
fun exp: Float is extern "kernel_Float_Float_exp_0"
# assert 1.1.ceil == 2.0
# Returns a random `Float` in `[0.0 .. self[`.
fun rand: Float is extern "kernel_Float_Float_rand_0"
- fun hypot_with( b : Float ) : Float is extern "hypotf"
+ # Returns the euclidean distance from `b`.
+ fun hypot_with(b : Float): Float is extern "hypotf"
+
+ # Returns true is self is not a number.
fun is_nan: Bool is extern "isnan"
# Is the float an infinite value
end
end
+# Computes the arc tangent given `x` and `y`.
+#
+# assert atan2(-0.0, 1.0) == -0.0
+# assert atan2(0.0, 1.0) == 0.0
fun atan2(x: Float, y: Float): Float is extern "kernel_Any_Any_atan2_2"
+
+# Approximate value of **pi**.
fun pi: Float is extern "kernel_Any_Any_pi_0"
# Initialize the pseudo-random generator with the given seed.
var cstr = text.substring_from(from).to_cstring
var eflags = gather_eflags
var match = self.native_match
- var matches = new Array[Match]
var res = native.regexec(cstr, 1, match, eflags)
# Right child of the node
var right: String
- init(l: String, r: String) do
+ init(l: String, r: String) is old_style_init do
left = l
right = r
length = l.length + r.length
redef fun +(o) do
var s = o.to_s
- var mlen = length
var slen = s.length
if s isa Concat then
return new Concat(self, s)
# the Rope traversal.
var subs: IndexedIterator[String]
- init(root: RopeString) do
+ init(root: RopeString) is old_style_init do
pos = root.length - 1
subs = new ReverseRopeSubstrings(root)
ns = subs.item
# Position (char) in the Rope (0-indexed)
var pos: Int
- init(root: RopeString) do
+ init(root: RopeString) is old_style_init do
subs = new RopeSubstrings(root)
pns = 0
str = subs.item
# Current leaf
var str: String is noinit
- init(root: RopeString) do
+ init(root: RopeString) is old_style_init do
var r = new RopeIterPiece(root, false, true, null)
pos = root.length - 1
var lnod: String = root
# Did we attain the buffered part ?
var nsstr_done = false
- init(str: RopeBuffer) do
+ init(str: RopeBuffer) is old_style_init do
iter = str.str.substrings
nsstr = new FlatString.with_infos(str.ns, str.rpos - str.dumped, str.dumped, str.rpos - 1)
if str.length == 0 then nsstr_done = true
# Current leaf
var str: String is noinit
- init(root: RopeString) do
+ init(root: RopeString) is old_style_init do
var r = new RopeIterPiece(root, true, false, null)
pos = 0
max = root.length - 1
var tgt: RopeString
- init(s: RopeString) do tgt = s
+ init(s: RopeString) is old_style_init do tgt = s
redef fun [](i) do
return tgt[i]
end
+# An Iterator over a RopeBuffer.
class RopeBufferIter
super IndexedIterator[Char]
+ # Subiterator.
var sit: IndexedIterator[Char]
+ # Native string iterated over.
var ns: NativeString
+ # Current position in `ns`.
var pns: Int
+ # Maximum position iterable.
var maxpos: Int
redef var index: Int
- init(t: RopeBuffer) do
+ # Init the iterator from a RopeBuffer.
+ init(t: RopeBuffer) is old_style_init do
ns = t.ns
maxpos = t.rpos
sit = t.str.chars.iterator
index = 0
end
+ # Init the iterator from a RopeBuffer starting from `pos`.
init from(t: RopeBuffer, pos: Int) do
ns = t.ns
maxpos = t.length
end
end
+# Reverse iterator over a RopeBuffer.
class RopeBufferReviter
super IndexedIterator[Char]
+ # Subiterator.
var sit: IndexedIterator[Char]
+ # Native string iterated over.
var ns: NativeString
+ # Current position in `ns`.
var pns: Int
redef var index: Int
- init(tgt: RopeBuffer) do
+ # Init the iterator from a RopeBuffer.
+ init(tgt: RopeBuffer) is old_style_init do
sit = tgt.str.chars.reverse_iterator
pns = tgt.rpos - 1
index = tgt.length - 1
ns = tgt.ns
end
+ # Init the iterator from a RopeBuffer starting from `pos`.
init from(tgt: RopeBuffer, pos: Int) do
sit = tgt.str.chars.reverse_iterator_from(pos - tgt.rpos - tgt.dumped)
pns = pos - tgt.str.length
end
end
+# An Input/Output Stream
interface IOStream
super IStream
super OStream
##############################################################"
+# A File Descriptor Stream.
abstract class FDStream
super IOS
# File description
private fun native_write_char(i: Int, c: Char): Int is extern "stream_FDStream_FDStream_native_write_char_2"
end
+# An Input File Descriptor Stream.
class FDIStream
super FDStream
super IStream
end
end
+# An Output File Descriptor Stream.
class FDOStream
super FDStream
super OStream
end
end
+# An Input/Output File Descriptor Stream.
class FDIOStream
super FDIStream
super FDOStream
content.add(str.to_s)
end
+ # Is the stream closed?
protected var closed = false
+
redef fun close do closed = true
end
redef var length: Int = 0
- init do end
-
redef fun output
do
var i = 0
type SELFTYPE: Text
- private var target: SELFTYPE
+ var target: SELFTYPE
redef fun is_empty do return target.is_empty
end
+# A `String` holds and manipulates an arbitrary sequence of characters.
+#
+# String objects may be created using literals.
+#
+# assert "Hello World!" isa String
abstract class String
super Text
# assert "abc" * 0 == ""
fun *(i: Int): SELFTYPE is abstract
+ # Insert `s` at `pos`.
+ #
+ # assert "helloworld".insert_at(" ", 5) == "hello world"
fun insert_at(s: String, pos: Int): SELFTYPE is abstract
redef fun substrings: Iterator[String] is abstract
end
+# A mutable sequence of characters.
abstract class Buffer
super Text
# Create a new empty string.
init do end
+ # Create a new string copied from `s`.
init from(s: Text)
do
capacity = s.length + 1
redef fun append(s)
do
- var my_items = target.items
var s_length = s.length
if target.capacity < s.length then enlarge(s_length + target.length)
end
extern class NativeString `{ char* `}
# Creates a new NativeString with a capacity of `length`
new(length: Int) is intern
+
+ # Get char at `index`.
fun [](index: Int): Char is intern
+
+ # Set char `item` at index.
fun []=(index: Int, item: Char) is intern
+
+ # Copy `self` to `dest`.
fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
# Position of the first nul character.
while self[l] != '\0' do l += 1
return l
end
+
+ # Parse `self` as an Int.
fun atoi: Int is intern
+
+ # Parse `self` as a Float.
fun atof: Float is extern "atof"
redef fun to_s
return to_s_with_length(cstring_length)
end
+ # Returns `self` as a String of `length`.
fun to_s_with_length(length: Int): FlatString
do
assert length >= 0
return str
end
+ # Returns `self` as a new String.
fun to_s_with_copy: FlatString
do
var length = cstring_length
return res
end
+ # Is `self` in `s`?
protected fun is_in(s: Text): Bool do return search_index_in(s, 0) != -1
end
private fun compute_gs
do
- var x = _motif
var m = _length
var suff = suffixes
var i = 0
# Time since epoch
extern class TimeT `{time_t`}
+
+ # Returns Time since epoch from now.
new `{ return time(NULL); `}
+
+ # Returns Time since epoch from `i` (expressed in seconds).
new from_i(i: Int) `{ return i; `}
+ # Update current time.
fun update `{ time(&recv); `}
+ # Convert `self` to a human readable String.
fun ctime: String import NativeString.to_s_with_copy `{
return NativeString_to_s_with_copy( ctime(&recv) );
`}
fun difftime(start: TimeT): Float `{ return difftime(recv, start); `}
redef fun to_s do return ctime.replace("\n", "")
+
+ # Convert self to Int (expressed as seconds since epoch).
fun to_i: Int `{ return (int)recv; `}
end
# Time structure
extern class Tm `{struct tm *`}
+
+ # Create a new Time structure expressed in Coordinated Universal Time (UTC).
new gmtime `{
struct tm *tm;
time_t t = time(NULL);
tm = gmtime(&t);
return tm;
`}
+
+ # Create a new Time structure expressed in UTC from `t`.
new gmtime_from_timet(t: TimeT) `{
struct tm *tm;
tm = gmtime(&t);
return tm;
`}
+ # Create a new Time structure expressed in the local timezone.
new localtime `{
struct tm *tm;
time_t t = time(NULL);
tm = localtime(&t);
return tm;
`}
+
+ # Create a new Time structure expressed in the local timezone from `t`.
new localtime_from_timet(t: TimeT) `{
struct tm *tm;
tm = localtime(&t);
return tm;
`}
+ # Convert `self` as a TimeT.
fun to_timet: TimeT `{ return mktime(recv); `}
+ # Seconds after the minute.
fun sec: Int `{ return recv->tm_sec; `}
+
+ # Minutes after the hour.
fun min: Int `{ return recv->tm_min; `}
+
+ # hours since midnight.
fun hour: Int `{ return recv->tm_hour; `}
+
+ # Day of the month.
fun mday: Int `{ return recv->tm_mday; `}
+
+ # Months since January.
fun mon: Int `{ return recv->tm_mon; `}
+
+ # Years since 1900.
fun year: Int `{ return recv->tm_year; `}
+
+ # Days since Sunday.
fun wday: Int `{ return recv->tm_wday; `}
+
+ # Days since January 1st.
fun yday: Int `{ return recv->tm_yday; `}
+
+ # Is `self` in Daylight Saving Time.
fun is_dst: Bool `{ return recv->tm_isdst; `}
+ # Convert `self` to a human readable String.
fun asctime: String import NativeString.to_s_with_copy `{
return NativeString_to_s_with_copy( asctime(recv) );
`}
+
+ # Convert `self` to a human readable String corresponding to `format`.
+ # TODO document allowed format.
fun strftime(format: String): String import String.to_cstring, NativeString.to_s `{
char* buf, *c_format;
size_t res;
-Runtime error: Cast failed. Expected `E`, got `Bool` (../lib/standard/collection/array.nit:782)
+Runtime error: Cast failed. Expected `E`, got `Bool` (../lib/standard/collection/array.nit:785)
NativeString
N
Nit