The script `nit_env.sh` tries to auto-magically configure PATH, MANPATH and bash completion for users. The point is to be as portable and simple a possible for the final used has he just has to write
~~~
$ source misc/nit_env.sh
~~~
and get a working setup.
Moreover, if `install` in given as argument, then the script register itself to the user `$HOME/.profile`.
~~~
$ source misc/nit_env.sh install
~~~
One advantage is that the script invocation is registered in `.profile`, thus future evolutions of the script will be automatically used in future sessions of the users.
Pull-Request: #1784
Reviewed-by: Alexis Laferrière <alexis.laf@xymus.net>
Reviewed-by: Alexandre Terrasa <alexandre@moz-code.org>
+++ /dev/null
-syntax: glob
-*.bak
-.nit_compile*
-*.orig
-nitc
-nitdoc
-doc/stdlib
-
-c_src/*.o
-c_src/*.cksum
-
-tests/*.res
-tests/*.log
-tests/*.bin
-tests/*.err
-tests/alt
-
-syntax: regexp
-
+This Changelog file is deprecated.
+
+Look at the [newsletter](https://groups.google.com/forum/#!forum/nitlanguage)
+for redacted informations or the commits log for fine-grained details.
+
version 0.6.1-git
* Devel version
-Nit is a statically typed object-oriented programming language.
-The goal of Nit is to propose a statically typed programming language where structure is not a pain.
+Nit is an expressive language with a script-like syntax, a friendly type-system and aims at elegance, simplicity and intuitiveness.
Nit has a simple straightforward style and can usually be picked up quickly, particularly by anyone who has programmed before.
While object-oriented, it allows procedural styles.
* Light and clear syntax.
-Requirement:
+Requirements:
- * gcc http://gcc.gnu.org/
- * pkg-config http://www.freedesktop.org/wiki/Software/pkg-config/
- * ccache http://ccache.samba.org/ to improve recompilation
- * libgc-dev http://www.hpl.hp.com/personal/Hans_Boehm/gc/
- * graphviz http://www.graphviz.org/ to enable graphes with the nitdoc tool
- * libunwind http://nongnu.org/libunwind
+ * gcc http://gcc.gnu.org/ (or a compatible C compiler)
+ * pkg-config http://www.freedesktop.org/wiki/Software/pkg-config/
+ * ccache http://ccache.samba.org/ to improve recompilation
+ * libgc-dev http://www.hpl.hp.com/personal/Hans_Boehm/gc/
+ * graphviz http://www.graphviz.org/ to enable graphs with the nitdoc tool
+ * libunwind http://nongnu.org/libunwind
-Those are available in most linux distributions
+Those are available in most Linux distributions
- # sudo apt-get install build-essential ccache libgc-dev graphviz libunwind pkg-config
+ $ sudo apt-get install build-essential ccache libgc-dev graphviz libunwind-dev pkg-config
-Important files and directory:
+Important files and directories:
- benchmarks/ Script to bench the compilers
- bin/ The Nit tools
- bin/nitc The Nit compiler
- bin/nit The Nit interpreter
- bin/nitdoc The Nit autodoc
- c_src/ C code of nitc (needed to bootstrap)
- clib/ C code needed by nitc to compile programs
- Changelog List of change between versions
- contrib/ Various Nit programs (may or may not be useful)
- doc/ Documentation
- examples/ Program examples written in Nit
- LICENCE License of the software
- misc/ Some additional file for commons text editors and tools
- tests/ Non-regression test-suite
- lib/ Nit standard library
- Makefile Bootstrap the Nit tools
- NOTICE List of the authors
- README This file
- src/ The Nit tool sources (written in Nit)
+ * benchmarks/ Script to bench the compilers
+ * bin/ The Nit tools
+ * c_src/ C code of nitc (needed to bootstrap)
+ * clib/ C code needed by nitc to compile programs
+ * contrib/ Various Nit programs (may or may not be useful)
+ * doc/ Documentation
+ * examples/ Program examples written in Nit
+ * lib/ Nit standard library
+ * LICENCE License of the software
+ * Makefile Bootstrap the Nit tools
+ * misc/ Some additional files for commons text editors and tools
+ * NOTICE.md List of the authors
+ * README This file
+ * share/ Common resources used by tools
+ * src/ The Nit tool sources (written in Nit)
+ * tests/ Non-regression test-suite
How to start:
$ . misc/nit_env.sh install
-More information:
-
- http://www.nitlanguage.org
+More information: <http://www.nitlanguage.org>
# See the License for the specific language governing permissions and
# limitations under the License.
+import opts
+
import benitlux_model
import benitlux_db
import correct
end
end
+var opts = new OptionContext
+var opt_columns = new OptionInt("Number of columns for the graph", 70, "-c")
+opts.add_option(opt_columns)
+
+opts.parse(args)
+var rest = opts.rest
+
# Use the local DB
var db_path = "benitlux_sherbrooke.db"
+if rest.not_empty then db_path = rest.first
var db = new DB.open(db_path)
# All known beers
print "\nAvailability graph:"
# Compute `column_width` days from all the known days
-var column_width = 70
-var days_sample = [for i in column_width.times do all_days[i*all_days.length/column_width]]
+var column_width = opt_columns.value
+var days_sample = [for i in [1..column_width[ do all_days[i*all_days.length/column_width]]
+var weeks_sample = new Array[Array[String]]
# Gather columns headers for each month
var headers = new Array[nullable String]
+var iter = all_days.iterator
+iter.start
var pre = ""
for day in days_sample do
+ # Prepare headers
var new_pre = day.substring(0, 7)
if not day.has_prefix(pre) then
else headers.add null
pre = new_pre
+
+ # Fill weeks
+ var week = new Array[String]
+ weeks_sample.add week
+ while iter.is_ok do
+ var item = iter.item
+ if item == day then break
+ week.add item
+ iter.next
+ end
end
# Draw the headers from top to bottom so they look like:
# Skip never-available beers, usually name errors
if days.is_empty then continue
- # Print a line looking like: " ############ ###### -----########-: Beer"
- for s in days_sample do printn if days.has(s) then "#" else s.date_to_back
- print ": {beer.name}"
+ # Print a line looking like: " ############ ###### -----########- Beer"
+ var last = null
+ #var iter = days.iterator
+ for week in weeks_sample do
+ printn if days.has_all(week) then
+ "#"
+ else if days.has_any(week) then
+ ":"
+ else week.first.date_to_back
+ end
+ print " {beer.name}"
end
db.close
var scores = {};
var answers = [];
var maxscore = 0;
+
+ // Pizza ratios
+ var pizzas = {};
+ var pizzas_person = {};
+ var pizzas_total = 0.0;
+
+ // Iterate over each participant x possible answers
for(i=0; i < anss.length; i++){
var incscore = 0;
var inccount = 0;
if(scores[ansid] > maxscore){
maxscore = scores[ansid];
}
+
+ if (ansid in pizzas_person) {
+
+ // Pizza ratio of previous participant
+ for (a in pizzas_person) {
+ var value = pizzas_person[a];
+ if (value != 0.0 && pizzas_total != 0)
+ value /= pizzas_total;
+
+ if (a in pizzas)
+ pizzas[a] += value;
+ else
+ pizzas[a] = value;
+ }
+
+ // Reset for a new person
+ pizzas_person = {};
+ pizzas_total = 0.0;
+ }
+
+ pizzas_total += incscore;
+ pizzas_person[ansid] = incscore;
}
+
+ // Pizza ratio of the last participant
+ for (a in pizzas_person) {
+ var value = pizzas_person[a];
+ if (value != 0.0 && pizzas_total != 0)
+ value /= pizzas_total;
+
+ if (a in pizzas)
+ pizzas[a] += value;
+ else
+ pizzas[a] = value;
+ }
+
+ var pizza_unit = document.getElementById("pizza_unit").value;
+ if (pizza_unit)
+ pizza_unit = parseFloat(pizza_unit);
+ else
+ pizza_unit = 1;
+
for(i=0; i < answers.length; i++){
var ansid = answers[i].toString();
var el = $('#total'+ansid)[0];
}
ins += "</center>";
el.innerHTML = ins;
+
+ // Pizza ratio
+ var val = pizzas[ansid] * pizza_unit;
+
+ el = $('#pizzas'+ansid)[0];
+ ins = "<center>"+val.toFixed(1);
+ ins += "<br><span style=\\"color:orange\\">∇</span>";
+ ins += "</center>";
+ el.innerHTML = ins;
}
+
+ var pizza_unit = $("#pizza_unit").val();
+ set_cookie("opportunity_pizza_unit", pizza_unit);
}
function change_answer(ele, id){
// modify only the currently selected entry
// Retrieve the last client-side participant's name
window.onload = function () {
- var name_field = document.getElementById("new_name");
- name_field.value = get_cookie("opportunity_participant_name");
+ $("#new_name").val(get_cookie("opportunity_participant_name"));
+ $("#new_name").focus();
+
+ $("#pizza_unit").val(get_cookie("opportunity_pizza_unit"));
+
+ update_scores();
}
"""
end
<tr id="total">
<th>Total ({{{participants(db).length}}})</th>
"""
- for i in answers(db) do
- t.add """<th id="total{{{i.id}}}"><center>{{{i.count(db)}}}"""
- if scores.has_key(i.id) and scores[i.id] >= maxsc then
- t.add """<br/><span style="color:blue">★</span>"""
- end
- t.add "</center></th>"
- end
+ for i in answers(db) do t.add """
+ <th id="total{{{i.id}}}"><center></center></th>
+"""
+ t.add """
+</tr>
+<tr id="pizzas">
+ <th>
+ {{{"%1 ratio × %2".format("<span style='color:orange'>∇</span>", "<input id='pizza_unit' type='number' placeholder='1' text='1' class='inputsm' style='width: 8ex !important;' onchange='update_scores()' onkeypress='update_scores()' onpaste='update_scores()' oninput='update_scores()'>")}}}
+ </th>
+"""
+ for i in answers(db) do t.add """
+ <th id="pizzas{{{i.id}}}"></center></th>
+"""
t.add "</th>"
t.add """
<th></th>
for e in self do if self.count(e) != other.count(e) then return false
return true
end
+
+ # Does the collection contain at least one element of `other`?
+ #
+ # assert [1,3,4,2].has_any([1..10]) == true
+ # assert [1,3,4,2].has_any([5..10]) == false
+ #
+ # Note that the default implementation is general and correct for any lawful Collections.
+ # It is memory-efficient but relies on `has` so may be CPU-inefficient for some kind of collections.
+ fun has_any(other: Collection[nullable Object]): Bool
+ do
+ for o in other do
+ if has(o) then return true
+ end
+ return false
+ end
end
# Iterators generate a series of elements, one at a time.
+++ /dev/null
-digraph g {
-rankdir=BT;node[shape=box];
-subgraph cluster_37053984 {
-label=".."
- m_41649040 [label="kernel"]
-subgraph cluster_37183344 {
-label="../collection"
- m_38874592 [label="array"]
- m_40662960 [label="abstract_collection"]
-}
-}
- m_38874592 -> m_40662960
- m_40662960 -> m_41649040
-}
end
# Tag attributes map
- var attrs: Map[String, String] = new HashMap[String, String]
+ var attrs: Map[String, String] = new HashMap[String, String] is lazy
# Get the attributed value of 'prop' or null if 'prop' is undifened
#
end
# CSS classes
- var classes: Set[String] = new HashSet[String]
+ var classes: Set[String] = new HashSet[String] is lazy
# Add multiple CSS classes
#
css_props[prop] = value
return self
end
- private var css_props: Map[String, String] = new HashMap[String, String]
+ private var css_props: Map[String, String] = new HashMap[String, String] is lazy
# Get CSS value for 'prop'
#
end
# List of children HTML elements
- var children: Set[HTMLTag] = new HashSet[HTMLTag]
+ var children: Set[HTMLTag] = new HashSet[HTMLTag] is lazy
# Clear all child and set the text of element
#
# Text is escaped see: `core::String::html_escape`
fun text(txt: String): HTMLTag do
- children.clear
+ if isset _children then children.clear
append(txt)
return self
end
res.add "<"
res.add tag
render_attrs_in(res)
- if is_void and children.is_empty then
+ if is_void and (not isset _children or children.is_empty) then
res.add "/>"
else
res.add ">"
- for child in children do child.render_in(res)
+ if isset _children then for child in children do child.render_in(res)
res.add "</"
res.add tag
res.add ">"
end
private fun render_attrs_in(res: Sequence[String]) do
+ if not isset _attrs and not isset _classes and not isset _css_props then return
if attrs.has_key("class") or not classes.is_empty then
res.add " class=\""
for cls in classes do
# Read the next useful line from file-name arguments
private fun read_next_line
do
- if stdin.eof then
+ while stdin.eof do
open_next_stream
end
- var line = stdin.read_line
- loop
- if not stdin.eof then break
- open_next_stream
- if not line.is_empty then break
- line = stdin.read_line
- end
- self.line = line
+ self.line = stdin.read_line
end
# Open the next file until there is no more arguments
end
# The next line to process by the main program
- var line: String
+ var line: String is noautoinit
end
--- /dev/null
+#!/bin/bash
+# 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.
+
+# Check that options are documented in the manpages of the tool.
+# Usage: check_manpages from to
+
+set -e
+
+ret=0
+for bin in bin/nit*; do
+
+ name=`basename $bin`
+
+ manc=share/man/nitc.md
+ man=share/man/$name.md
+
+ if ! test -f $man; then
+ echo "No manpage for binary $bin. Add one in $man"
+ echo ""
+ ret=1
+ continue
+ fi
+
+ $bin --help | grep '^ ' | sed 's/ */;/;s/ //' > check_manpages-option_list.out
+ while IFS=';' read opt cmt; do
+ # Generate first lines for the man page from --help
+ printf "%s\n" "$opt" | sed 's/, /`, `/g;s/^/### `/;s/$/`/' > check_manpages-from_help.out
+ echo "$cmt." >> check_manpages-from_help.out
+
+ # Generate grep pattern to search in the existing manpage
+ printf "%s\n" "$opt" | sed 's/, /`\\|`/g;s/^/###.*\\(`/;s/$/`\\)/' > check_manpages-grep_pattern.out
+
+ # Search pattern
+ if ! grep -A 1 -f check_manpages-grep_pattern.out $man > check_manpages-from_man.out; then
+ if ! grep -A 1 -f check_manpages-grep_pattern.out $manc > check_manpages-from_man.out; then
+ # Motif not found :(
+ echo "$opt: missing in the manpage $man. Here what is expected:"
+ echo ""
+ cat check_manpages-from_help.out
+ echo ""
+ ret=1
+ continue
+ fi
+
+ # found in `nitc.md`, check more only if dealing with nitc
+ [ "$man" = "$manc" ] || continue
+ fi
+
+ # Test what is expected
+ if ! diff -q <(sed 's/\s*(.*)//' check_manpages-from_help.out) <(sed 's/\s*(.*)//' check_manpages-from_man.out) > /dev/null; then
+ echo "$opt: mismatch documentation in the manpage $man. Here the word diff:"
+ echo ""
+ wdiff check_manpages-from_help.out check_manpages-from_man.out | colordiff
+ echo ""
+ ret=1
+ continue
+ fi
+ done < check_manpages-option_list.out
+done
+
+exit "$ret"
## DEBUGGER OPTIONS
### `-d`
-Launches the target program with the debugger attached to it
+Launches the target program with the debugger attached to it.
### `-c`
-Launches the target program with the interpreter, such as when the program fails, the debugging prompt is summoned
+Launches the target program with the interpreter, such as when the program fails, the debugging prompt is summoned.
### `--socket`
-Launches the target program with raw output on the network via sockets
+Launches the target program with raw output on the network via sockets.
### `--websocket`
-Launches the target program with output on the network via websockets
+Launches the target program with output on the network via websockets.
### `--port`
-Sets the debug port (Defaults to 22125) - Must be contained between 0 and 65535
+Sets the debug port (Defaults to 22125) - Must be contained between 0 and 65535.
## OTHER OPTIONS
### `--vm`
-Run the virtual machine instead of the naive interpreter (experimental)
+Run the virtual machine instead of the naive interpreter (experimental).
The virtual machine is currently under heavy development and, unless you are developing the vm, there is no reason to use this option yet.
## MESSAGES
### `-W`, `--warn`
-
Show additional warnings (advices).
By default, only important warnings are displayed.
in order to let people fix them before promoting the advice to an important warning.
### `-w`, `--warning`
-
Show/hide a specific warning.
Each type of warning can be individually displayed or hidden.
May be used more than once.
### `-o`, `--output`
-Output executable name.
+Filename of the generated executable.
Indicates the path and name of the produced executable.
Note: it is better to use `--dir` if only the directory is important.
This way, the platform extension will be correctly set.
-### `-o` is not usable if multiple programs are compiled at once.
+`-o` is not usable if multiple programs are compiled at once.
### `--dir`
Output directory.
Note that, to be useful, the compilation directory is not destroyed when `--no-cc` is used.
-### `-m`
+### `-m`, `--mixin`
Additional module to mix-in.
Additional modules are imported and refine the main module of the program.
Allow the separate compiler to direct call monomorphic sites (semi-global).
Need `--rta`.
+### `--direct-call-monomorph0`
+Allow the separate compiler to direct call monomorphic sites (semi-global).
+Need `--rta`.
+
+The difference with the non-zero option is internal:
+with this option, the monomorphism is looked-at on the mmethod level and not at the callsite level.
+
### `--skip-dead-methods`
Do not compile dead methods (semi-global).
Need `--rta`.
It also produces executables that are a little bit smaller since static memory does not have to store the colors.
### `--substitute-monomorph`
-Replace monomorphic trampolines with direct call.
+Replace monomorphic trampolines with direct calls.
Late-binding is implemented with *trampolines*, that are small functions that just select and jump the to right implementations.
If, at link-time, is it known that the target will always by the same implementation then all calls to the trampoline are replaced by
Note: automatically enable option `--trampoline-call`.
+## POTENTIAL OPTIMIZATIONS
+
+These optimisation are not enabled by default as they are counter-effective in most cases.
+
+### `--guard-call`
+Guard VFT calls with a direct call.
+
+### `--type-poset`
+Build a poset of types to create more condensed tables.
+
+The drawback is that more time and memory are used by the compilation process.
+
+
## DANGEROUS OPTIMIZATIONS
The following optimizations disable runtime checks.
### `--trampoline-call`
Use an indirection when calling.
-Just add the trampolines of `--substitute-monomorph` without doing any aditionnal optimizations.
+Just add the trampolines of `--substitute-monomorph` without doing any additionnal optimizations.
+
+### `--no-tag-primitives`
+Use only boxes for primitive types.
## INTERNAL OPTIONS
Do not generate main entry point.
### `--no-stacktrace`
-The compiled program will not display stack traces on runtime errors.
+Disable the generation of stack traces.
+
+With this option, the compiled program will not display stack traces on runtime errors.
Because stack traces rely on libunwind, this option might be useful in order to generate more portable binaries
since libunwind might be non available on the runtime system (or available with an ABI incompatible version).
The tool does not stop after some errors but continue until it produces incorrect result, crashes, erases the hard drive, or just continue forever in an infinite loop.
This option is used to test the robustness of the tools by allowing phases to progress on incorrect data.
+### `--sloppy`
+Force lazy semantic analysis of the source-code.
+
+Analysis of methods is thus done only when required.
+This option breaks the behavior of most of the tools since errors in methods are undetected until the method is required in some processing.
+
# ENVIRONMENT VARIABLES
### `NIT_DIR`
# OPTIONS
### `--host`
-Sets the host to debug from, use IPV4 only. (Defaults to 127.0.0.1).
+Sets the host to debug from, use IPV4 only (Defaults to 127.0.0.1).
### `--port`
Sets the debug port (Defaults to 22125).
-Must be contained between 0 and 65535
+Must be contained between 0 and 65535.
# SEE ALSO
# OPTIONS
### `-d`, `--dir`
-output directory.
+Output directory.
Where the HTML files are generated.
Here, the `git rev-parse HEAD` is used to link to the current snapshot revision of the file.
-### `--no-attribute`
+### `--no-attributes`
Ignore the attributes.
Note: In Nit, attributes are private. Therefore, this option is only useful
when combined with `--private`.
### `--no-dot`
-do not generate graphs with graphviz.
+Do not generate graphs with graphviz.
### `--private`
-also generate private API.
+Also generate private API.
## CUSTOMIZATION
### `--sharedir`
-directory containing nitdoc assets.
+Directory containing nitdoc assets.
By default `$NIT_DIR/share/nitdoc/` is used.
### `--shareurl`
-use shareurl instead of copy shared files.
+Use shareurl instead of copy shared files.
By default, assets from the sharedir a copied into the output directory and referred with a relative path in the generated files.
With this option, the assets are not copied and the given URL of path is used in the generated files to locate assets.
### `--custom-title`
-custom title for homepage.
+Custom title for homepage.
### `--custom-footer-text`
-custom footer text.
+Custom footer text.
### `--custom-overview-text`
-custom intro text for homepage
+Custom intro text for homepage.
### `--custom-brand`
-custom link to external site
+Custom link to external site.
## SERVICES
### `--github-upstream`
-Git branch where edited commits will be pulled into (ex: user:repo:branch)
+Git branch where edited commits will be pulled into (ex: user:repo:branch).
### `--github-base-sha1`
-Git sha1 of base commit used to create pull request
+Git sha1 of base commit used to create pull request.
### `--github-gitdir`
-Git working directory used to resolve path name (ex: /home/me/myproject/)
+Git working directory used to resolve path name (ex: /home/me/myproject/).
### `--piwik-tracker`
-Piwik tracker URL (ex: `"nitlanguage.org/piwik/"`)
+Piwik tracker URL (ex: `nitlanguage.org/piwik/`).
### `--piwik-site-id`
-Piwik site ID
+Piwik site ID.
## TESTING
### `--test`
-Only print the pages structure. Nothing is generated.
+Print test data (metrics and structure).
+
+### `--no-render`
+Do not render HTML files.
# SEE ALSO
The generated HTML will only contains lines bellow the specified one.
### `--last-line`
-End the source file at this line (default: to the end)
+End the source file at this line (default: to the end).
The generated HTML will only contains lines above the specified one.
All `.nit` files found in the specified directory and subdirectories are considered.
### `-d`, `--depends`
-List dependencies of given modules
+List dependencies of given modules.
All imported modules are also considered.
## PRESENTATION OPTIONS
-### `-p`, `--path`
+### `-p`, `--path-only`
List only path (instead of name + path).
Paths are displayed uncolored.
## METRICS
### `--all`
-Compute all metrics
+Compute all metrics.
### `--mmodules`
-Compute metrics about mmodules
+Compute metrics about mmodules.
### `--mclasses`
-Compute metrics about mclasses
+Compute metrics about mclasses.
### `--mendel`
-Compute mendel metrics
+Compute mendel metrics.
### `--inheritance`
-Compute metrics about inheritance usage
+Compute metrics about inheritance usage.
### `--refinement`
-Compute metrics about refinement usage
+Compute metrics about refinement usage.
### `--self`
-Compute metrics about the usage of explicit and implicit self
+Compute metrics about the usage of explicit and implicit self.
### `--ast`
-Compute metrics about the usage of nodes and identifiers in the AST
+Compute metrics about the usage of nodes and identifiers in the AST.
### `--nullables`
-Compute metrics on nullables send
+Compute metrics on nullables send.
### `--static-types`
-Compute explicit static types metrics
+Compute explicit static types metrics.
### `--tables`
-Compute tables metrics
+Compute tables metrics.
### `--rta`
-Compute RTA metrics
+Compute RTA metrics.
### `--generate_hyperdoc`
-Generate Hyperdoc
+Generate Hyperdoc.
### `--poset`
-Complete metrics on posets
+Complete metrics on posets.
### `--detect-variance-constraints`
-Detects the definition-site variance constraints on formal parameters.
+Detect the definition-site variance constraints on formal parameters.
Infers the possible variance annotations of formal types in Nit programs by identifying the existing constraints on the usage of those formal type.
+### `--detect-covariance`
+Detect the static covariance usages.
+
## OUTPUT
### `--csv`
# OPTIONS
-Only common options of the Nit tools are understood.
+### `--vim-autocomplete`
+Generate metadata files used by the Vim plugin for autocompletion.
+
+This option is not expected to be called directly by users.
# SEE ALSO
# OPTIONS
### `--dir`
-Working directory (default is '.nitpretty')
+Working directory (default is '.nitpretty').
### `-o`, `--output`
-Output name (default is pretty.nit)
+Output name (default is pretty.nit).
### `--diff`
-Show diff between source and output
+Show diff between source and output.
### `--meld`
-Show diff between source and output using meld
+Show diff between source and output using meld.
### `--check`
-Check format of Nit source files
+Check format of Nit source files.
This option creates a temporary pretty printed file then checks if the output
of the diff command on the source file and the pretty printed one is empty.
### `--break-strings`
-Break too long string literals
+Break too long string literals.
### `--inline-do`
-Force do keyword on the same line as the method signature
+Force do keyword on the same line as the method signature.
### `--skip-empty`
-Force formatting of empty lines
+Force formatting of empty lines.
By default empty lines are kept as they were typed in the file.
When enabling this option, `nitpretty` will decide where to break lines and
will put empty lines to separate properties and code blocks.
+### `--line-width`
+Maximum length of lines (use 0 to disable automatic line breaks).
+
+### `--no-inline`
+Disable automatic one-liners.
+
# SPECIFICATION
The specification of the pretty printing is described here.
# OPTIONS
### `-o`, `--output`
-Output file (can also be 'stdout')
+Output file (can also be 'stdout').
### `--dir`
-Output directory
+Output directory.
+
+### `-d`, `--depth`
+Depth of the visit and generation <module, group, package>.
# SEE ALSO
With the `--full` option, all imported modules (even those in standard) are also precessed.
### `-o`, `--output`
-Output name (default is 'nitunit.xml')
+Output name (default is 'nitunit.xml').
### `nitunit` produces a XML file comatible with JUnit.
### `--dir`
-Working directory (default is '.nitunit')
+Working directory (default is '.nitunit').
In order to execute the tests, nit files are generated then compiled and executed in the giver working directory.
Does not compile and run tests.
### `-p`, `--pattern`
-Only run test case with name that match pattern. Examples: `TestFoo`, `TestFoo*`, `TestFoo::test_foo`, `TestFoo::test_foo*`, `test_foo`, `test_foo*`
+Only run test case with name that match pattern.
+
+Examples: `TestFoo`, `TestFoo*`, `TestFoo::test_foo`, `TestFoo::test_foo*`, `test_foo`, `test_foo*`
### `-t`, `--target-file`
Specify test suite location.
## SUITE GENERATION
### `--gen-suite`
-Generate test suite skeleton for a module
+Generate test suite skeleton for a module.
### `-f`, `--force`
Force test generation even if file exists.
# OPTIONS
-### `-q`
-execute a query, display results in console then quit.
+### `-c`, `--command`
+Nitx command to perform.
+
+Execute a command, display results in the console, then quit.
+
+### `--no-attributes`
+Ignore the attributes.
+
+### `--private`
+Also generate private API.
# SEE ALSO
# Add compiling options
redef class ToolContext
# --output
- var opt_output = new OptionString("Output file", "-o", "--output")
+ var opt_output = new OptionString("Filename of the generated executable", "-o", "--output")
# --dir
var opt_dir = new OptionString("Output directory", "--dir")
# --no-cc
- var opt_no_cc = new OptionBool("Do not invoke C compiler", "--no-cc")
+ var opt_no_cc = new OptionBool("Do not invoke the C compiler", "--no-cc")
# --no-main
var opt_no_main = new OptionBool("Do not generate main entry point", "--no-main")
# --make-flags
- var opt_make_flags = new OptionString("Additional options to make", "--make-flags")
+ var opt_make_flags = new OptionString("Additional options to the `make` command", "--make-flags")
# --max-c-lines
var opt_max_c_lines = new OptionInt("Maximum number of lines in generated C files. Use 0 for unlimited", 10000, "--max-c-lines")
# --group-c-files
# --no-check-attr-isset
var opt_no_check_attr_isset = new OptionBool("Disable isset tests before each attribute access (dangerous)", "--no-check-attr-isset")
# --no-check-assert
- var opt_no_check_assert = new OptionBool("Disable the evaluation of explicit 'assert' and 'as' (dangerous)", "--no-check-assert")
+ var opt_no_check_assert = new OptionBool("Disable the evaluation of explicit `assert` and `as` (dangerous)", "--no-check-assert")
# --no-check-autocast
var opt_no_check_autocast = new OptionBool("Disable implicit casts on unsafe expression usage (dangerous)", "--no-check-autocast")
# --no-check-null
# --no-stacktrace
var opt_no_stacktrace = new OptionBool("Disable the generation of stack traces", "--no-stacktrace")
# --no-gcc-directives
- var opt_no_gcc_directive = new OptionArray("Disable a advanced gcc directives for optimization", "--no-gcc-directive")
+ var opt_no_gcc_directive = new OptionArray("Disable advanced gcc directives for optimization", "--no-gcc-directive")
# --release
var opt_release = new OptionBool("Compile in release mode and finalize application", "--release")
# -g
- var opt_debug = new OptionBool("Compile in debug mode (no C-side optimization)", "--debug", "-g")
+ var opt_debug = new OptionBool("Compile in debug mode (no C-side optimization)", "-g", "--debug")
redef init
do
do
if v.compiler.modelbuilder.toolcontext.opt_no_check_covariance.value then return
+ var msignature = self.msignature.as(not null)
+
for i in [0..msignature.arity[ do
# skip test for vararg since the array is instantiated with the correct polymorphic type
if msignature.vararg_rank == i then continue
if not origmtype.need_anchor then continue
# get the parameter type
- var mtype = self.msignature.mparameters[i].mtype
+ var mtype = msignature.mparameters[i].mtype
# generate the cast
# note that v decides if and how to implements the cast
- v.add("/* Covariant cast for argument {i} ({self.msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
+ v.add("/* Covariant cast for argument {i} ({msignature.mparameters[i].name}) {arguments[i+1].inspect} isa {mtype} */")
v.add_cast(arguments[i+1], mtype, "covariance")
end
end
redef class ASuperExpr
redef fun expr(v)
do
- var recv = v.frame.arguments.first
+ var frame = v.frame.as(not null)
+ var recv = frame.arguments.first
var callsite = self.callsite
if callsite != null then
# Add automatic arguments for the super init call
args = [recv]
for i in [0..callsite.msignature.arity[ do
- args.add(v.frame.arguments[i+1])
+ args.add(frame.arguments[i+1])
end
else
args = v.varargize(callsite.mpropdef, callsite.signaturemap, recv, self.n_args.n_exprs)
var args
if self.n_args.n_exprs.is_empty then
- args = v.frame.arguments
+ args = frame.arguments
else
args = v.varargize(mpropdef, signaturemap, recv, self.n_args.n_exprs)
end
var res = v.new_var(mtype)
res.is_exact = true
if is_native_array then
- var mtype_elt = mtype.arguments.first
v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof(val*));")
v.add("((struct {mtype.c_name}*){res})->length = length;")
else
# --no-inline-intern
var opt_no_inline_intern = new OptionBool("Do not inline call to intern methods", "--no-inline-intern")
# --no-union-attribute
- var opt_no_union_attribute = new OptionBool("Put primitive attibutes in a box instead of an union", "--no-union-attribute")
+ var opt_no_union_attribute = new OptionBool("Put primitive attributes in a box instead of an union", "--no-union-attribute")
# --no-shortcut-equate
var opt_no_shortcut_equate = new OptionBool("Always call == in a polymorphic way", "--no-shortcut-equal")
# --no-tag-primitives
var opt_no_tag_primitives = new OptionBool("Use only boxes for primitive types", "--no-tag-primitives")
# --colors-are-symbols
- var opt_colors_are_symbols = new OptionBool("Store colors as symbols (link-boost)", "--colors-are-symbols")
+ var opt_colors_are_symbols = new OptionBool("Store colors as symbols instead of static data (link-boost)", "--colors-are-symbols")
# --trampoline-call
var opt_trampoline_call = new OptionBool("Use an indirection when calling", "--trampoline-call")
# --guard-call
var opt_guard_call = new OptionBool("Guard VFT calls with a direct call", "--guard-call")
# --substitute-monomorph
- var opt_substitute_monomorph = new OptionBool("Replace monomorph trampoline with direct call (link-boost)", "--substitute-monomorph")
+ var opt_substitute_monomorph = new OptionBool("Replace monomorphic trampolines with direct calls (link-boost)", "--substitute-monomorph")
# --link-boost
var opt_link_boost = new OptionBool("Enable all link-boost optimizations", "--link-boost")
# --inline-some-methods
var opt_inline_some_methods = new OptionBool("Allow the separate compiler to inline some methods (semi-global)", "--inline-some-methods")
# --direct-call-monomorph
- var opt_direct_call_monomorph = new OptionBool("Allow the separate compiler to direct call monomorph sites (semi-global)", "--direct-call-monomorph")
+ var opt_direct_call_monomorph = new OptionBool("Allow the separate compiler to direct call monomorphic sites (semi-global)", "--direct-call-monomorph")
# --direct-call-monomorph0
- var opt_direct_call_monomorph0 = new OptionBool("Allow the separate compiler to direct call monomorph sites (semi-global)", "--direct-call-monomorph0")
+ var opt_direct_call_monomorph0 = new OptionBool("Allow the separate compiler to direct call monomorphic sites (semi-global)", "--direct-call-monomorph0")
# --skip-dead-methods
var opt_skip_dead_methods = new OptionBool("Do not compile dead methods (semi-global)", "--skip-dead-methods")
# --semi-global
# --tables-metrics
var opt_tables_metrics = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
# --type-poset
- var opt_type_poset = new OptionBool("Build a poset of types to create more condensed tables.", "--type-poset")
+ var opt_type_poset = new OptionBool("Build a poset of types to create more condensed tables", "--type-poset")
redef init
do
redef class ToolContext
# Directory where the Nitdoc is rendered.
- var opt_dir = new OptionString("output directory", "-d", "--dir")
+ var opt_dir = new OptionString("Output directory", "-d", "--dir")
# Shortcut for `opt_dir.value` with default "doc".
var output_dir: String is lazy do return opt_dir.value or else "doc"
redef class ToolContext
# Do not generate documentation for attributes.
- var opt_no_attributes = new OptionBool("ignore the attributes", "--no-attributes")
+ var opt_no_attributes = new OptionBool("Ignore the attributes", "--no-attributes")
# Do not generate documentation for private properties.
- var opt_private = new OptionBool("also generate private API", "--private")
+ var opt_private = new OptionBool("Also generate private API", "--private")
redef init do
super
redef class ToolContext
# Do not generate `graphviz` diagrams.
- var opt_nodot = new OptionBool("do not generate graphes with graphviz", "--no-dot")
+ var opt_nodot = new OptionBool("Do not generate graphs with graphviz", "--no-dot")
redef init do
super
redef class ToolContext
# File pattern used to link documentation to source code.
- var opt_source = new OptionString("link for source (%f for filename, " +
+ var opt_source = new OptionString("Format to link source code (%f for filename, " +
"%l for first line, %L for last line)", "--source")
# Directory where the CSS and JS is stored.
- var opt_sharedir = new OptionString("directory containing nitdoc assets", "--sharedir")
+ var opt_sharedir = new OptionString("Directory containing nitdoc assets", "--sharedir")
# Use a shareurl instead of copy shared files.
#
# This is usefull if you don't want to store the Nitdoc templates with your
# documentation.
- var opt_shareurl = new OptionString("use shareurl instead of copy shared files", "--shareurl")
+ var opt_shareurl = new OptionString("Use shareurl instead of copy shared files", "--shareurl")
# Use a custom title for the homepage.
- var opt_custom_title = new OptionString("custom title for homepage", "--custom-title")
+ var opt_custom_title = new OptionString("Custom title for homepage", "--custom-title")
# Display a custom brand or logo in the documentation top menu.
- var opt_custom_brand = new OptionString("custom link to external site", "--custom-brand")
+ var opt_custom_brand = new OptionString("Custom link to external site", "--custom-brand")
# Display a custom introduction text before the packages overview.
- var opt_custom_intro = new OptionString("custom intro text for homepage", "--custom-overview-text")
+ var opt_custom_intro = new OptionString("Custom intro text for homepage", "--custom-overview-text")
# Display a custom footer on each documentation page.
#
# Generally used to display the documentation or product version.
- var opt_custom_footer = new OptionString("custom footer text", "--custom-footer-text")
+ var opt_custom_footer = new OptionString("Custom footer text", "--custom-footer-text")
# Piwik tracker URL.
#
# If you want to monitor your visitors.
- var opt_piwik_tracker = new OptionString("Piwik tracker URL (ex: nitlanguage.org/piwik/)", "--piwik-tracker")
+ var opt_piwik_tracker = new OptionString("Piwik tracker URL (ex: `nitlanguage.org/piwik/`)", "--piwik-tracker")
# Piwik tracker site id.
var opt_piwik_site_id = new OptionString("Piwik site ID", "--piwik-site-id")
var opt_github_gitdir = new OptionString("Git working directory used to resolve path name (ex: /home/me/mypackage/)", "--github-gitdir")
# Do not produce HTML files
- var opt_no_render = new OptionBool("do not render HTML files", "--no-render")
+ var opt_no_render = new OptionBool("Do not render HTML files", "--no-render")
redef init do
super
redef class ToolContext
# File pattern used to link documentation to source code.
- var opt_test = new OptionBool("print test data", "--test")
+ var opt_test = new OptionBool("Print test data (metrics and structure)", "--test")
redef init do
super
do
super
option_context.add_option opt_vim_autocomplete
+ opt_vim_autocomplete.hidden = true
end
end
redef class ToolContext
# --discover-call-trace
- var opt_discover_call_trace = new OptionBool("Trace calls of the first invocation of a method", "--discover-call-trace")
+ var opt_discover_call_trace = new OptionBool("Trace calls of the first invocation of methods", "--discover-call-trace")
redef init
do
n.debug("inconsitance: no value and not escaping.")
end
var implicit_cast_to = n.implicit_cast_to
- if implicit_cast_to != null then
+ if i != null and implicit_cast_to != null then
var mtype = self.unanchor_type(implicit_cast_to)
if not self.is_subtype(i.mtype, mtype) then n.fatal(self, "Cast failed. Expected `{implicit_cast_to}`, got `{i.mtype}`")
end
# Execute type checks of covariant parameters
fun parameter_check(node: ANode, mpropdef: MMethodDef, args: Array[Instance])
do
- var msignature = mpropdef.msignature
+ var msignature = mpropdef.msignature.as(not null)
for i in [0..msignature.arity[ do
# skip test for vararg since the array is instantiated with the correct polymorphic type
if msignature.vararg_rank == i then continue
# Use this method, instead of `send` to execute and control the additional behavior of the call-sites
fun callsite(callsite: nullable CallSite, arguments: Array[Instance]): nullable Instance
do
+ if callsite == null then return null
var initializers = callsite.mpropdef.initializers
if not initializers.is_empty then
var recv = arguments.first
redef class ToolContext
# Option --path
- var opt_path = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
+ var opt_path = new OptionArray("Add an additional include path (may be used more than once)", "-I", "--path")
# Option --only-metamodel
var opt_only_metamodel = new OptionBool("Stop after meta-model processing", "--only-metamodel")
# Option --only-parse
- var opt_only_parse = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
+ var opt_only_parse = new OptionBool("Only proceed to parse files", "--only-parse")
redef init
do
end
end
- var candidate = search_module_in_paths(anode.hot_location, name, lookpaths)
+ var loc = null
+ if anode != null then loc = anode.hot_location
+ var candidate = search_module_in_paths(loc, name, lookpaths)
if candidate == null then
if mgroup != null then
var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
nmodule.mmodule = mmodule
nmodules.add(nmodule)
+ parsed_modules.add mmodule
self.mmodule2nmodule[mmodule] = nmodule
if parent!= null then
# --rta
var opt_rta = new OptionBool("Compute RTA metrics", "--rta")
# --generate-csv
- var opt_csv = new OptionBool("Export metrics in CSV format", "--csv")
+ var opt_csv = new OptionBool("Also export metrics in CSV format", "--csv")
# --generate_hyperdoc
var opt_generate_hyperdoc = new OptionBool("Generate Hyperdoc", "--generate_hyperdoc")
# --poset
redef class ToolContext
# --mixin
- var opt_mixins = new OptionArray("Additionals module to min-in", "-m", "--mixin")
+ var opt_mixins = new OptionArray("Additional module to mix-in", "-m", "--mixin")
# --define
var opt_defines = new OptionArray("Define a specific property", "-D", "--define")
redef fun mdoc_or_fallback
do
if mdoc != null then return mdoc
+ var default_mmodule = self.default_mmodule
if default_mmodule == null then return null
return default_mmodule.mdoc_or_fallback
end
do
model.mmodules_by_name.add_one(name, self)
model.mmodules.add(self)
+ var mgroup = self.mgroup
if mgroup != null then
mgroup.mmodules.add(self)
if mgroup.name == name then
end
end
- # Is `self` created for internal purpose?
- # Fictive modules are instantiated internally but they should not be
- # exposed to the final user.
- var is_fictive: Bool = false is writable
-
# Is `self` a unit test module used by `nitunit`?
var is_test_suite: Bool = false is writable
end
print("Fatal Error: no primitive class {name} in {self}")
exit(1)
+ abort
end
if cla.length != 1 then
var msg = "Fatal Error: more than one primitive class {name} in {self}:"
end
if resolved_receiver isa MNullableType then resolved_receiver = resolved_receiver.mtype
if resolved_receiver isa MParameterType then
+ assert anchor != null
assert resolved_receiver.mclass == anchor.mclass
resolved_receiver = anchor.arguments[resolved_receiver.rank]
if resolved_receiver isa MNullableType then resolved_receiver = resolved_receiver.mtype
# The container class of a Nit object-oriented model.
# A model knows modules, classes and properties and can retrieve them.
class Model
+ super MEntity
end
# A named and possibly documented entity in the model.
# Note that the broken status is not propagated to enclosing and enclosed entities.
# e.g. a broken method does not make the whole module broken.
var is_broken = false is writable
+
+ # Is `self` created for internal purpose?
+ #
+ # Fictive entities are used internally but they should not be
+ # exposed to the final user.
+ var is_fictive: Bool = false is writable
end
# Something that represents a concern
--- /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.
+
+# Simple visitor framework for Nit models.
+#
+# This module provides the `ModelVisitor` abstract class and
+# refines the classes of the `MEntity` hierarchy to add visiting related methods.
+#
+# A standard approach on complex visitor is to dispatch the `ModelVisitor::visit` on the
+# entities to do specific things.
+#
+# ~~~nitish
+# class FooVisitor
+# super ModelVisitor
+# redef fun visit(e) do e.foo_visit(self)
+# end
+#
+# redef class MEntity
+# do
+# fun foo_vist(v: FooVisitor) do visit_all(v)
+# end
+#
+# redef class MClass
+# do
+# redef fun foo_visit(v) do
+# print self
+# super
+# end
+# end
+# ~~~
+module model_visitor
+
+import model
+
+# The abstract model visitor template.
+#
+# Specific visitor must implement the `visit` method to perform the work.
+abstract class ModelVisitor
+ # Visit the entity `e`.
+ #
+ # This method setups `current_entity` and call `visit`.
+ # If `e` is null, nothing is done.
+ fun enter_visit(e: nullable MEntity) do
+ if e == null then return
+ if e.is_fictive and not include_fictive then return
+ var old_entity = current_entity
+ current_entity = e
+ visit(e)
+ current_entity = old_entity
+ end
+
+ # The current visited entity
+ var current_entity: nullable MEntity = null
+
+ # Method to define in specific visitor.
+ #
+ # It should not be called directly but used by `enter_visit`
+ protected fun visit(e: MEntity) is abstract
+
+ # Filter classes and method on the visibility.
+ #
+ # If set, only the classes and method with at least the given
+ # visibility level will be visited.
+ var min_visibility: nullable MVisibility = null is writable
+
+ # Is `visibility` acceptable with regard to `min_visibility`?
+ private fun accept_visitibily(visibility: MVisibility): Bool
+ do
+ var min = min_visibility
+ return min == null or min <= visibility
+ end
+
+ # Include fictive entities?
+ #
+ # By default, fictive entities (see `MEntity::is_fictive`) are not visited.
+ var include_fictive = false is writable
+end
+
+redef class MEntity
+ # Call `v.enter_visit` on all nested entities.
+ #
+ # See the specific implementation in the subclasses.
+ fun visit_all(v: ModelVisitor) do end
+end
+
+redef class Model
+ # Visit all the packages of the model.
+ redef fun visit_all(v) do
+ for x in mpackages do v.enter_visit(x)
+ end
+end
+
+redef class MPackage
+ # Visit the root group of the package.
+ redef fun visit_all(v) do
+ v.enter_visit(root)
+ end
+end
+
+redef class MGroup
+ # Visit all the subgroups and modules of the group.
+ redef fun visit_all(v) do
+ for x in in_nesting.direct_smallers do v.enter_visit(x)
+ for x in mmodules do v.enter_visit(x)
+ end
+end
+
+redef class MModule
+ # Visit all the classes and class definitions of the module.
+ #
+ # On class introduction, the `MClass` then the `MClassDef` are visited.
+ # On class refinement, only the `MClassDef` is visited (the `MClass` is visited in an imported module).
+ # On class importation, nothing is visited (the `MClass` and the `MClassDef` are visited in imported modules).
+ redef fun visit_all(v) do
+ for x in mclassdefs do
+ if not v.accept_visitibily(x.mclass.visibility) then return
+ if x.is_intro then v.enter_visit(x.mclass)
+ v.enter_visit(x)
+ end
+ end
+end
+
+redef class MClassDef
+ # Visit all the classes and class definitions of the module.
+ #
+ # On property introduction, the `MProperty` then the `MPropDef` are visited.
+ # On property redefinition, only the `MPropDef` is visited (the `MProperty` is visited in an inherited class).
+ # On property inheritance, nothing is visited (the `MProperty` and the `MPropDef` are visited in inherited classes).
+ redef fun visit_all(v) do
+ for x in mpropdefs do
+ if not v.accept_visitibily(x.mproperty.visibility) then return
+ if x.is_intro then v.enter_visit(x.mproperty)
+ v.enter_visit(x)
+ end
+ end
+end
redef fun display(a) do
if a isa MGroup then
- if a.parent == null then return "{a.mpackage.name} ({a.filepath.to_s})"
+ if a.parent == null then return "{a.mpackage.name} ({a.filepath or else "?"})"
return a.name + " (group)"
else if a isa MModule then
return a.name
var subs = tree.sub[o]
var minres = mini(subs.first)
var maxres = maxi(subs.first)
- var order = minres.model.mmodule_importation_hierarchy
+ var order = o.model.mmodule_importation_hierarchy
for o2 in subs do
var c = mini(o2)
if c == null then continue
if mgroup.parent == null then
# is is a root group, so display the package
if package_group then
- o.write("subgraph cluster_{mgroup.object_id} \{\nlabel=\"{mgroup.mpackage.name}\\n({mgroup.filepath.to_s})\"\ncolor=black\nstyle=dotted\n")
+ o.write("subgraph cluster_{mgroup.object_id} \{\nlabel=\"{mgroup.mpackage.name}\\n({mgroup.filepath or else "?"})\"\ncolor=black\nstyle=dotted\n")
end
else
if cluster_group then
redef class ToolContext
# Option --ignore-visibility
- var opt_ignore_visibility = new OptionBool("Do not check, and produce errors, on visibility issues.", "--ignore-visibility")
+ var opt_ignore_visibility = new OptionBool("Do not check, and produce errors, on visibility issues", "--ignore-visibility")
redef init
do
for npropdef in nclassdef.n_propdefs do
if npropdef isa AMethPropdef then
if not npropdef.is_autoinit then continue # Skip non tagged autoinit
- if npropdef.mpropdef == null then return # Skip broken method
- var sig = npropdef.mpropdef.msignature
+ var mpropdef = npropdef.mpropdef
+ if mpropdef == null then return # Skip broken method
+ var sig = mpropdef.msignature
if sig == null then continue # Skip broken method
for param in sig.mparameters do
var mparameter = new MParameter(param.name, ret_type, false)
mparameters.add(mparameter)
end
- initializers.add(npropdef.mpropdef.mproperty)
- npropdef.mpropdef.mproperty.is_autoinit = true
+ initializers.add(mpropdef.mproperty)
+ mpropdef.mproperty.is_autoinit = true
end
if npropdef isa AAttrPropdef then
var mreadpropdef = npropdef.mreadpropdef
- if mreadpropdef == null or mreadpropdef.msignature == null then return # Skip broken attribute
+ if mreadpropdef == null then return # Skip broken attribute
+ var msignature = mreadpropdef.msignature
+ if msignature == null then return # Skip broken attribute
if npropdef.noinit then continue # Skip noinit attribute
var atlateinit = npropdef.get_single_annotation("lateinit", self)
if atlateinit != null then
end
if npropdef.has_value then continue
var paramname = mreadpropdef.mproperty.name
- var ret_type = mreadpropdef.msignature.return_mtype
+ var ret_type = msignature.return_mtype
if ret_type == null then return
var mparameter = new MParameter(paramname, ret_type, false)
mparameters.add(mparameter)
end
end
+ var the_root_init_mmethod = self.the_root_init_mmethod
if the_root_init_mmethod == null then return
# Look for most-specific new-stype init definitions
end
# Else create the local implicit basic init definition
- var mprop = the_root_init_mmethod.as(not null)
+ var mprop = the_root_init_mmethod
var mpropdef = new MMethodDef(mclassdef, mprop, nclassdef.location)
mpropdef.has_supercall = true
mpropdef.initializers.add_all(initializers)
var precursor_ret_type = msignature.return_mtype
var ret_type = mysignature.return_mtype
if ret_type != null and precursor_ret_type == null then
- modelbuilder.error(nsig.n_type.as(not null), "Redef Error: `{mpropdef.mproperty}` is a procedure, not a function.")
+ modelbuilder.error(nsig.n_type, "Redef Error: `{mpropdef.mproperty}` is a procedure, not a function.")
mpropdef.msignature = null
mpropdef.is_broken = true
return
# For parameters, type is always useless in a redef.
# For return type, type is useless if not covariant with introduction.
redef fun check_repeated_types(modelbuilder) do
+ var mpropdef = self.mpropdef
+ if mpropdef == null then return
if mpropdef.is_intro or n_signature == null then return
# check params
for param in n_signature.n_params do
end
is_lazy = true
var mlazyprop = new MAttribute(mclassdef, "lazy _" + name, none_visibility)
+ mlazyprop.is_fictive = true
var mlazypropdef = new MAttributeDef(mclassdef, mlazyprop, self.location)
+ mlazypropdef.is_fictive = true
self.mlazypropdef = mlazypropdef
end
# Type is useless if the attribute type is the same thant the intro.
redef fun check_repeated_types(modelbuilder) do
+ var mreadpropdef = self.mreadpropdef
+ if mreadpropdef == null then return
if mreadpropdef.is_intro or n_type == null then return
# get intro
var intro = mreadpropdef.mproperty.intro
var toolcontext = new ToolContext
toolcontext.option_context.options_before_rest = true
toolcontext.tooldescription = "Usage: nit [OPTION]... <file.nit>...\nInterprets and debugs Nit programs."
-# Add an option "-o" to enable compatibilit with the tests.sh script
-var opt = new OptionString("compatibility (does noting)", "-o")
+# Add an option "-o" to enable compatibility with the tests.sh script
+var opt = new OptionString("Does nothing. Used for compatibility.", "-o")
+opt.hidden = true
toolcontext.option_context.add_option(opt)
var opt_eval = new OptionBool("Specifies the program from command-line", "-e")
var opt_loop = new OptionBool("Repeatedly run the program for each line in file-name arguments", "-n")
redef class ToolContext
var opt_host_address: OptionString = new OptionString("Sets the host to debug from, use IPV4 only (Defaults to 127.0.0.1)", "--host")
- var opt_debug_port: OptionInt = new OptionInt("Sets the debug port (Defaults to 22125) - Must be contained between 0 and 65535", 22125, "--port")
+ var opt_debug_port: OptionInt = new OptionInt("Sets the debug port (Defaults to 22125)", 22125, "--port")
redef init
do
toolcontext.keep_going = true
var opt_fragment = new OptionBool("Omit document header and footer", "-f", "--fragment")
-var opt_line_id_prefix = new OptionString("Prefix of the id of each line <span> element", "--line-id-prefix")
+var opt_line_id_prefix = new OptionString("Prefix of the id of each line `<span>` element", "--line-id-prefix")
var opt_first_line = new OptionInt("Start the source file at this line (default: 1)", 0, "--first-line")
var opt_last_line = new OptionInt("End the source file at this line (default: to the end)", 0, "--last-line")
var opt_dir = new OptionString("Output html files in a specific directory (required if more than one module)", "-d", "--dir")
var tc = new ToolContext
var opt_keep = new OptionBool("Ignore errors and files that are not a Nit source file", "-k", "--keep")
-var opt_recursive = new OptionBool("Process directories recussively", "-r", "--recursive")
+var opt_recursive = new OptionBool("Process directories recursively", "-r", "--recursive")
var opt_tree = new OptionBool("List source files in their groups and packages", "-t", "--tree")
-var opt_source = new OptionBool("List source files", "-s", "--source")
-var opt_package = new OptionBool("List packages paths (default)", "-P", "--package")
+var opt_source = new OptionBool("List source files in a flat list", "-s", "--source")
+var opt_package = new OptionBool("List packages in a flat list (default)", "-P", "--package")
var opt_depends = new OptionBool("List dependencies of given modules", "-d", "--depends")
-var opt_make = new OptionBool("List dependencies suitable for a rule in a Makefile. Alias for -d, -p and -s", "-M")
-var opt_paths = new OptionBool("List only path (instead of name + path)", "-p", "--path")
+var opt_make = new OptionBool("List dependencies suitable for a rule in a Makefile (alias for -d, -p and -s)", "-M")
+var opt_paths = new OptionBool("List only path (instead of name + path)", "-p", "--path-only")
tc.option_context.add_option(opt_keep, opt_recursive, opt_tree, opt_source, opt_package, opt_depends, opt_paths, opt_make)
tc.tooldescription = "Usage: nitls [OPTION]... <file.nit|directory>...\nLists the packages and/or paths of Nit sources files."
var docx: Phase = new NitxPhase(self, null)
# Used to shortcut the prompt and display directly the result in console.
- var opt_query = new OptionString("Nitx query to perform", "-q", "--query")
+ var opt_command = new OptionString("Nitx command to perform", "-c", "--command")
- init do option_context.add_option opt_query
+ init do option_context.add_option opt_command
end
# Nitx phase explores the model and prepares the console rendering.
# start nitx
var nitx = new Nitx(toolcontext, doc)
- var q = toolcontext.opt_query.value
+ var q = toolcontext.opt_command.value
if q != null then # shortcut prompt
print ""
nitx.do_query(q)
var phases = new POSet[Phase]
# --disable-phase
- var opt_disable_phase = new OptionArray("DEBUG: Disable a specific phase; use `list` to get the list.", "--disable-phase")
+ var opt_disable_phase = new OptionArray("Disable a specific phase; use `list` to get the list (debug)", "--disable-phase")
- # --disable-phase
- var opt_sloppy = new OptionBool("DEBUG: force lazy semantic analysis of the source-code", "--sloppy")
+ # --sloppy
+ var opt_sloppy = new OptionBool("Force lazy semantic analysis of the source-code (debug)", "--sloppy")
redef init
do
--- /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.
+
+# Example of model_visitor
+module test_model_visitor
+
+import test_phase
+import frontend
+import model_visitor
+import counter
+
+# Example visitor that just count kind of entities.
+class TestModelVisitor
+ super ModelVisitor
+
+ redef fun visit(e) do
+ if not doc_only or e.mdoc != null then
+ cpt.inc(e.class_name)
+ end
+ e.visit_all(self)
+ end
+
+ # Counter of visited entities (by classnames)
+ var cpt = new Counter[String]
+
+ # Do the visitor only count entities with a documentation?
+ var doc_only = false
+end
+
+# The body of the specific work.
+# The main entry point is provided by `test_phase`,
+# This function is then automatically (unless errors where found).
+redef fun do_work(mainmodule, given_mmodules, modelbuilder)
+do
+ var model = modelbuilder.model
+
+ print "All entities, including fictive ones:"
+ var v = new TestModelVisitor
+ v.include_fictive = true
+ v.enter_visit(model)
+ v.cpt.print_elements(10)
+
+ print "All entities:"
+ v = new TestModelVisitor
+ v.enter_visit(model)
+ v.cpt.print_elements(10)
+
+ print "\nAll non-private entities:"
+ v = new TestModelVisitor
+ v.min_visibility = protected_visibility
+ v.enter_visit(model)
+ v.cpt.print_elements(10)
+
+ print "\nAll documented non-private entities:"
+ v = new TestModelVisitor
+ v.min_visibility = protected_visibility
+ v.doc_only = true
+ v.enter_visit(model)
+ v.cpt.print_elements(10)
+end
var opt_gen_unit = new OptionBool("Generate test suite skeleton for a module", "--gen-suite")
var opt_gen_force = new OptionBool("Force test generation even if file exists", "-f", "--force")
var opt_gen_private = new OptionBool("Also generate test case for private methods", "--private")
- var opt_gen_show = new OptionBool("Only display skeleton, do not write file", "--only-show")
+ var opt_gen_show = new OptionBool("Only display the skeleton, do not write any file", "--only-show")
end
redef class ToolContext
# -- target-file
- var opt_file = new OptionString("Specify test suite location.", "-t", "--target-file")
+ var opt_file = new OptionString("Specify test suite location", "-t", "--target-file")
# --pattern
- var opt_pattern = new OptionString("Only run test case with name that match pattern. Examples: 'TestFoo', 'TestFoo*', 'TestFoo::test_foo', 'TestFoo::test_foo*', 'test_foo', 'test_foo*'", "-p", "--pattern")
+ var opt_pattern = new OptionString("Only run test case with name that match pattern", "-p", "--pattern")
end
# Used to test nitunit test files.
var option_context = new OptionContext
# Option --warn
- var opt_warn = new OptionCount("Show more warnings", "-W", "--warn")
+ var opt_warn = new OptionCount("Show additional warnings (advices)", "-W", "--warn")
# Option --warning
var opt_warning = new OptionArray("Show/hide a specific warning", "-w", "--warning")
var opt_set_dummy_tool = new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
# Option --verbose
- var opt_verbose = new OptionCount("Verbose", "-v", "--verbose")
+ var opt_verbose = new OptionCount("Additional messages from the tool", "-v", "--verbose")
# Option --stop-on-first-error
- var opt_stop_on_first_error = new OptionBool("Stop on first error", "--stop-on-first-error")
+ var opt_stop_on_first_error = new OptionBool("Just display the first encountered error then stop", "--stop-on-first-error")
# Option --keep-going
var opt_keep_going = new OptionBool("Continue after errors, whatever the consequences", "--keep-going")
if opt_stub_man.value then
print """
-% {{{toolname.to_upper}}}(1)
-
# NAME
{{{tooldescription.split("\n")[1]}}}
# SYNOPSYS
-{{{toolname}}} [*options*]...
-
# OPTIONS
"""
for o in option_context.options do
var first = true
+ printn "### "
for n in o.names do
if first then first = false else printn ", "
printn "`{n}`"
end
print ""
- print ": {o.helptext}"
+ print "{o.helptext}."
print ""
end
print """
redef class Model
# Generates a UML Class diagram from the entities of a `Model`
- fun tpl_class(ctx: ToolContext, main: MModule): Writable do
+ redef fun tpl_class(ctx, main) do
var t = new Template
for i in mclasses do
if not ctx.private_gen and i.visibility != public_visibility then continue
redef class Model
# Returns a UML package diagram of `main`
- fun tpl_module(ctx: ToolContext, main: MModule): Writable do
+ redef fun tpl_module(ctx, main) do
return main.tpl_module(ctx, main)
end
end
base_simple3.nit
-m test_mixin.nit ../examples/hello_world.nit
-D text=hello -D num=42 -D flag test_define.nit
+-e 'print "hello world"'
+-n -e 'print line' test_prog/README.md test_prog/test_prog.nit
test_phase
test_parser
test_highlight
+test_model_visitor
^nit
nit_args1
nit_args3
nit_args4
+nit_args5
+nit_args6
nitvm_args1
nitvm_args3
nitc_args1
nit_args1
nit_args3
nit_args4
+nit_args5
+nit_args6
nitvm_args1
nitvm_args3
nitc_args1
-base_simple3.nit -q A
-base_simple3.nit -q foo
-base_simple3.nit -q base_simple3
+base_simple3.nit -c A
+base_simple3.nit -c foo
+base_simple3.nit -c base_simple3
--- /dev/null
+hello world
--- /dev/null
+Test program for model tools.
+
+This program creates a fake model that can be used to test tools like:
+
+* `nitdoc`
+* `nitmetrics`
+* `nitx`
+* or others `modelbuilder`.
+# 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.
+
+# A test program with a fake model to check model tools.
+module test_prog
+
+import rpg
+import game
+
+class Starter
+ fun start do end
+end
+
+var starter = new Starter
+starter.start
+
--- /dev/null
+Usage: [OPTION]... <file.nit>...
+Use --help for help
--- /dev/null
+All entities, including fictive ones:
+ list:
+ MMethodDef: 17 (30.35%)
+ MMethod: 15 (26.78%)
+ MClassDef: 7 (12.50%)
+ MClass: 7 (12.50%)
+ MAttributeDef: 3 (5.35%)
+ MAttribute: 3 (5.35%)
+ Model: 1 (1.78%)
+ MGroup: 1 (1.78%)
+ MPackage: 1 (1.78%)
+ MModule: 1 (1.78%)
+All entities:
+ list:
+ MMethodDef: 17 (30.35%)
+ MMethod: 15 (26.78%)
+ MClassDef: 7 (12.50%)
+ MClass: 7 (12.50%)
+ MAttributeDef: 3 (5.35%)
+ MAttribute: 3 (5.35%)
+ Model: 1 (1.78%)
+ MGroup: 1 (1.78%)
+ MPackage: 1 (1.78%)
+ MModule: 1 (1.78%)
+
+All non-private entities:
+ list:
+ MMethodDef: 8 (24.24%)
+ MMethod: 7 (21.21%)
+ MClassDef: 7 (21.21%)
+ MClass: 7 (21.21%)
+ MModule: 1 (3.03%)
+ MGroup: 1 (3.03%)
+ MPackage: 1 (3.03%)
+ Model: 1 (3.03%)
+
+All documented non-private entities:
+ list:
Usage: test_toolcontext [OPTION]...
Test for ToolContext, try --bash-completion.
- -W, --warn Show more warnings
+ -W, --warn Show additional warnings (advices)
-w, --warning Show/hide a specific warning
-q, --quiet Do not show warnings
- --stop-on-first-error Stop on first error
+ --stop-on-first-error Just display the first encountered error then stop
--keep-going Continue after errors, whatever the consequences
--no-color Do not use color to display errors and warnings
--log Generate various log files
--nit-dir Base directory of the Nit installation
-h, -?, --help Show Help (This screen)
--version Show version and exit
- -v, --verbose Verbose
+ -v, --verbose Additional messages from the tool
-a, --option-a option a, do nothing
-b, --option-b option b, do nothing
-c option c, do nothing
--- /dev/null
+base_simple3.nit