Merge: Adds a module for logging requests
authorJean Privat <jean@pryen.org>
Tue, 1 Dec 2015 14:07:35 +0000 (09:07 -0500)
committerJean Privat <jean@pryen.org>
Tue, 1 Dec 2015 14:07:35 +0000 (09:07 -0500)
Title pretty much says it all

Pull-Request: #1869
Reviewed-by: Alexis Laferrière <alexis.laf@xymus.net>
Reviewed-by: Jean Privat <jean@pryen.org>
Reviewed-by: Lucas Bajolet <r4pass@hotmail.com>

34 files changed:
contrib/benitlux/src/benitlux_daily.nit
contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/first.md [new file with mode: 0644]
contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/index.md [new file with mode: 0644]
contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/second.md [new file with mode: 0644]
contrib/nitiwiki/src/wiki_html.nit
contrib/nitrpg/src/achievements.nit
contrib/nitrpg/src/events.nit
contrib/nitrpg/src/game.nit
contrib/nitrpg/src/reactors.nit
contrib/nitrpg/src/statistics.nit
contrib/nitrpg/src/templates/templates_base.nit
lib/android/audio.nit
lib/console.nit
lib/core/collection/array.nit
lib/core/collection/hash_collection.nit
lib/core/text/abstract_text.nit
lib/github/api.nit
lib/github/events.nit
lib/libevent.nit
lib/mongodb/mongodb.nit
lib/mongodb/native_mongodb.nit
src/ffi/cpp.nit
src/modelize/modelize_property.nit
src/rapid_type_analysis.nit
tests/base_prot_sig.nit
tests/sav/base_prot_sig_alt1.res
tests/sav/base_prot_sig_alt2.res
tests/sav/base_prot_sig_alt3.res
tests/sav/base_prot_sig_alt4.res
tests/sav/base_prot_sig_alt5.res
tests/sav/base_prot_sig_alt6.res
tests/sav/base_prot_sig_alt7.res
tests/sav/nituml_args3.res
tests/sav/nituml_args4.res

index d242751..f9e8400 100644 (file)
@@ -89,9 +89,19 @@ class Benitlux
                # Get the web page
                var body = download_html_page
 
+               if opts.verbose.value > 1 then
+                       print " # Body"
+                       print body
+               end
+
                # Parse the Web page and get the available beers
                var beers = parse_beers_from_html(body)
 
+               if opts.verbose.value > 0 then
+                       print " # Beers"
+                       print beers
+               end
+
                var db = new DB.open(db_path)
 
                # Update the database with the beers of the day
@@ -112,6 +122,10 @@ class Benitlux
                # Set the email if desired
                if send_emails then
                        var subs = db.subscribers
+                       if opts.verbose.value > 0 then
+                               print " # Subscribers"
+                               print subs
+                       end
                        send_emails_to subs
                end
 
@@ -152,9 +166,14 @@ class Benitlux
                var of_interest = body.substring(start, finish-start)
                var lines = of_interest.strip_tags.to_clean_lines
 
+               if opts.verbose.value > 0 then
+                       print " # Lines"
+                       print lines
+               end
+
                var beers = new HashSet[Beer]
                for line in lines do
-                       var parts = line.split(" - ")
+                       var parts = line.split("- ")
                        if parts.length >= 2 then
                                beers.add new Beer(parts[0].trim, parts[1].trim)
                        end
@@ -202,16 +221,23 @@ redef class OptionContext
        # Shall we mail the mailing list?
        var send_emails = new OptionBool("Send emails to subscribers", "-e", "--email")
 
+       # Display more debug messages
+       var verbose = new OptionCount("Display extra debug messages", "-v")
+
        # Print the usage message
        var help = new OptionBool("Print this help message", "-h", "--help")
 
-       redef init do add_option(send_emails, help)
+       redef init do add_option(send_emails, verbose, help)
+end
+
+redef class Sys
+       # Command line options
+       var opts = new OptionContext
 end
 
 # Avoid executing when running tests
 if "NIT_TESTING".environ == "true" then exit 0
 
-var opts = new OptionContext
 opts.parse args
 if not opts.errors.is_empty or opts.help.value == true then
        print opts.errors.join("\n")
diff --git a/contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/first.md b/contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/first.md
new file mode 100644 (file)
index 0000000..c61423f
--- /dev/null
@@ -0,0 +1 @@
+first page
diff --git a/contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/index.md b/contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/index.md
new file mode 100644 (file)
index 0000000..0a918d5
--- /dev/null
@@ -0,0 +1,3 @@
+# A independant trail
+
+a [[trail: first]] and a [[trail: second]] page.
diff --git a/contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/second.md b/contrib/nitiwiki/examples/nitiwiki/pages/section/other_section/second.md
new file mode 100644 (file)
index 0000000..ce04f0f
--- /dev/null
@@ -0,0 +1 @@
+a second page
index 05c06f9..8042af6 100644 (file)
@@ -313,17 +313,21 @@ redef class WikiArticle
 
                var res = new Template
                res.add "<ul class=\"trail\">"
-               if pos > 0 then
-                       var target = flat[pos-1]
-                       res.add "<li>{target.a_from(self, "prev")}</li>"
-               end
                var parent = wiki.trails.parent(self)
+               # Up and prev are disabled on a root
                if parent != null then
+                       if pos > 0 then
+                               var target = flat[pos-1]
+                               res.add "<li>{target.a_from(self, "prev")}</li>"
+                       end
                        res.add "<li>{parent.a_from(self, "up")}</li>"
                end
                if pos < flat.length - 1 then
                        var target = flat[pos+1]
-                       res.add "<li>{target.a_from(self, "next")}</li>"
+                       # Only print the next if it is not a root
+                       if target.parent != null then
+                               res.add "<li>{target.a_from(self, "next")}</li>"
+                       end
                end
                res.add "</ul>"
 
index 9b18a6b..5ce317a 100644 (file)
@@ -74,10 +74,15 @@ end
 class Achievement
        super GameEntity
 
-       redef var key is lazy do return "achievements" / id
 
        redef var game
 
+       redef var key is lazy do
+               var owner = self.owner
+               if owner == null then return id
+               return "{owner.key}-{id}"
+       end
+
        # Uniq ID for this achievement.
        var id: String
 
@@ -93,6 +98,9 @@ class Achievement
        # Is this achievement unlocked by somebody?
        var is_unlocked: Bool is lazy do return not load_events.is_empty
 
+       # Game entity this achievement is about.
+       var owner: nullable GameEntity = null
+
        # Init `self` from a `json` object.
        #
        # Used to load achievements from storage.
@@ -106,6 +114,8 @@ class Achievement
                json["name"] = name
                json["desc"] = desc
                json["reward"] = reward
+               json["game"] = game.key
+               if owner != null then json["owner"] = owner.key
                return json
        end
 end
@@ -346,7 +356,7 @@ abstract class PlayerXCommits
                if not event.action == "closed" then return
                if not event.pull.merged then return
                var player = event.pull.user.player(game)
-               if player.stats["commits"] == threshold then
+               if player.stats["commits"] >= threshold then
                        var a = new_achievement(game)
                        player.unlock_achievement(a, event)
                end
@@ -447,7 +457,7 @@ end
 class Player1KComments
        super PlayerXComments
 
-       redef var id = "player_1000__comments"
+       redef var id = "player_1000_comments"
        redef var name = "You sir, talk a lot!"
        redef var desc = "Comment 1000 times on issues."
        redef var reward = 1000
index d1ba25a..bd1ee58 100644 (file)
@@ -24,8 +24,10 @@ import game
 
 redef class GameEntity
 
-       # Saves `event` in `self`.
-       fun add_event(event: GameEvent) do event.save_in(self.key)
+       fun add_event(event: GameEvent) do
+               event.owner = self
+               event.save
+       end
 
        # List all events registered in this entity.
        #
@@ -61,10 +63,12 @@ end
 class GameEvent
        super GameEntity
 
-       redef var key is lazy do return "events" / internal_id
 
        redef var game
 
+       # Entity this event belongs to.
+       var owner: nullable GameEntity = null
+
        # String used to dissociate events in the display.
        var kind: String
 
@@ -76,6 +80,8 @@ class GameEvent
        # GameEvent uniq id used for storage.
        var internal_id: String is noinit
 
+       redef var key = internal_id is lazy
+
        # Date and time of the event.
        var time: ISODate is noinit, writable
 
@@ -100,6 +106,8 @@ class GameEvent
                json["kind"] = kind
                json["time"] = time.to_s
                json["data"] = data
+               json["game"] = game.key
+               if owner != null then json["owner"] = owner.key
                return json
        end
 end
index a109949..2924e46 100644 (file)
@@ -65,20 +65,20 @@ class Game
 
        redef fun game do return self
 
-       # Returns the repo `full_name`.
-       #
-       # Example: `"nitlang/nit"`
-       redef fun key do return repo.full_name
-
        # We need a `GithubAPI` client to load Github data.
        var api: GithubAPI
 
        # A game takes place in a `github::Repo`.
        var repo: Repo
 
+       # Game name
+       var name: String = repo.full_name is lazy
+
        # Directory where game data are stored.
        var game_dir: String is lazy do return "nitrpg_data" / repo.full_name
 
+       redef var key = name is lazy
+
        # Used for data storage.
        #
        # File are stored in `game_dir`.
@@ -92,6 +92,12 @@ class Game
        # Used to load entities from saved data.
        fun from_json(json: JsonObject) do end
 
+       redef fun to_json do
+               var json = super
+               json["name"] = name
+               return json
+       end
+
        # Create a player from a Github `User`.
        #
        # Or return the existing one from game data.
@@ -180,9 +186,6 @@ end
 class Player
        super GameEntity
 
-       # Key is based on player `name`.
-       redef var key is lazy do return "players" / name
-
        redef var game
 
        # FIXME contructor should be private
@@ -195,6 +198,8 @@ class Player
        # The name is also used to load the user data lazilly from Github API.
        var name: String
 
+       redef var key = name is lazy
+
        # Player amount of nitcoins.
        #
        # Nitcoins is the currency used in nitrpg.
@@ -218,6 +223,7 @@ class Player
 
        redef fun to_json do
                var json = super
+               json["game"] = game.key
                json["name"] = name
                json["nitcoins"] = nitcoins
                return json
index 7073c98..e2717f4 100644 (file)
@@ -58,7 +58,7 @@ redef class PullRequestEvent
 
        # Rewards player for opened pull requests.
        redef fun react_player_event(r, game) do
-               if action == "opened" then
+               if action == "opened" or action == "reopened" then
                        react_pull_open(r, game)
                else if action == "closed" then
                        react_pull_close(r, game)
@@ -95,14 +95,18 @@ redef class IssueCommentEvent
        # Rewards player for review comments.
        #
        # TODO only give nitcoins if reviewers < 2
+       # TODO give more points to first reviewer
        redef fun react_player_event(r, game) do
                if comment.is_ack then
                        react_player_review(r, game)
                end
        end
 
+       # TODO same player should not be authorized to review multiple times? How to handle rerols?
        private fun react_player_review(r: PlayerReactor, game: Game) do
+               if issue.state == "closed" then return
                var player = comment.user.player(game)
+               if issue.user == player.user then return
                player.nitcoins += r.nc_pull_review
                player.save
                var event = player_reward_event("pull_review", player, r.nc_pull_review)
index b7d3530..153b5cd 100644 (file)
@@ -79,49 +79,32 @@ class GameStatsManager
        # The GameEntity monitored by these statistics.
        var owner: GameEntity
 
-       redef var key = "stats"
+       # Current date to extract stats
+       private var date = new Tm.gmtime
 
        # Returns the `GameStats` instance for the overall statistics.
-       var overall: GameStats is lazy do
-               return load_stats_for("all")
-       end
+       var overall: GameStats = load_stats_for("all") is lazy
 
        # Returns the `GameStats` instance for the current year statistics.
-       var yearly: GameStats is lazy do
-               var date = new Tm.gmtime
-               var key = date.strftime("%Y")
-               return load_stats_for(key)
-       end
+       var yearly: GameStats = load_stats_for(date.strftime("%Y")) is lazy
 
        # Returns the `GameStats` instance for the current month statistics.
-       var monthly: GameStats is lazy do
-               var date = new Tm.gmtime
-               var key = date.strftime("%Y-%m")
-               return load_stats_for(key)
-       end
+       var monthly: GameStats = load_stats_for(date.strftime("%Y-%m")) is lazy
 
        # Returns the `GameStats` instance for the current day statistics.
-       var daily: GameStats is lazy do
-               var date = new Tm.gmtime
-               var key = date.strftime("%Y-%m-%d")
-               return load_stats_for(key)
-       end
+       var daily: GameStats = load_stats_for(date.strftime("%Y-%m-%d")) is lazy
 
        # Returns the `GameStats` instance for the current week statistics.
-       var weekly: GameStats is lazy do
-               var date = new Tm.gmtime
-               var key = date.strftime("%Y-W%U")
-               return load_stats_for(key)
-       end
+       var weekly: GameStats = load_stats_for(date.strftime("%Y-W%U")) is lazy
 
        # Load statistics for a `period` key.
        fun load_stats_for(period: String): GameStats do
                var key = owner.key / self.key / period
                if not game.store.has_key(key) then
-                       return new GameStats(game, period)
+                       return new GameStats(game, period, owner)
                end
                var json = game.store.load_object(key)
-               return new GameStats.from_json(game, period, json)
+               return new GameStats.from_json(game, period, owner, json)
        end
 
        redef fun [](key) do return overall[key]
@@ -168,19 +151,28 @@ class GameStats
 
        redef var game
 
-       # The pedriod these stats are about.
+       # The period these stats are about.
        var period: String
 
-       redef fun key do return period
+       # The game entity these stats are about.
+       var owner: GameEntity
+
+       redef var key = "{owner.key}-{period}" is lazy
 
        # Load `self` from saved data.
-       init from_json(game: Game, period: String, json: JsonObject) do
-               for k, v in json do self[k] = v.as(Int)
+       init from_json(game: Game, period: String, owner: GameEntity, json: JsonObject) do
+               var values = json.get_or_null("values")
+               if not values isa JsonObject then return
+               for k, v in values do self[k] = v.as(Int)
        end
 
        redef fun to_json do
-               var obj = new JsonObject
-               for k, v in self do obj[k] = v
+               var obj = super
+               obj["period"] = period
+               obj["owner"] = owner.key
+               var values = new JsonObject
+               values.recover_with(self)
+               obj["values"] = values
                return obj
        end
 
index 8b85a4d..a4f40d9 100644 (file)
@@ -34,9 +34,6 @@ redef class Game
 
        redef fun url do return "{root_url}/games" / key
 
-       # Displayed name.
-       fun name: String do return repo.full_name
-
        # Return a HTML link to this Game.
        fun link: String do return "<a href=\"{url}\">{name}</a>"
 end
index 9cc54d7..649a95d 100644 (file)
@@ -646,7 +646,7 @@ redef class App
        var default_soundpool: SoundPool is lazy do return new SoundPool
 
        # Get the native audio manager
-       fun audio_manager: NativeAudioManager import native_activity in "Java" `{
+       private fun audio_manager: NativeAudioManager import native_activity in "Java" `{
                return (AudioManager)App_native_activity(self).getSystemService(Context.AUDIO_SERVICE);
        `}
 
index 0020b7a..b8fe277 100644 (file)
@@ -337,3 +337,75 @@ redef class String
        # WARNING: SEE: `TermCharFormat`
        fun underline: String do return apply_format(normal.underline)
 end
+
+# A dynamic progressbar displayable in console.
+#
+# Example:
+# ~~~nitish
+# var max = 10
+# var current = 0
+# var pb = new TermProgress(max, current)
+#
+# pb.display
+# for i in [current + 1 .. max] do
+#      nanosleep(1, 0)
+#      pb.update(i)
+# end
+#
+# print "\ndone"
+# ~~~
+#
+# Progressbar can accept metadata to display a small amount of data.
+#
+# Example with metadata:
+# ~~~nitish
+# var pb = new TermProgress(10, 0)
+# for i in [0..10] do
+#      pb.update(i, "Step {i}")
+# end
+# ~~~
+class TermProgress
+
+       # Max value of the progress bar (business value).
+       var max_value: Int
+
+       # Current value of the progress bar (business value).
+       var current_value: Int
+
+       # Number of columns used to display the progress bar.
+       var max_columns = 70 is writable
+
+       # Get the current percent value.
+       fun current_percentage: Int do
+               return current_value * 100 / max_value
+       end
+
+       # Display the progress bar.
+       #
+       # `metadata`  can be used to pass a small amount of data to display after
+       # the progressbar.
+       fun display(metadata: nullable String) do
+               var percent = current_percentage
+               var p = current_value * max_columns / max_value
+               printn "\r{percent}% ["
+               for i in [1..max_columns] do
+                       if i < p then
+                               printn "="
+                       else if i == p then
+                               printn ">"
+                       else
+                               printn " "
+                       end
+               end
+               printn "]"
+               if metadata != null then printn " ({metadata})"
+       end
+
+       # Update and display the progresssbar.
+       #
+       # See `display`.
+       fun update(new_current: Int, metadata: nullable String) do
+               current_value = new_current
+               display(metadata)
+       end
+end
index ce89435..b65f282 100644 (file)
@@ -130,7 +130,7 @@ abstract class AbstractArrayRead[E]
                end
        end
 
-       redef fun iterator: ArrayIterator[E] do
+       redef fun iterator: IndexedIterator[E] do
                var res = _free_iterator
                if res == null then return new ArrayIterator[E](self)
                res._index = 0
@@ -653,7 +653,7 @@ private class ArraySetIterator[E]
 
        redef fun item: E do return _iter.item
 
-       var iter: ArrayIterator[E]
+       var iter: Iterator[E]
 end
 
 
index 890ecd9..ac4a8a1 100644 (file)
@@ -238,7 +238,7 @@ class HashMap[K, V]
                end
        end
 
-       redef fun iterator: HashMapIterator[K, V] do return new HashMapIterator[K,V](self)
+       redef fun iterator do return new HashMapIterator[K,V](self)
 
        redef fun length do return _the_length
 
index 64c22c0..e114d35 100644 (file)
@@ -68,7 +68,7 @@ abstract class Text
        fun substring(from: Int, count: Int): SELFTYPE is abstract
 
        # Iterates on the substrings of self if any
-       fun substrings: Iterator[FlatText] is abstract
+       private fun substrings: Iterator[FlatText] is abstract
 
        # Is the current Text empty (== "")
        #
index 7e7400c..18880ec 100644 (file)
@@ -732,6 +732,12 @@ class Issue
                super
        end
 
+       # Issue id.
+       fun id: Int do return json["id"].as(Int)
+
+       # Set issue id.
+       fun id=(id: Int) do json["id"] = id
+
        # Issue title.
        fun title: String do return json["title"].as(String)
 
@@ -814,10 +820,16 @@ class Issue
                        for obj in array do
                                if not obj isa JsonObject then continue
                                var id = obj["id"].as(Int)
-                               res.add(api.load_issue_comment(repo, id).as(not null))
+                               var comment = api.load_issue_comment(repo, id)
+                               if comment == null then continue
+                               res.add(comment)
                        end
                        page += 1
-                       array = api.get("{key}/comments?page={page}").as(JsonArray)
+                       var json = api.get("{key}/comments?page={page}")
+                       if not json isa JsonArray then
+                               return res
+                       end
+                       array = json
                end
                return res
        end
index df7c8c3..543a786 100644 (file)
@@ -38,6 +38,12 @@ class GithubEvent
                self.json = json
        end
 
+       # Event ID from Github.
+       fun id: String do return json["id"].as(String)
+
+       # Set id.
+       fun id=(id: String) do json["id"] = id
+
        # Action performed by the event.
        fun action: String do return json["action"].as(String)
 
index 9cbe38e..c01d417 100644 (file)
@@ -346,6 +346,10 @@ extern class ConnectionListener `{ struct evconnlistener * `}
 
                struct hostent *hostent = gethostbyname(address);
 
+               if (!hostent) {
+                       return NULL;
+               }
+
                memset(&sin, 0, sizeof(sin));
                sin.sin_family = hostent->h_addrtype;
                sin.sin_port = htons(port);
index 624dc8a..78cd75d 100644 (file)
@@ -55,16 +55,11 @@ in "C header" `{
 # * [Binary JSON spec](http://bsonspec.org/)
 # * [Libbson](http://api.mongodb.org/libbson/1.1.4/)#
 private class BSON
-       super Finalizable
+       super FinalizableOnce
 
        # Native instance pointer.
        var native: NativeBSON
 
-       # Is the native instance valid?
-       #
-       # This is set to false if the `native` is destroyed.
-       var is_alive = true
-
        # Returns a new BSON object initialized from the content of `json`.
        #
        # ~~~
@@ -95,7 +90,6 @@ private class BSON
        end
 
        redef fun to_s do
-               assert is_alive
                var ns = native.to_native_string
                var res = ns.to_s_with_copy
                ns.free # manual free of gc allocated NativeString
@@ -114,16 +108,15 @@ private class BSON
        # assert json["ELS"].as(JsonArray).is_empty
        # ~~~
        fun to_json: JsonObject do
-               assert is_alive
-               return to_s.parse_json.as(JsonObject)
-       end
-
-       redef fun finalize do
-               if is_alive then
-                       native.destroy
-                       is_alive = false
+               var json = to_s.parse_json
+               if json isa JsonParseError then
+                       print json.message
+                       sys.exit 1
                end
+               return json.as(JsonObject)
        end
+
+       redef fun finalize_once do native.destroy
 end
 
 redef class JsonObject
@@ -144,26 +137,14 @@ class MongoError
 
        private var native: BSONError
 
-       # Is the native instance valid?
-       #
-       # This is set to false if the `native` is destroyed.
-       private var is_alive = true
-
        # Logical domain within a library that created the error.
-       fun domain: Int do
-               assert is_alive
-               return native.domain
-       end
+       fun domain: Int do return native.domain
 
        # Domain specific error code.
-       fun code: Int do
-               assert is_alive
-               return native.code
-       end
+       fun code: Int do return native.code
 
        # Human readable error message.
        fun message: String do
-               assert is_alive
                var ns = native.message
                var res = ns.to_s_with_copy
                ns.free
@@ -211,21 +192,14 @@ end
 # assert client.server_uri == uri
 # ~~~
 class MongoClient
-       super Finalizable
+       super FinalizableOnce
 
        # Server URI.
        var server_uri: String
 
        private var native: NativeMongoClient is noinit
 
-       # Is the native instance valid?
-       #
-       # This is set to false if the `native` is destroyed.
-       private var is_alive = true
-
-       init do
-               native = new NativeMongoClient(server_uri.to_cstring)
-       end
+       init do native = new NativeMongoClient(server_uri.to_cstring)
 
        # Gets server data.
        #
@@ -236,7 +210,6 @@ class MongoClient
        # assert client.server_status["process"] == "mongod"
        # ~~~
        fun server_status: nullable JsonObject do
-               assert is_alive
                var nbson = native.server_status
                if nbson == null then return null
                var bson = new BSON(nbson)
@@ -253,7 +226,6 @@ class MongoClient
        # assert client.database_names.has("test")
        # ~~~
        fun database_names: Array[String] do
-               assert is_alive
                var res = new Array[String]
                var nas = native.database_names
                if nas == null then return res
@@ -278,25 +250,14 @@ class MongoClient
        # var client = new MongoClient("mongodb://localhost:27017/")
        # assert client.database("test").name == "test"
        # ~~~
-       fun database(name: String): MongoDb do
-               assert is_alive
-               return new MongoDb(self, name)
-       end
+       fun database(name: String): MongoDb do return new MongoDb(self, name)
 
        # Close the connexion and destroy the instance.
        #
        # The reference should not be used beyond this point!
-       fun close do
-               assert is_alive
-               finalize
-       end
+       fun close do finalize_once
 
-       redef fun finalize do
-               if is_alive then
-                       native.destroy
-                       is_alive = false
-               end
-       end
+       redef fun finalize_once do native.destroy
 
        # Last error raised by mongoc.
        fun last_error: nullable MongoError do
@@ -328,7 +289,7 @@ end
 # first document into a collection.
 # There is no need to create a database manually.
 class MongoDb
-       super Finalizable
+       super FinalizableOnce
 
        # `MongoClient` used to load this database.
        var client: MongoClient
@@ -338,14 +299,7 @@ class MongoDb
 
        private var native: NativeMongoDb is noinit
 
-       # Is the native instance valid?
-       #
-       # This is set to false if the `native` is destroyed.
-       private var is_alive = true
-
-       init do
-               native = new NativeMongoDb(client.native, name.to_cstring)
-       end
+       init do native = new NativeMongoDb(client.native, name.to_cstring)
 
        # Lists available collection names.
        #
@@ -358,7 +312,6 @@ class MongoDb
        # assert db.collection_names.has("test")
        # ~~~
        fun collection_names: Array[String] do
-               assert is_alive
                var res = new Array[String]
                var nas = native.collection_names
                if nas == null then return res
@@ -382,7 +335,6 @@ class MongoDb
        # assert col.name == "test"
        # ~~~
        fun collection(name: String): MongoCollection do
-               assert is_alive
                return new MongoCollection(self, name)
        end
 
@@ -394,23 +346,14 @@ class MongoDb
        # assert not db.has_collection("qwerty")
        # ~~~
        fun has_collection(name: String): Bool do
-               assert is_alive
                # TODO handle error
                return native.has_collection(name.to_cstring)
        end
 
        # Drop `self`, returns false if an error occured.
-       fun drop: Bool do
-               assert is_alive
-               return native.drop
-       end
+       fun drop: Bool do return native.drop
 
-       redef fun finalize do
-               if is_alive then
-                       native.destroy
-                       is_alive = false
-               end
-       end
+       redef fun finalize_once do native.destroy
 end
 
 # A Mongo collection.
@@ -419,7 +362,7 @@ end
 # the first document.
 # There is no need to create a database manually.
 class MongoCollection
-       super Finalizable
+       super FinalizableOnce
 
        # Database that collection belongs to.
        var database: MongoDb
@@ -429,11 +372,6 @@ class MongoCollection
 
        private var native: NativeMongoCollection is noinit
 
-       # Is the native instance valid?
-       #
-       # This is set to false if the `native` is destroyed.
-       private var is_alive = true
-
        # Loads a collection.
        #
        # Call `MongoDb::collection` instead.
@@ -471,7 +409,6 @@ class MongoCollection
        # assert doc.has_key("_id")
        # ~~~
        fun insert(doc: JsonObject): Bool do
-               assert is_alive
                var res = native.insert(doc.to_bson.native)
                if res then set_id(doc)
                return res
@@ -481,7 +418,6 @@ class MongoCollection
        #
        # See `insert`.
        fun insert_all(docs: Collection[JsonObject]): Bool do
-               assert is_alive
                var res = true
                for doc in docs do res = insert(doc) and res
                return res
@@ -511,9 +447,12 @@ class MongoCollection
        # assert doc["_id"] == id
        # ~~~
        fun save(doc: JsonObject): Bool do
-               assert is_alive
-               var res = native.save(doc.to_bson.native)
+               var bson = doc.to_bson
+               var nat = bson.native
+               var res = native.save(nat)
                if res then set_id(doc)
+               assert nat != self #FIXME used to avoid GC crashes
+               assert bson != self #FIXME used to avoid GC crashes
                return res
        end
 
@@ -529,7 +468,6 @@ class MongoCollection
        # assert col.remove(sel)
        # ~~~
        fun remove(selector: JsonObject): Bool do
-               assert is_alive
                return native.remove(selector.to_bson.native)
        end
 
@@ -537,7 +475,6 @@ class MongoCollection
        #
        # See `remove`.
        fun remove_all(selector: JsonObject): Bool do
-               assert is_alive
                return native.remove_all(selector.to_bson.native)
        end
 
@@ -555,7 +492,6 @@ class MongoCollection
        # assert col.update(sel, upd)
        # ~~~
        fun update(selector: JsonObject, update: JsonObject): Bool do
-               assert is_alive
                return native.update(
                        selector.to_bson.native,
                        update.to_bson.native)
@@ -582,12 +518,15 @@ class MongoCollection
        # assert col.count(query) > 0
        # ~~~
        fun count(query: JsonObject): Int do
-               assert is_alive
                return native.count(query.to_bson.native)
        end
 
        # Finds the first document that matches `query`.
        #
+       # Params:
+       # * `skip` number of documents to skip
+       # * `limit` number of documents to return
+       #
        # Returns `null` if an error occured. See `Sys::last_mongoc_error`.
        #
        # ~~~
@@ -598,19 +537,28 @@ class MongoCollection
        # var doc = col.find(query)
        # assert doc["foo"] == 10
        # ~~~
-       fun find(query: JsonObject): nullable JsonObject do
-               assert is_alive
+       fun find(query: JsonObject, skip, limit: nullable Int): nullable JsonObject do
                var q = new NativeBSON.from_json_string(query.to_json.to_cstring)
-               var c = native.find(q)
+               var s = skip or else 0
+               var l = limit or else 0
+               var c = native.find(q, s, l)
                q.destroy
                if c == null then return null
                var cursor = new MongoCursor(c)
-               if cursor.is_ok then return cursor.item
-               return null
+               if not cursor.is_ok then
+                       return null
+               end
+               var item = cursor.item
+               assert cursor != self
+               return item
        end
 
        # Finds all the documents matching the `query`.
        #
+       # Params:
+       # * `skip` number of documents to skip
+       # * `limit` number of documents to return
+       #
        # ~~~
        # var client = new MongoClient("mongodb://localhost:27017/")
        # var col = client.database("test").collection("test")
@@ -618,13 +566,17 @@ class MongoCollection
        # query["foo"] = 10
        # assert col.find_all(query).length > 0
        # ~~~
-       fun find_all(query: JsonObject): Array[JsonObject] do
-               assert is_alive
+       fun find_all(query: JsonObject, skip, limit: nullable Int): Array[JsonObject] do
+               var s = skip or else 0
+               var l = limit or else 0
                var res = new Array[JsonObject]
-               var c = native.find(query.to_bson.native)
+               var c = native.find(query.to_bson.native, s, l)
                if c == null then return res
                var cursor = new MongoCursor(c)
-               for item in cursor do res.add item
+               while cursor.is_ok do
+                       res.add cursor.item
+                       cursor.next
+               end
                return res
        end
 
@@ -638,17 +590,13 @@ class MongoCollection
        # assert col.stats["ns"] == "test.test"
        # ~~~
        fun stats: nullable JsonObject do
-               assert is_alive
                var bson = native.stats
                if bson == null then return null
                return new JsonObject.from_bson(new BSON(bson))
        end
 
        # Drops `self`, returns false if an error occured.
-       fun drop: Bool do
-               assert is_alive
-               return native.drop
-       end
+       fun drop: Bool do return native.drop
 
        # Moves `self` to another `database`.
        #
@@ -656,7 +604,6 @@ class MongoCollection
        # this collection after the move.
        # Additional operations will occur on moved collection.
        fun move(database: MongoDb): Bool do
-               assert is_alive
                self.database = database
                return native.rename(database.name.to_cstring, name.to_cstring)
        end
@@ -667,17 +614,11 @@ class MongoCollection
        # to continue using this collection after the rename.
        # Additional operations will occur on renamed collection.
        fun rename(name: String): Bool do
-               assert is_alive
                self.name = name
                return native.rename(database.name.to_cstring, name.to_cstring)
        end
 
-       redef fun finalize do
-               if is_alive then
-                       native.destroy
-                       is_alive = false
-               end
-       end
+       redef fun finalize_once do native.destroy
 end
 
 # A MongoDB query cursor.
@@ -685,37 +626,20 @@ end
 # It wraps up the wire protocol negotation required to initiate a query and
 # retreive an unknown number of documents.
 class MongoCursor
-       super Finalizable
+       super FinalizableOnce
        super Iterator[JsonObject]
 
        private var native: NativeMongoCursor
 
-       # Is the native instance valid?
-       #
-       # This is set to false if the `native` is destroyed.
-       private var is_alive = true
-
        init do next
 
-       redef fun is_ok do
-               assert is_alive
-               return native.more
-       end
+       redef var is_ok = true
 
-       redef fun next do
-               assert is_alive
-               native.next
-       end
+       redef fun next do is_ok = native.next
 
        redef fun item do
-               assert is_alive
                return new JsonObject.from_bson(new BSON(native.current))
        end
 
-       redef fun finalize do
-               if is_alive then
-                       native.destroy
-                       is_alive = false
-               end
-       end
+       redef fun finalize_once do native.destroy
 end
index d25a9ac..fb8b305 100644 (file)
@@ -421,11 +421,11 @@ extern class NativeMongoCollection `{ mongoc_collection_t * `}
        #
        # If you would like to specify options such as a sort order,
        # the query must be placed inside of `{"$query": {}}`.
-       fun find(query: NativeBSON): nullable NativeMongoCursor import
+       fun find(query: NativeBSON, skip, limit: Int): nullable NativeMongoCursor import
                NativeMongoCursor.as nullable, set_mongoc_error `{
                bson_error_t error;
                mongoc_cursor_t *cursor;
-               cursor = mongoc_collection_find(self, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
+               cursor = mongoc_collection_find(self, MONGOC_QUERY_NONE, skip, limit, 0, query, NULL, NULL);
                if (mongoc_cursor_error(cursor, &error)) {
                        NativeMongoCollection_set_mongoc_error(self, &error);
                        return null_NativeMongoCursor();
@@ -506,7 +506,12 @@ extern class NativeMongoCursor `{ mongoc_cursor_t* `}
        # Wrapper for `mongoc_cursor_current()`.
        #
        # Fetches the cursors current document or NULL if there has been an error.
-       fun current: NativeBSON `{ return (bson_t*) mongoc_cursor_current(self); `}
+       fun current: NativeBSON `{
+               // As said in documentation, BSON objects should not be freed manually.
+               bson_t* bson = (bson_t*) mongoc_cursor_current(self);
+               // Copy BSON so we can let the GC free it automatically.
+               return bson_copy(bson);
+       `}
 
        # Wrapper for `mongoc_cursor_next()`.
        #
@@ -519,11 +524,6 @@ extern class NativeMongoCursor `{ mongoc_cursor_t* `}
                return mongoc_cursor_next(self, &doc);
        `}
 
-       # Wrapper for `mongoc_cursor_more()`.
-       #
-       # This function shall indicate if there is more data to be read from the cursor.
-       fun more: Bool `{ return mongoc_cursor_more(self); `}
-
        # Wrapper for `mongoc_cursor_destroy()`.
        #
        # This instance should not be used beyond this point!
index 8bcd56c..13a6e92 100644 (file)
@@ -195,9 +195,9 @@ redef class NitniCallback
        fun compile_callback_to_cpp(mmodule: MModule, mainmodule: MModule) do end
 end
 
-fun cpp_call_context: CppCallContext do return once new CppCallContext
-fun to_cpp_call_context: ToCppCallContext do return once new ToCppCallContext
-fun from_cpp_call_context: FromCppCallContext do return once new FromCppCallContext
+private fun cpp_call_context: CppCallContext do return once new CppCallContext
+private fun to_cpp_call_context: ToCppCallContext do return once new ToCppCallContext
+private fun from_cpp_call_context: FromCppCallContext do return once new FromCppCallContext
 
 redef class MExplicitCall
        redef fun compile_callback_to_cpp(mmodule, mainmodule)
index cd50d4a..afd299f 100644 (file)
@@ -1060,7 +1060,7 @@ redef class AMethPropdef
                        end
                end
 
-               if mysignature.arity > 0 then
+               if nsig != null then
                        # Check parameters visibility
                        for i in [0..mysignature.arity[ do
                                var nt = nsig.n_params[i].n_type
index a87a48f..9a6b117 100644 (file)
@@ -25,7 +25,7 @@ module rapid_type_analysis
 
 import semantize
 
-private import csv # for live_types_to_csv
+import csv # for live_types_to_csv
 private import ordered_tree # for live_methods_to_tree
 
 private import more_collections
index 22d361e..5c399c6 100644 (file)
@@ -18,6 +18,10 @@ class A
        protected fun proA(a: A) do end
        private fun priA(a: A) do end
 
+       fun pubA2: A do abort
+       protected fun proA2: A do abort
+       private fun priA2: A do abort
+
        var vpubA: nullable A is writable, noinit
        protected var vproA: nullable A is protected writable, noinit
        private var vpriA: nullable A is noinit
@@ -30,6 +34,10 @@ class A
        #alt2#protected fun proB(a: B) do end
        private fun priB(a: B) do end
 
+       #alt1#fun pubB2: B do abort
+       #alt2#protected fun proB2: B do abort
+       private fun priB2: B do abort
+
        #alt3#var vpubB: nullable B is writable, noinit
        #alt4#protected var vproB: nullable B is protected writable, noinit
        private var vpriB: nullable B is noinit
index 6d747f4..30dc40c 100644 (file)
@@ -1 +1,2 @@
-alt/base_prot_sig_alt1.nit:29,14: Error: the public property `pubB` cannot contain the private type `B`.
+alt/base_prot_sig_alt1.nit:33,14: Error: the public property `pubB` cannot contain the private type `B`.
+alt/base_prot_sig_alt1.nit:37,13: Error: the public property `pubB2` cannot contain the private type `B`.
index e28956b..f31d97a 100644 (file)
@@ -1 +1,2 @@
-alt/base_prot_sig_alt2.nit:30,24: Error: the protected property `proB` cannot contain the private type `B`.
+alt/base_prot_sig_alt2.nit:34,24: Error: the protected property `proB` cannot contain the private type `B`.
+alt/base_prot_sig_alt2.nit:38,23: Error: the protected property `proB2` cannot contain the private type `B`.
index 6c32a28..aa019c0 100644 (file)
@@ -1,2 +1,2 @@
-alt/base_prot_sig_alt3.nit:33,13--22: Error: the public property `vpubB` cannot contain the private type `B`.
-alt/base_prot_sig_alt3.nit:33,13--22: Error: the public property `vpubB=` cannot contain the private type `B`.
+alt/base_prot_sig_alt3.nit:41,13--22: Error: the public property `vpubB` cannot contain the private type `B`.
+alt/base_prot_sig_alt3.nit:41,13--22: Error: the public property `vpubB=` cannot contain the private type `B`.
index 7a646cb..bb4255d 100644 (file)
@@ -1,2 +1,2 @@
-alt/base_prot_sig_alt4.nit:34,23--32: Error: the protected property `vproB` cannot contain the private type `B`.
-alt/base_prot_sig_alt4.nit:34,23--32: Error: the protected property `vproB=` cannot contain the private type `B`.
+alt/base_prot_sig_alt4.nit:42,23--32: Error: the protected property `vproB` cannot contain the private type `B`.
+alt/base_prot_sig_alt4.nit:42,23--32: Error: the protected property `vproB=` cannot contain the private type `B`.
index 01696e4..071db82 100644 (file)
@@ -1,2 +1,2 @@
-alt/base_prot_sig_alt5.nit:37,6--11: Error: the public property `vpubB2` cannot contain the private type `B`.
-alt/base_prot_sig_alt5.nit:37,6--11: Error: the public property `vpubB2=` cannot contain the private type `B`.
+alt/base_prot_sig_alt5.nit:45,6--11: Error: the public property `vpubB2` cannot contain the private type `B`.
+alt/base_prot_sig_alt5.nit:45,6--11: Error: the public property `vpubB2=` cannot contain the private type `B`.
index f129fb5..154d877 100644 (file)
@@ -1,2 +1,2 @@
-alt/base_prot_sig_alt6.nit:38,16--21: Error: the protected property `vproB2` cannot contain the private type `B`.
-alt/base_prot_sig_alt6.nit:38,16--21: Error: the protected property `vproB2=` cannot contain the private type `B`.
+alt/base_prot_sig_alt6.nit:46,16--21: Error: the protected property `vproB2` cannot contain the private type `B`.
+alt/base_prot_sig_alt6.nit:46,16--21: Error: the protected property `vproB2=` cannot contain the private type `B`.
index 1451e5f..786426c 100644 (file)
@@ -1,10 +1,10 @@
-alt/base_prot_sig_alt7.nit:46,2--10: Error: `private` is the only legal visibility for properties in a private class.
-alt/base_prot_sig_alt7.nit:50,2--10: Error: `private` is the only legal visibility for properties in a private class.
-alt/base_prot_sig_alt7.nit:50,37--45: Error: `private` is the only legal visibility for properties in a private class.
 alt/base_prot_sig_alt7.nit:54,2--10: Error: `private` is the only legal visibility for properties in a private class.
-alt/base_prot_sig_alt7.nit:54,34--42: Error: `private` is the only legal visibility for properties in a private class.
 alt/base_prot_sig_alt7.nit:58,2--10: Error: `private` is the only legal visibility for properties in a private class.
+alt/base_prot_sig_alt7.nit:58,37--45: Error: `private` is the only legal visibility for properties in a private class.
 alt/base_prot_sig_alt7.nit:62,2--10: Error: `private` is the only legal visibility for properties in a private class.
-alt/base_prot_sig_alt7.nit:62,37--45: Error: `private` is the only legal visibility for properties in a private class.
+alt/base_prot_sig_alt7.nit:62,34--42: Error: `private` is the only legal visibility for properties in a private class.
 alt/base_prot_sig_alt7.nit:66,2--10: Error: `private` is the only legal visibility for properties in a private class.
-alt/base_prot_sig_alt7.nit:66,34--42: Error: `private` is the only legal visibility for properties in a private class.
+alt/base_prot_sig_alt7.nit:70,2--10: Error: `private` is the only legal visibility for properties in a private class.
+alt/base_prot_sig_alt7.nit:70,37--45: Error: `private` is the only legal visibility for properties in a private class.
+alt/base_prot_sig_alt7.nit:74,2--10: Error: `private` is the only legal visibility for properties in a private class.
+alt/base_prot_sig_alt7.nit:74,34--42: Error: `private` is the only legal visibility for properties in a private class.
index ec356da..9f86235 100644 (file)
@@ -78,7 +78,7 @@ Task [
 Object -> Task [dir=back arrowtail=open style=dashed];
 
 A [
- label = "{A|- _vpubA: nullable A\l- _vproA: nullable A\l- _vpriA: nullable A\l- _vpubA2: A\l- _vproA2: A\l- _vpriA2: A\l- _vpriB: nullable B\l- _vpriB2: B\l|+ pubA(a: A)\l# proA(a: A)\l- priA(a: A)\l+ vpubA(): nullable A\l+ vpubA=(vpubA: nullable A)\l# vproA(): nullable A\l# vproA=(vproA: nullable A)\l- vpriA(): nullable A\l- vpriA=(vpriA: nullable A)\l+ vpubA2(): A\l+ vpubA2=(vpubA2: A)\l# vproA2(): A\l# vproA2=(vproA2: A)\l- vpriA2(): A\l- vpriA2=(vpriA2: A)\l- priB(a: B)\l- vpriB(): nullable B\l- vpriB=(vpriB: nullable B)\l- vpriB2(): B\l- vpriB2=(vpriB2: B)\l}"
+ label = "{A|- _vpubA: nullable A\l- _vproA: nullable A\l- _vpriA: nullable A\l- _vpubA2: A\l- _vproA2: A\l- _vpriA2: A\l- _vpriB: nullable B\l- _vpriB2: B\l|+ pubA(a: A)\l# proA(a: A)\l- priA(a: A)\l+ pubA2(): A\l# proA2(): A\l- priA2(): A\l+ vpubA(): nullable A\l+ vpubA=(vpubA: nullable A)\l# vproA(): nullable A\l# vproA=(vproA: nullable A)\l- vpriA(): nullable A\l- vpriA=(vpriA: nullable A)\l+ vpubA2(): A\l+ vpubA2=(vpubA2: A)\l# vproA2(): A\l# vproA2=(vproA2: A)\l- vpriA2(): A\l- vpriA2=(vpriA2: A)\l- priB(a: B)\l- priB2(): B\l- vpriB(): nullable B\l- vpriB=(vpriB: nullable B)\l- vpriB2(): B\l- vpriB2=(vpriB2: B)\l}"
 ]
 Object -> A [dir=back arrowtail=open style=dashed];
 
index a87d928..c846cb7 100644 (file)
@@ -78,7 +78,7 @@ Task [
 Object -> Task [dir=back arrowtail=open style=dashed];
 
 A [
- label = "{A||+ pubA(a: A)\l+ vpubA(): nullable A\l+ vpubA=(vpubA: nullable A)\l+ vpubA2(): A\l+ vpubA2=(vpubA2: A)\l}"
+ label = "{A||+ pubA(a: A)\l+ pubA2(): A\l+ vpubA(): nullable A\l+ vpubA=(vpubA: nullable A)\l+ vpubA2(): A\l+ vpubA2=(vpubA2: A)\l}"
 ]
 Object -> A [dir=back arrowtail=open style=dashed];