diff options
Diffstat (limited to 'src/etc')
58 files changed, 5864 insertions, 0 deletions
diff --git a/src/etc/CONFIGS.md b/src/etc/CONFIGS.md new file mode 100644 index 000000000..542b7bf79 --- /dev/null +++ b/src/etc/CONFIGS.md @@ -0,0 +1,13 @@ +# Configs + +These are some links to repos with configs which ease the use of rust. + +## Officially Maintained Configs + +* [rust.vim](https://github.com/rust-lang/rust.vim) +* [emacs rust-mode](https://github.com/rust-lang/rust-mode) +* [sublime-rust](https://github.com/rust-lang/sublime-rust) +* [gedit-config](https://github.com/rust-lang/gedit-config) +* [kate-config](https://github.com/rust-lang/kate-config) +* [nano-config](https://github.com/rust-lang/nano-config) +* [zsh-config](https://github.com/rust-lang/zsh-config) diff --git a/src/etc/cat-and-grep.sh b/src/etc/cat-and-grep.sh new file mode 100755 index 000000000..77dc52a93 --- /dev/null +++ b/src/etc/cat-and-grep.sh @@ -0,0 +1,84 @@ +#!/bin/sh +set -eu + +# Performs `cat` and `grep` simultaneously for `run-make` tests in the Rust CI. +# +# This program will read lines from stdin and print them to stdout immediately. +# At the same time, it will check if the input line contains the substring or +# regex specified in the command line. If any match is found, the program will +# set the exit code to 0, otherwise 1. +# +# This is written to simplify debugging runmake tests. Since `grep` swallows all +# output, when a test involving `grep` failed, it is impossible to know the +# reason just by reading the failure log. While it is possible to `tee` the +# output into another stream, it becomes pretty annoying to do this for all test +# cases. + +USAGE=' +cat-and-grep.sh [-v] [-e] [-i] s1 s2 s3 ... < input.txt + +Prints the stdin, and exits successfully only if all of `sN` can be found in +some lines of the input. + +Options: + -v Invert match, exits successfully only if all of `sN` cannot be found + -e Regex search, search using extended Regex instead of fixed string + -i Case insensitive search. +' + +GREPPER=fgrep +INVERT=0 +GREPFLAGS='q' +while getopts ':vieh' OPTION; do + case "$OPTION" in + v) + INVERT=1 + ERROR_MSG='should not be found' + ;; + i) + GREPFLAGS="i$GREPFLAGS" + ;; + e) + GREPPER=egrep + ;; + h) + echo "$USAGE" + exit 2 + ;; + *) + break + ;; + esac +done + +shift $((OPTIND - 1)) + +# use gnu version of tool if available (for bsd) +if command -v "g${GREPPER}"; then + GREPPER="g${GREPPER}" +fi + +LOG=$(mktemp -t cgrep.XXXXXX) +trap "rm -f $LOG" EXIT + +printf "[[[ begin stdout ]]]\n\033[90m" +tee "$LOG" +echo >> "$LOG" # ensure at least 1 line of output, otherwise `grep -v` may unconditionally fail. +printf "\033[0m\n[[[ end stdout ]]]\n" + +HAS_ERROR=0 +for MATCH in "$@"; do + if "$GREPPER" "-$GREPFLAGS" -- "$MATCH" "$LOG"; then + if [ "$INVERT" = 1 ]; then + printf "\033[1;31mError: should not match: %s\033[0m\n" "$MATCH" + HAS_ERROR=1 + fi + else + if [ "$INVERT" = 0 ]; then + printf "\033[1;31mError: cannot match: %s\033[0m\n" "$MATCH" + HAS_ERROR=1 + fi + fi +done + +exit "$HAS_ERROR" diff --git a/src/etc/check_missing_items.py b/src/etc/check_missing_items.py new file mode 100644 index 000000000..343dd0387 --- /dev/null +++ b/src/etc/check_missing_items.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python + +# This test ensures that every ID in the produced json actually resolves to an item either in +# `index` or `paths`. It DOES NOT check that the structure of the produced json is actually in +# any way correct, for example an empty map would pass. + +# FIXME: Better error output + +import sys +import json + +crate = json.load(open(sys.argv[1], encoding="utf-8")) + + +def get_local_item(item_id): + if item_id in crate["index"]: + return crate["index"][item_id] + print("Missing local ID:", item_id) + sys.exit(1) + + +# local IDs have to be in `index`, external ones can sometimes be in `index` but otherwise have +# to be in `paths` +def valid_id(item_id): + return item_id in crate["index"] or item_id[0] != "0" and item_id in crate["paths"] + + +def check_generics(generics): + for param in generics["params"]: + check_generic_param(param) + for where_predicate in generics["where_predicates"]: + if "bound_predicate" in where_predicate: + pred = where_predicate["bound_predicate"] + check_type(pred["type"]) + for bound in pred["bounds"]: + check_generic_bound(bound) + elif "region_predicate" in where_predicate: + pred = where_predicate["region_predicate"] + for bound in pred["bounds"]: + check_generic_bound(bound) + elif "eq_predicate" in where_predicate: + pred = where_predicate["eq_predicate"] + check_type(pred["rhs"]) + check_type(pred["lhs"]) + + +def check_generic_param(param): + if "type" in param["kind"]: + ty = param["kind"]["type"] + if ty["default"]: + check_type(ty["default"]) + elif "const" in param["kind"]: + check_type(param["kind"]["const"]) + + +def check_generic_bound(bound): + if "trait_bound" in bound: + for param in bound["trait_bound"]["generic_params"]: + check_generic_param(param) + check_type(bound["trait_bound"]["trait"]) + + +def check_decl(decl): + for (_name, ty) in decl["inputs"]: + check_type(ty) + if decl["output"]: + check_type(decl["output"]) + + +def check_type(ty): + if ty["kind"] == "resolved_path": + for bound in ty["inner"]["param_names"]: + check_generic_bound(bound) + args = ty["inner"]["args"] + if args: + if "angle_bracketed" in args: + for arg in args["angle_bracketed"]["args"]: + if "type" in arg: + check_type(arg["type"]) + elif "const" in arg: + check_type(arg["const"]["type"]) + for binding in args["angle_bracketed"]["bindings"]: + if "equality" in binding["binding"]: + term = binding["binding"]["equality"] + if "type" in term: check_type(term["type"]) + elif "const" in term: check_type(term["const"]) + elif "constraint" in binding["binding"]: + for bound in binding["binding"]["constraint"]: + check_generic_bound(bound) + elif "parenthesized" in args: + for ty in args["parenthesized"]["inputs"]: + check_type(ty) + if args["parenthesized"]["output"]: + check_type(args["parenthesized"]["output"]) + if not valid_id(ty["inner"]["id"]): + print("Type contained an invalid ID:", ty["inner"]["id"]) + sys.exit(1) + elif ty["kind"] == "tuple": + for ty in ty["inner"]: + check_type(ty) + elif ty["kind"] == "slice": + check_type(ty["inner"]) + elif ty["kind"] == "impl_trait": + for bound in ty["inner"]: + check_generic_bound(bound) + elif ty["kind"] in ("raw_pointer", "borrowed_ref", "array"): + check_type(ty["inner"]["type"]) + elif ty["kind"] == "function_pointer": + for param in ty["inner"]["generic_params"]: + check_generic_param(param) + check_decl(ty["inner"]["decl"]) + elif ty["kind"] == "qualified_path": + check_type(ty["inner"]["self_type"]) + check_type(ty["inner"]["trait"]) + + +work_list = set([crate["root"]]) +visited = work_list.copy() + +while work_list: + current = work_list.pop() + visited.add(current) + item = get_local_item(current) + # check intradoc links + for (_name, link) in item["links"].items(): + if not valid_id(link): + print("Intra-doc link contains invalid ID:", link) + + # check all fields that reference types such as generics as well as nested items + # (modules, structs, traits, and enums) + if item["kind"] == "module": + work_list |= set(item["inner"]["items"]) - visited + elif item["kind"] == "struct": + check_generics(item["inner"]["generics"]) + work_list |= ( + set(item["inner"]["fields"]) | set(item["inner"]["impls"]) + ) - visited + elif item["kind"] == "struct_field": + check_type(item["inner"]) + elif item["kind"] == "enum": + check_generics(item["inner"]["generics"]) + work_list |= ( + set(item["inner"]["variants"]) | set(item["inner"]["impls"]) + ) - visited + elif item["kind"] == "variant": + if item["inner"]["variant_kind"] == "tuple": + for ty in item["inner"]["variant_inner"]: + check_type(ty) + elif item["inner"]["variant_kind"] == "struct": + work_list |= set(item["inner"]["variant_inner"]) - visited + elif item["kind"] in ("function", "method"): + check_generics(item["inner"]["generics"]) + check_decl(item["inner"]["decl"]) + elif item["kind"] in ("static", "constant", "assoc_const"): + check_type(item["inner"]["type"]) + elif item["kind"] == "typedef": + check_type(item["inner"]["type"]) + check_generics(item["inner"]["generics"]) + elif item["kind"] == "opaque_ty": + check_generics(item["inner"]["generics"]) + for bound in item["inner"]["bounds"]: + check_generic_bound(bound) + elif item["kind"] == "trait_alias": + check_generics(item["inner"]["params"]) + for bound in item["inner"]["bounds"]: + check_generic_bound(bound) + elif item["kind"] == "trait": + check_generics(item["inner"]["generics"]) + for bound in item["inner"]["bounds"]: + check_generic_bound(bound) + work_list |= ( + set(item["inner"]["items"]) | set(item["inner"]["implementations"]) + ) - visited + elif item["kind"] == "impl": + check_generics(item["inner"]["generics"]) + if item["inner"]["trait"]: + check_type(item["inner"]["trait"]) + if item["inner"]["blanket_impl"]: + check_type(item["inner"]["blanket_impl"]) + check_type(item["inner"]["for"]) + for assoc_item in item["inner"]["items"]: + if not valid_id(assoc_item): + print("Impl block referenced a missing ID:", assoc_item) + sys.exit(1) + elif item["kind"] == "assoc_type": + for bound in item["inner"]["bounds"]: + check_generic_bound(bound) + if item["inner"]["default"]: + check_type(item["inner"]["default"]) diff --git a/src/etc/cpu-usage-over-time-plot.sh b/src/etc/cpu-usage-over-time-plot.sh new file mode 100755 index 000000000..1c3425591 --- /dev/null +++ b/src/etc/cpu-usage-over-time-plot.sh @@ -0,0 +1,59 @@ +#!/bin/bash + +# A small script to help visualizing CPU usage over time data collected on CI +# using `gnuplot`. +# +# This script is expected to be called with two arguments. The first is the full +# commit SHA of the build you're interested in, and the second is the name of +# the builder. For example: +# +# ./src/etc/cpu-usage-over-time-plot.sh 7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c x86_64-gnu +# +# That will generate `$builder.png` in the current directory which you can open +# up to see a hopefully pretty graph. +# +# Improvements to this script are greatly appreciated! + +if [[ $# != 2 ]]; then + echo "expected 2 arguments, recieved $#" + echo "example usage: './src/etc/cpu-usage-over-time-plot.sh \ +7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c \ +x86_64-gnu'" + exit 1 +fi + +set -ex + +bucket=rust-lang-ci2 +commit=$1 +builder=$2 + +curl -O https://$bucket.s3.amazonaws.com/rustc-builds/$commit/cpu-$builder.csv + +gnuplot <<-EOF +reset +set timefmt '%Y-%m-%dT%H:%M:%S' +set xdata time +set ylabel "CPU Usage %" +set xlabel "Time" +set datafile sep ',' +set term png size 3000,1000 +set output "$builder-$commit-cpu-usage-plot.png" +set grid + +f(x) = mean_y +fit f(x) 'cpu-$builder.csv' using 1:(100-\$2) via mean_y + +set label 1 gprintf("Average = %g%%", mean_y) center font ",18" +set label 1 at graph 0.50, 0.25 +set xtics rotate by 45 offset -2,-2.4 300 +set ytics 10 +set boxwidth 0.5 + +plot \\ + mean_y with lines linetype 1 linecolor rgb "#ff0000" title "average", "cpu-$builder.csv" \\ + using 1:(100-\$2) with points pointtype 7 pointsize 0.4 title "$builder", "" \\ + using 1:(100-\$2) smooth bezier linewidth 3 title "bezier" +EOF + +rm "cpu-$builder.csv" diff --git a/src/etc/ctags.rust b/src/etc/ctags.rust new file mode 100644 index 000000000..4397f290a --- /dev/null +++ b/src/etc/ctags.rust @@ -0,0 +1,11 @@ +--langdef=Rust +--langmap=Rust:.rs +--regex-Rust=/^[ \t]*(#\[[^\]]\][ \t]*)*(pub[ \t]+)?(extern[ \t]+)?("[^"]+"[ \t]+)?(unsafe[ \t]+)?fn[ \t]+([a-zA-Z0-9_]+)/\6/f,functions,function definitions/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?type[ \t]+([a-zA-Z0-9_]+)/\2/T,types,type definitions/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?enum[ \t]+([a-zA-Z0-9_]+)/\2/g,enum,enumeration names/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?struct[ \t]+([a-zA-Z0-9_]+)/\2/s,structure names/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?mod[ \t]+([a-zA-Z0-9_]+)/\2/m,modules,module names/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?(static|const)[ \t]+(mut[ \t]+)?([a-zA-Z0-9_]+)/\4/c,consts,static constants/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?(unsafe[ \t]+)?trait[ \t]+([a-zA-Z0-9_]+)/\3/t,traits,traits/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?(unsafe[ \t]+)?impl([ \t\n]*<[^>]*>)?[ \t]+(([a-zA-Z0-9_:]+)[ \t]*(<[^>]*>)?[ \t]+(for)[ \t]+)?([a-zA-Z0-9_]+)/\5 \7 \8/i,impls,trait implementations/ +--regex-Rust=/^[ \t]*macro_rules![ \t]+([a-zA-Z0-9_]+)/\1/d,macros,macro definitions/ diff --git a/src/etc/dec2flt_table.py b/src/etc/dec2flt_table.py new file mode 100644 index 000000000..aa5188d96 --- /dev/null +++ b/src/etc/dec2flt_table.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 + +""" +Generate powers of five using Daniel Lemire's ``Eisel-Lemire algorithm`` for use in +decimal to floating point conversions. + +Specifically, computes and outputs (as Rust code) a table of 10^e for some +range of exponents e. The output is one array of 128 bit significands. +The base two exponents can be inferred using a logarithmic slope +of the decimal exponent. The approximations are normalized and rounded perfectly, +i.e., within 0.5 ULP of the true value. + +Adapted from Daniel Lemire's fast_float ``table_generation.py``, +available here: <https://github.com/fastfloat/fast_float/blob/main/script/table_generation.py>. +""" +from __future__ import print_function +from math import ceil, floor, log, log2 +from fractions import Fraction +from collections import deque + +HEADER = """ +//! Pre-computed tables powers-of-5 for extended-precision representations. +//! +//! These tables enable fast scaling of the significant digits +//! of a float to the decimal exponent, with minimal rounding +//! errors, in a 128 or 192-bit representation. +//! +//! DO NOT MODIFY: Generated by `src/etc/dec2flt_table.py` +""" + +STATIC_WARNING = """ +// Use static to avoid long compile times: Rust compiler errors +// can have the entire table compiled multiple times, and then +// emit code multiple times, even if it's stripped out in +// the final binary. +""" + +def main(): + min_exp = minimum_exponent(10) + max_exp = maximum_exponent(10) + bias = -minimum_exponent(5) + + print(HEADER.strip()) + print() + print('pub const SMALLEST_POWER_OF_FIVE: i32 = {};'.format(min_exp)) + print('pub const LARGEST_POWER_OF_FIVE: i32 = {};'.format(max_exp)) + print('pub const N_POWERS_OF_FIVE: usize = ', end='') + print('(LARGEST_POWER_OF_FIVE - SMALLEST_POWER_OF_FIVE + 1) as usize;') + print() + print_proper_powers(min_exp, max_exp, bias) + + +def minimum_exponent(base): + return ceil(log(5e-324, base) - log(0xFFFFFFFFFFFFFFFF, base)) + + +def maximum_exponent(base): + return floor(log(1.7976931348623157e+308, base)) + + +def print_proper_powers(min_exp, max_exp, bias): + powers = deque() + + # Add negative exponents. + # 2^(2b)/(5^−q) with b=64 + int(math.ceil(log2(5^−q))) + powers = [] + for q in range(min_exp, 0): + power5 = 5 ** -q + z = 0 + while (1 << z) < power5: + z += 1 + if q >= -27: + b = z + 127 + c = 2 ** b // power5 + 1 + powers.append((c, q)) + else: + b = 2 * z + 2 * 64 + c = 2 ** b // power5 + 1 + # truncate + while c >= (1<<128): + c //= 2 + powers.append((c, q)) + + # Add positive exponents + for q in range(0, max_exp + 1): + power5 = 5 ** q + # move the most significant bit in position + while power5 < (1<<127): + power5 *= 2 + # *truncate* + while power5 >= (1<<128): + power5 //= 2 + powers.append((power5, q)) + + # Print the powers. + print(STATIC_WARNING.strip()) + print('#[rustfmt::skip]') + typ = '[(u64, u64); N_POWERS_OF_FIVE]' + print('pub static POWER_OF_FIVE_128: {} = ['.format(typ)) + lo_mask = (1 << 64) - 1 + for c, exp in powers: + hi = '0x{:x}'.format(c // (1 << 64)) + lo = '0x{:x}'.format(c % (1 << 64)) + value = ' ({}, {}), '.format(hi, lo) + comment = '// {}^{}'.format(5, exp) + print(value.ljust(46, ' ') + comment) + print('];') + + +if __name__ == '__main__': + main() diff --git a/src/etc/gdb_load_rust_pretty_printers.py b/src/etc/gdb_load_rust_pretty_printers.py new file mode 100644 index 000000000..856b5df2d --- /dev/null +++ b/src/etc/gdb_load_rust_pretty_printers.py @@ -0,0 +1,3 @@ +import gdb +import gdb_lookup +gdb_lookup.register_printers(gdb.current_objfile()) diff --git a/src/etc/gdb_lookup.py b/src/etc/gdb_lookup.py new file mode 100644 index 000000000..292e91b4d --- /dev/null +++ b/src/etc/gdb_lookup.py @@ -0,0 +1,92 @@ +import gdb +import re + +from gdb_providers import * +from rust_types import * + + +_gdb_version_matched = re.search('([0-9]+)\\.([0-9]+)', gdb.VERSION) +gdb_version = [int(num) for num in _gdb_version_matched.groups()] if _gdb_version_matched else [] + +def register_printers(objfile): + objfile.pretty_printers.append(lookup) + + +# BACKCOMPAT: rust 1.35 +def is_hashbrown_hashmap(hash_map): + return len(hash_map.type.fields()) == 1 + + +def classify_rust_type(type): + type_class = type.code + if type_class == gdb.TYPE_CODE_STRUCT: + return classify_struct(type.tag, type.fields()) + if type_class == gdb.TYPE_CODE_UNION: + return classify_union(type.fields()) + + return RustType.OTHER + + +def check_enum_discriminant(valobj): + content = valobj[valobj.type.fields()[0]] + fields = content.type.fields() + if len(fields) > 1: + discriminant = int(content[fields[0]]) + 1 + if discriminant > len(fields): + # invalid discriminant + return False + return True + + +def lookup(valobj): + rust_type = classify_rust_type(valobj.type) + + if rust_type == RustType.ENUM: + # use enum provider only for GDB <7.12 + if gdb_version[0] < 7 or (gdb_version[0] == 7 and gdb_version[1] < 12): + if check_enum_discriminant(valobj): + return EnumProvider(valobj) + + if rust_type == RustType.STD_STRING: + return StdStringProvider(valobj) + if rust_type == RustType.STD_OS_STRING: + return StdOsStringProvider(valobj) + if rust_type == RustType.STD_STR: + return StdStrProvider(valobj) + if rust_type == RustType.STD_SLICE: + return StdSliceProvider(valobj) + if rust_type == RustType.STD_VEC: + return StdVecProvider(valobj) + if rust_type == RustType.STD_VEC_DEQUE: + return StdVecDequeProvider(valobj) + if rust_type == RustType.STD_BTREE_SET: + return StdBTreeSetProvider(valobj) + if rust_type == RustType.STD_BTREE_MAP: + return StdBTreeMapProvider(valobj) + if rust_type == RustType.STD_HASH_MAP: + if is_hashbrown_hashmap(valobj): + return StdHashMapProvider(valobj) + else: + return StdOldHashMapProvider(valobj) + if rust_type == RustType.STD_HASH_SET: + hash_map = valobj[valobj.type.fields()[0]] + if is_hashbrown_hashmap(hash_map): + return StdHashMapProvider(valobj, show_values=False) + else: + return StdOldHashMapProvider(hash_map, show_values=False) + + if rust_type == RustType.STD_RC: + return StdRcProvider(valobj) + if rust_type == RustType.STD_ARC: + return StdRcProvider(valobj, is_atomic=True) + + if rust_type == RustType.STD_CELL: + return StdCellProvider(valobj) + if rust_type == RustType.STD_REF: + return StdRefProvider(valobj) + if rust_type == RustType.STD_REF_MUT: + return StdRefProvider(valobj) + if rust_type == RustType.STD_REF_CELL: + return StdRefCellProvider(valobj) + + return None diff --git a/src/etc/gdb_providers.py b/src/etc/gdb_providers.py new file mode 100644 index 000000000..0a52b8c97 --- /dev/null +++ b/src/etc/gdb_providers.py @@ -0,0 +1,431 @@ +from sys import version_info + +import gdb + +if version_info[0] >= 3: + xrange = range + +ZERO_FIELD = "__0" +FIRST_FIELD = "__1" + + +def unwrap_unique_or_non_null(unique_or_nonnull): + # BACKCOMPAT: rust 1.32 + # https://github.com/rust-lang/rust/commit/7a0911528058e87d22ea305695f4047572c5e067 + # BACKCOMPAT: rust 1.60 + # https://github.com/rust-lang/rust/commit/2a91eeac1a2d27dd3de1bf55515d765da20fd86f + ptr = unique_or_nonnull["pointer"] + return ptr if ptr.type.code == gdb.TYPE_CODE_PTR else ptr[ptr.type.fields()[0]] + + +class EnumProvider: + def __init__(self, valobj): + content = valobj[valobj.type.fields()[0]] + fields = content.type.fields() + self.empty = len(fields) == 0 + if not self.empty: + if len(fields) == 1: + discriminant = 0 + else: + discriminant = int(content[fields[0]]) + 1 + self.active_variant = content[fields[discriminant]] + self.name = fields[discriminant].name + self.full_name = "{}::{}".format(valobj.type.name, self.name) + else: + self.full_name = valobj.type.name + + def to_string(self): + return self.full_name + + def children(self): + if not self.empty: + yield self.name, self.active_variant + + +class StdStringProvider: + def __init__(self, valobj): + self.valobj = valobj + vec = valobj["vec"] + self.length = int(vec["len"]) + self.data_ptr = unwrap_unique_or_non_null(vec["buf"]["ptr"]) + + def to_string(self): + return self.data_ptr.lazy_string(encoding="utf-8", length=self.length) + + @staticmethod + def display_hint(): + return "string" + + +class StdOsStringProvider: + def __init__(self, valobj): + self.valobj = valobj + buf = self.valobj["inner"]["inner"] + is_windows = "Wtf8Buf" in buf.type.name + vec = buf[ZERO_FIELD] if is_windows else buf + + self.length = int(vec["len"]) + self.data_ptr = unwrap_unique_or_non_null(vec["buf"]["ptr"]) + + def to_string(self): + return self.data_ptr.lazy_string(encoding="utf-8", length=self.length) + + def display_hint(self): + return "string" + + +class StdStrProvider: + def __init__(self, valobj): + self.valobj = valobj + self.length = int(valobj["length"]) + self.data_ptr = valobj["data_ptr"] + + def to_string(self): + return self.data_ptr.lazy_string(encoding="utf-8", length=self.length) + + @staticmethod + def display_hint(): + return "string" + +def _enumerate_array_elements(element_ptrs): + for (i, element_ptr) in enumerate(element_ptrs): + key = "[{}]".format(i) + element = element_ptr.dereference() + + try: + # rust-lang/rust#64343: passing deref expr to `str` allows + # catching exception on garbage pointer + str(element) + except RuntimeError: + yield key, "inaccessible" + + break + + yield key, element + +class StdSliceProvider: + def __init__(self, valobj): + self.valobj = valobj + self.length = int(valobj["length"]) + self.data_ptr = valobj["data_ptr"] + + def to_string(self): + return "{}(size={})".format(self.valobj.type, self.length) + + def children(self): + return _enumerate_array_elements( + self.data_ptr + index for index in xrange(self.length) + ) + + @staticmethod + def display_hint(): + return "array" + +class StdVecProvider: + def __init__(self, valobj): + self.valobj = valobj + self.length = int(valobj["len"]) + self.data_ptr = unwrap_unique_or_non_null(valobj["buf"]["ptr"]) + + def to_string(self): + return "Vec(size={})".format(self.length) + + def children(self): + return _enumerate_array_elements( + self.data_ptr + index for index in xrange(self.length) + ) + + @staticmethod + def display_hint(): + return "array" + + +class StdVecDequeProvider: + def __init__(self, valobj): + self.valobj = valobj + self.head = int(valobj["head"]) + self.tail = int(valobj["tail"]) + self.cap = int(valobj["buf"]["cap"]) + self.data_ptr = unwrap_unique_or_non_null(valobj["buf"]["ptr"]) + if self.head >= self.tail: + self.size = self.head - self.tail + else: + self.size = self.cap + self.head - self.tail + + def to_string(self): + return "VecDeque(size={})".format(self.size) + + def children(self): + return _enumerate_array_elements( + (self.data_ptr + ((self.tail + index) % self.cap)) for index in xrange(self.size) + ) + + @staticmethod + def display_hint(): + return "array" + + +class StdRcProvider: + def __init__(self, valobj, is_atomic=False): + self.valobj = valobj + self.is_atomic = is_atomic + self.ptr = unwrap_unique_or_non_null(valobj["ptr"]) + self.value = self.ptr["data" if is_atomic else "value"] + self.strong = self.ptr["strong"]["v" if is_atomic else "value"]["value"] + self.weak = self.ptr["weak"]["v" if is_atomic else "value"]["value"] - 1 + + def to_string(self): + if self.is_atomic: + return "Arc(strong={}, weak={})".format(int(self.strong), int(self.weak)) + else: + return "Rc(strong={}, weak={})".format(int(self.strong), int(self.weak)) + + def children(self): + yield "value", self.value + yield "strong", self.strong + yield "weak", self.weak + + +class StdCellProvider: + def __init__(self, valobj): + self.value = valobj["value"]["value"] + + def to_string(self): + return "Cell" + + def children(self): + yield "value", self.value + + +class StdRefProvider: + def __init__(self, valobj): + self.value = valobj["value"].dereference() + self.borrow = valobj["borrow"]["borrow"]["value"]["value"] + + def to_string(self): + borrow = int(self.borrow) + if borrow >= 0: + return "Ref(borrow={})".format(borrow) + else: + return "Ref(borrow_mut={})".format(-borrow) + + def children(self): + yield "*value", self.value + yield "borrow", self.borrow + + +class StdRefCellProvider: + def __init__(self, valobj): + self.value = valobj["value"]["value"] + self.borrow = valobj["borrow"]["value"]["value"] + + def to_string(self): + borrow = int(self.borrow) + if borrow >= 0: + return "RefCell(borrow={})".format(borrow) + else: + return "RefCell(borrow_mut={})".format(-borrow) + + def children(self): + yield "value", self.value + yield "borrow", self.borrow + + +# Yields children (in a provider's sense of the word) for a BTreeMap. +def children_of_btree_map(map): + # Yields each key/value pair in the node and in any child nodes. + def children_of_node(node_ptr, height): + def cast_to_internal(node): + internal_type_name = node.type.target().name.replace("LeafNode", "InternalNode", 1) + internal_type = gdb.lookup_type(internal_type_name) + return node.cast(internal_type.pointer()) + + if node_ptr.type.name.startswith("alloc::collections::btree::node::BoxedNode<"): + # BACKCOMPAT: rust 1.49 + node_ptr = node_ptr["ptr"] + node_ptr = unwrap_unique_or_non_null(node_ptr) + leaf = node_ptr.dereference() + keys = leaf["keys"] + vals = leaf["vals"] + edges = cast_to_internal(node_ptr)["edges"] if height > 0 else None + length = leaf["len"] + + for i in xrange(0, length + 1): + if height > 0: + child_ptr = edges[i]["value"]["value"] + for child in children_of_node(child_ptr, height - 1): + yield child + if i < length: + # Avoid "Cannot perform pointer math on incomplete type" on zero-sized arrays. + key_type_size = keys.type.sizeof + val_type_size = vals.type.sizeof + key = keys[i]["value"]["value"] if key_type_size > 0 else gdb.parse_and_eval("()") + val = vals[i]["value"]["value"] if val_type_size > 0 else gdb.parse_and_eval("()") + yield key, val + + if map["length"] > 0: + root = map["root"] + if root.type.name.startswith("core::option::Option<"): + root = root.cast(gdb.lookup_type(root.type.name[21:-1])) + node_ptr = root["node"] + height = root["height"] + for child in children_of_node(node_ptr, height): + yield child + + +class StdBTreeSetProvider: + def __init__(self, valobj): + self.valobj = valobj + + def to_string(self): + return "BTreeSet(size={})".format(self.valobj["map"]["length"]) + + def children(self): + inner_map = self.valobj["map"] + for i, (child, _) in enumerate(children_of_btree_map(inner_map)): + yield "[{}]".format(i), child + + @staticmethod + def display_hint(): + return "array" + + +class StdBTreeMapProvider: + def __init__(self, valobj): + self.valobj = valobj + + def to_string(self): + return "BTreeMap(size={})".format(self.valobj["length"]) + + def children(self): + for i, (key, val) in enumerate(children_of_btree_map(self.valobj)): + yield "key{}".format(i), key + yield "val{}".format(i), val + + @staticmethod + def display_hint(): + return "map" + + +# BACKCOMPAT: rust 1.35 +class StdOldHashMapProvider: + def __init__(self, valobj, show_values=True): + self.valobj = valobj + self.show_values = show_values + + self.table = self.valobj["table"] + self.size = int(self.table["size"]) + self.hashes = self.table["hashes"] + self.hash_uint_type = self.hashes.type + self.hash_uint_size = self.hashes.type.sizeof + self.modulo = 2 ** self.hash_uint_size + self.data_ptr = self.hashes[ZERO_FIELD]["pointer"] + + self.capacity_mask = int(self.table["capacity_mask"]) + self.capacity = (self.capacity_mask + 1) % self.modulo + + marker = self.table["marker"].type + self.pair_type = marker.template_argument(0) + self.pair_type_size = self.pair_type.sizeof + + self.valid_indices = [] + for idx in range(self.capacity): + data_ptr = self.data_ptr.cast(self.hash_uint_type.pointer()) + address = data_ptr + idx + hash_uint = address.dereference() + hash_ptr = hash_uint[ZERO_FIELD]["pointer"] + if int(hash_ptr) != 0: + self.valid_indices.append(idx) + + def to_string(self): + if self.show_values: + return "HashMap(size={})".format(self.size) + else: + return "HashSet(size={})".format(self.size) + + def children(self): + start = int(self.data_ptr) & ~1 + + hashes = self.hash_uint_size * self.capacity + align = self.pair_type_size + len_rounded_up = (((((hashes + align) % self.modulo - 1) % self.modulo) & ~( + (align - 1) % self.modulo)) % self.modulo - hashes) % self.modulo + + pairs_offset = hashes + len_rounded_up + pairs_start = gdb.Value(start + pairs_offset).cast(self.pair_type.pointer()) + + for index in range(self.size): + table_index = self.valid_indices[index] + idx = table_index & self.capacity_mask + element = (pairs_start + idx).dereference() + if self.show_values: + yield "key{}".format(index), element[ZERO_FIELD] + yield "val{}".format(index), element[FIRST_FIELD] + else: + yield "[{}]".format(index), element[ZERO_FIELD] + + def display_hint(self): + return "map" if self.show_values else "array" + + +class StdHashMapProvider: + def __init__(self, valobj, show_values=True): + self.valobj = valobj + self.show_values = show_values + + table = self.table() + table_inner = table["table"] + capacity = int(table_inner["bucket_mask"]) + 1 + ctrl = table_inner["ctrl"]["pointer"] + + self.size = int(table_inner["items"]) + self.pair_type = table.type.template_argument(0).strip_typedefs() + + self.new_layout = not table_inner.type.has_key("data") + if self.new_layout: + self.data_ptr = ctrl.cast(self.pair_type.pointer()) + else: + self.data_ptr = table_inner["data"]["pointer"] + + self.valid_indices = [] + for idx in range(capacity): + address = ctrl + idx + value = address.dereference() + is_presented = value & 128 == 0 + if is_presented: + self.valid_indices.append(idx) + + def table(self): + if self.show_values: + hashbrown_hashmap = self.valobj["base"] + elif self.valobj.type.fields()[0].name == "map": + # BACKCOMPAT: rust 1.47 + # HashSet wraps std::collections::HashMap, which wraps hashbrown::HashMap + hashbrown_hashmap = self.valobj["map"]["base"] + else: + # HashSet wraps hashbrown::HashSet, which wraps hashbrown::HashMap + hashbrown_hashmap = self.valobj["base"]["map"] + return hashbrown_hashmap["table"] + + def to_string(self): + if self.show_values: + return "HashMap(size={})".format(self.size) + else: + return "HashSet(size={})".format(self.size) + + def children(self): + pairs_start = self.data_ptr + + for index in range(self.size): + idx = self.valid_indices[index] + if self.new_layout: + idx = -(idx + 1) + element = (pairs_start + idx).dereference() + if self.show_values: + yield "key{}".format(index), element[ZERO_FIELD] + yield "val{}".format(index), element[FIRST_FIELD] + else: + yield "[{}]".format(index), element[ZERO_FIELD] + + def display_hint(self): + return "map" if self.show_values else "array" diff --git a/src/etc/generate-deriving-span-tests.py b/src/etc/generate-deriving-span-tests.py new file mode 100755 index 000000000..d38f5add7 --- /dev/null +++ b/src/etc/generate-deriving-span-tests.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python + +""" +This script creates a pile of UI tests check that all the +derives have spans that point to the fields, rather than the +#[derive(...)] line. + +sample usage: src/etc/generate-deriving-span-tests.py +""" + +import os +import stat + +TEST_DIR = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../test/ui/derives/')) + +TEMPLATE = """\ +// This file was auto-generated using 'src/etc/generate-deriving-span-tests.py' + +{error_deriving} +struct Error; +{code} +fn main() {{}} +""" + +ENUM_STRING = """ +#[derive({traits})] +enum Enum {{ + A( + Error {errors} + ) +}} +""" +ENUM_STRUCT_VARIANT_STRING = """ +#[derive({traits})] +enum Enum {{ + A {{ + x: Error {errors} + }} +}} +""" +STRUCT_STRING = """ +#[derive({traits})] +struct Struct {{ + x: Error {errors} +}} +""" +STRUCT_TUPLE_STRING = """ +#[derive({traits})] +struct Struct( + Error {errors} +); +""" + +ENUM_TUPLE, ENUM_STRUCT, STRUCT_FIELDS, STRUCT_TUPLE = range(4) + + +def create_test_case(type, trait, super_traits, error_count): + string = [ENUM_STRING, ENUM_STRUCT_VARIANT_STRING, STRUCT_STRING, STRUCT_TUPLE_STRING][type] + all_traits = ','.join([trait] + super_traits) + super_traits = ','.join(super_traits) + error_deriving = '#[derive(%s)]' % super_traits if super_traits else '' + + errors = '\n'.join('//~%s ERROR' % ('^' * n) for n in range(error_count)) + code = string.format(traits=all_traits, errors=errors) + return TEMPLATE.format(error_deriving=error_deriving, code=code) + + +def write_file(name, string): + test_file = os.path.join(TEST_DIR, 'derives-span-%s.rs' % name) + + # set write permission if file exists, so it can be changed + if os.path.exists(test_file): + os.chmod(test_file, stat.S_IWUSR) + + with open(test_file, 'w') as f: + f.write(string) + + # mark file read-only + os.chmod(test_file, stat.S_IRUSR|stat.S_IRGRP|stat.S_IROTH) + + +ENUM = 1 +STRUCT = 2 +ALL = STRUCT | ENUM + +traits = { + 'Default': (STRUCT, [], 1), + 'FromPrimitive': (0, [], 0), # only works for C-like enums + + 'Decodable': (0, [], 0), # FIXME: quoting gives horrible spans + 'Encodable': (0, [], 0), # FIXME: quoting gives horrible spans +} + +for (trait, supers, errs) in [('Clone', [], 1), + ('PartialEq', [], 2), + ('PartialOrd', ['PartialEq'], 1), + ('Eq', ['PartialEq'], 1), + ('Ord', ['Eq', 'PartialOrd', 'PartialEq'], 1), + ('Debug', [], 1), + ('Hash', [], 1)]: + traits[trait] = (ALL, supers, errs) + +for (trait, (types, super_traits, error_count)) in traits.items(): + mk = lambda ty: create_test_case(ty, trait, super_traits, error_count) + if types & ENUM: + write_file(trait + '-enum', mk(ENUM_TUPLE)) + write_file(trait + '-enum-struct-variant', mk(ENUM_STRUCT)) + if types & STRUCT: + write_file(trait + '-struct', mk(STRUCT_FIELDS)) + write_file(trait + '-tuple-struct', mk(STRUCT_TUPLE)) diff --git a/src/etc/generate-keyword-tests.py b/src/etc/generate-keyword-tests.py new file mode 100755 index 000000000..77c3d2758 --- /dev/null +++ b/src/etc/generate-keyword-tests.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python + +""" +This script takes a list of keywords and generates a testcase, that checks +if using the keyword as identifier fails, for every keyword. The generate +test files are set read-only. +Test for https://github.com/rust-lang/rust/issues/2275 + +sample usage: src/etc/generate-keyword-tests.py as break +""" + +import sys +import os +import stat + + +template = """\ +// This file was auto-generated using 'src/etc/generate-keyword-tests.py %s' + +fn main() { + let %s = "foo"; //~ error: expected pattern, found keyword `%s` +} +""" + +test_dir = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../test/ui/parser') +) + +for kw in sys.argv[1:]: + test_file = os.path.join(test_dir, 'keyword-%s-as-identifier.rs' % kw) + + # set write permission if file exists, so it can be changed + if os.path.exists(test_file): + os.chmod(test_file, stat.S_IWUSR) + + with open(test_file, 'wt') as f: + f.write(template % (kw, kw, kw)) + + # mark file read-only + os.chmod(test_file, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) diff --git a/src/etc/htmldocck.py b/src/etc/htmldocck.py new file mode 100644 index 000000000..d02ac9d9c --- /dev/null +++ b/src/etc/htmldocck.py @@ -0,0 +1,655 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +r""" +htmldocck.py is a custom checker script for Rustdoc HTML outputs. + +# How and why? + +The principle is simple: This script receives a path to generated HTML +documentation and a "template" script, which has a series of check +commands like `@has` or `@matches`. Each command is used to check if +some pattern is present or not present in the particular file or in +a particular node of the HTML tree. In many cases, the template script +happens to be the source code given to rustdoc. + +While it indeed is possible to test in smaller portions, it has been +hard to construct tests in this fashion and major rendering errors were +discovered much later. This script is designed to make black-box and +regression testing of Rustdoc easy. This does not preclude the needs for +unit testing, but can be used to complement related tests by quickly +showing the expected renderings. + +In order to avoid one-off dependencies for this task, this script uses +a reasonably working HTML parser and the existing XPath implementation +from Python's standard library. Hopefully, we won't render +non-well-formed HTML. + +# Commands + +Commands start with an `@` followed by a command name (letters and +hyphens), and zero or more arguments separated by one or more whitespace +characters and optionally delimited with single or double quotes. The `@` +mark cannot be preceded by a non-whitespace character. Other lines +(including every text up to the first `@`) are ignored, but it is +recommended to avoid the use of `@` in the template file. + +There are a number of supported commands: + +* `@has PATH` checks for the existence of the given file. + + `PATH` is relative to the output directory. It can be given as `-` + which repeats the most recently used `PATH`. + +* `@has PATH PATTERN` and `@matches PATH PATTERN` checks for + the occurrence of the given pattern `PATTERN` in the specified file. + Only one occurrence of the pattern is enough. + + For `@has`, `PATTERN` is a whitespace-normalized (every consecutive + whitespace being replaced by one single space character) string. + The entire file is also whitespace-normalized including newlines. + + For `@matches`, `PATTERN` is a Python-supported regular expression. + The file remains intact but the regexp is matched without the `MULTILINE` + and `IGNORECASE` options. You can still use a prefix `(?m)` or `(?i)` + to override them, and `\A` and `\Z` for definitely matching + the beginning and end of the file. + + (The same distinction goes to other variants of these commands.) + +* `@has PATH XPATH PATTERN` and `@matches PATH XPATH PATTERN` checks for + the presence of the given XPath `XPATH` in the specified HTML file, + and also the occurrence of the given pattern `PATTERN` in the matching + node or attribute. Only one occurrence of the pattern in the match + is enough. + + `PATH` should be a valid and well-formed HTML file. It does *not* + accept arbitrary HTML5; it should have matching open and close tags + and correct entity references at least. + + `XPATH` is an XPath expression to match. The XPath is fairly limited: + `tag`, `*`, `.`, `//`, `..`, `[@attr]`, `[@attr='value']`, `[tag]`, + `[POS]` (element located in given `POS`), `[last()-POS]`, `text()` + and `@attr` (both as the last segment) are supported. Some examples: + + - `//pre` or `.//pre` matches any element with a name `pre`. + - `//a[@href]` matches any element with an `href` attribute. + - `//*[@class="impl"]//code` matches any element with a name `code`, + which is an ancestor of some element which `class` attr is `impl`. + - `//h1[@class="fqn"]/span[1]/a[last()]/@class` matches a value of + `class` attribute in the last `a` element (can be followed by more + elements that are not `a`) inside the first `span` in the `h1` with + a class of `fqn`. Note that there cannot be any additional elements + between them due to the use of `/` instead of `//`. + + Do not try to use non-absolute paths, it won't work due to the flawed + ElementTree implementation. The script rejects them. + + For the text matches (i.e. paths not ending with `@attr`), any + subelements are flattened into one string; this is handy for ignoring + highlights for example. If you want to simply check for the presence of + a given node or attribute, use an empty string (`""`) as a `PATTERN`. + +* `@count PATH XPATH COUNT` checks for the occurrence of the given XPath + in the specified file. The number of occurrences must match the given + count. + +* `@count PATH XPATH TEXT COUNT` checks for the occurrence of the given XPath + with the given text in the specified file. The number of occurrences must + match the given count. + +* `@snapshot NAME PATH XPATH` creates a snapshot test named NAME. + A snapshot test captures a subtree of the DOM, at the location + determined by the XPath, and compares it to a pre-recorded value + in a file. The file's name is the test's name with the `.rs` extension + replaced with `.NAME.html`, where NAME is the snapshot's name. + + htmldocck supports the `--bless` option to accept the current subtree + as expected, saving it to the file determined by the snapshot's name. + compiletest's `--bless` flag is forwarded to htmldocck. + +* `@has-dir PATH` checks for the existence of the given directory. + +All conditions can be negated with `!`. `@!has foo/type.NoSuch.html` +checks if the given file does not exist, for example. + +""" + +from __future__ import absolute_import, print_function, unicode_literals + +import codecs +import io +import sys +import os.path +import re +import shlex +from collections import namedtuple +try: + from html.parser import HTMLParser +except ImportError: + from HTMLParser import HTMLParser +try: + from xml.etree import cElementTree as ET +except ImportError: + from xml.etree import ElementTree as ET + +try: + from html.entities import name2codepoint +except ImportError: + from htmlentitydefs import name2codepoint + +# "void elements" (no closing tag) from the HTML Standard section 12.1.2 +VOID_ELEMENTS = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', + 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'} + +# Python 2 -> 3 compatibility +try: + unichr +except NameError: + unichr = chr + + +channel = os.environ["DOC_RUST_LANG_ORG_CHANNEL"] + +# Initialized in main +rust_test_path = None +bless = None + +class CustomHTMLParser(HTMLParser): + """simplified HTML parser. + + this is possible because we are dealing with very regular HTML from + rustdoc; we only have to deal with i) void elements and ii) empty + attributes.""" + def __init__(self, target=None): + HTMLParser.__init__(self) + self.__builder = target or ET.TreeBuilder() + + def handle_starttag(self, tag, attrs): + attrs = {k: v or '' for k, v in attrs} + self.__builder.start(tag, attrs) + if tag in VOID_ELEMENTS: + self.__builder.end(tag) + + def handle_endtag(self, tag): + self.__builder.end(tag) + + def handle_startendtag(self, tag, attrs): + attrs = {k: v or '' for k, v in attrs} + self.__builder.start(tag, attrs) + self.__builder.end(tag) + + def handle_data(self, data): + self.__builder.data(data) + + def handle_entityref(self, name): + self.__builder.data(unichr(name2codepoint[name])) + + def handle_charref(self, name): + code = int(name[1:], 16) if name.startswith(('x', 'X')) else int(name, 10) + self.__builder.data(unichr(code)) + + def close(self): + HTMLParser.close(self) + return self.__builder.close() + + +Command = namedtuple('Command', 'negated cmd args lineno context') + + +class FailedCheck(Exception): + pass + + +class InvalidCheck(Exception): + pass + + +def concat_multi_lines(f): + """returns a generator out of the file object, which + - removes `\\` then `\n` then a shared prefix with the previous line then + optional whitespace; + - keeps a line number (starting from 0) of the first line being + concatenated.""" + lastline = None # set to the last line when the last line has a backslash + firstlineno = None + catenated = '' + for lineno, line in enumerate(f): + line = line.rstrip('\r\n') + + # strip the common prefix from the current line if needed + if lastline is not None: + common_prefix = os.path.commonprefix([line, lastline]) + line = line[len(common_prefix):].lstrip() + + firstlineno = firstlineno or lineno + if line.endswith('\\'): + if lastline is None: + lastline = line[:-1] + catenated += line[:-1] + else: + yield firstlineno, catenated + line + lastline = None + firstlineno = None + catenated = '' + + if lastline is not None: + print_err(lineno, line, 'Trailing backslash at the end of the file') + + +LINE_PATTERN = re.compile(r''' + (?<=(?<!\S))(?P<invalid>!?)@(?P<negated>!?) + (?P<cmd>[A-Za-z]+(?:-[A-Za-z]+)*) + (?P<args>.*)$ +''', re.X | re.UNICODE) + + +def get_commands(template): + with io.open(template, encoding='utf-8') as f: + for lineno, line in concat_multi_lines(f): + m = LINE_PATTERN.search(line) + if not m: + continue + + negated = (m.group('negated') == '!') + cmd = m.group('cmd') + if m.group('invalid') == '!': + print_err( + lineno, + line, + 'Invalid command: `!@{0}{1}`, (help: try with `@!{1}`)'.format( + '!' if negated else '', + cmd, + ), + ) + continue + args = m.group('args') + if args and not args[:1].isspace(): + print_err(lineno, line, 'Invalid template syntax') + continue + try: + args = shlex.split(args) + except UnicodeEncodeError: + args = [arg.decode('utf-8') for arg in shlex.split(args.encode('utf-8'))] + yield Command(negated=negated, cmd=cmd, args=args, lineno=lineno+1, context=line) + + +def _flatten(node, acc): + if node.text: + acc.append(node.text) + for e in node: + _flatten(e, acc) + if e.tail: + acc.append(e.tail) + + +def flatten(node): + acc = [] + _flatten(node, acc) + return ''.join(acc) + + +def make_xml(text): + xml = ET.XML('<xml>%s</xml>' % text) + return xml + + +def normalize_xpath(path): + path = path.replace("{{channel}}", channel) + if path.startswith('//'): + return '.' + path # avoid warnings + elif path.startswith('.//'): + return path + else: + raise InvalidCheck('Non-absolute XPath is not supported due to implementation issues') + + +class CachedFiles(object): + def __init__(self, root): + self.root = root + self.files = {} + self.trees = {} + self.last_path = None + + def resolve_path(self, path): + if path != '-': + path = os.path.normpath(path) + self.last_path = path + return path + elif self.last_path is None: + raise InvalidCheck('Tried to use the previous path in the first command') + else: + return self.last_path + + def get_file(self, path): + path = self.resolve_path(path) + if path in self.files: + return self.files[path] + + abspath = os.path.join(self.root, path) + if not(os.path.exists(abspath) and os.path.isfile(abspath)): + raise FailedCheck('File does not exist {!r}'.format(path)) + + with io.open(abspath, encoding='utf-8') as f: + data = f.read() + self.files[path] = data + return data + + def get_tree(self, path): + path = self.resolve_path(path) + if path in self.trees: + return self.trees[path] + + abspath = os.path.join(self.root, path) + if not(os.path.exists(abspath) and os.path.isfile(abspath)): + raise FailedCheck('File does not exist {!r}'.format(path)) + + with io.open(abspath, encoding='utf-8') as f: + try: + tree = ET.fromstringlist(f.readlines(), CustomHTMLParser()) + except Exception as e: + raise RuntimeError('Cannot parse an HTML file {!r}: {}'.format(path, e)) + self.trees[path] = tree + return self.trees[path] + + def get_dir(self, path): + path = self.resolve_path(path) + abspath = os.path.join(self.root, path) + if not(os.path.exists(abspath) and os.path.isdir(abspath)): + raise FailedCheck('Directory does not exist {!r}'.format(path)) + + +def check_string(data, pat, regexp): + pat = pat.replace("{{channel}}", channel) + if not pat: + return True # special case a presence testing + elif regexp: + return re.search(pat, data, flags=re.UNICODE) is not None + else: + data = ' '.join(data.split()) + pat = ' '.join(pat.split()) + return pat in data + + +def check_tree_attr(tree, path, attr, pat, regexp): + path = normalize_xpath(path) + ret = False + for e in tree.findall(path): + if attr in e.attrib: + value = e.attrib[attr] + else: + continue + + ret = check_string(value, pat, regexp) + if ret: + break + return ret + + +# Returns the number of occurences matching the regex (`regexp`) and the text (`pat`). +def check_tree_text(tree, path, pat, regexp, stop_at_first): + path = normalize_xpath(path) + match_count = 0 + try: + for e in tree.findall(path): + try: + value = flatten(e) + except KeyError: + continue + else: + if check_string(value, pat, regexp): + match_count += 1 + if stop_at_first: + break + except Exception: + print('Failed to get path "{}"'.format(path)) + raise + return match_count + + +def get_tree_count(tree, path): + path = normalize_xpath(path) + return len(tree.findall(path)) + + +def check_snapshot(snapshot_name, actual_tree, normalize_to_text): + assert rust_test_path.endswith('.rs') + snapshot_path = '{}.{}.{}'.format(rust_test_path[:-3], snapshot_name, 'html') + try: + with open(snapshot_path, 'r') as snapshot_file: + expected_str = snapshot_file.read().replace("{{channel}}", channel) + except FileNotFoundError: + if bless: + expected_str = None + else: + raise FailedCheck('No saved snapshot value') + + if not normalize_to_text: + actual_str = ET.tostring(actual_tree).decode('utf-8') + else: + actual_str = flatten(actual_tree) + + # Conditions: + # 1. Is --bless + # 2. Are actual and expected tree different + # 3. Are actual and expected text different + if not expected_str \ + or (not normalize_to_text and \ + not compare_tree(make_xml(actual_str), make_xml(expected_str), stderr)) \ + or (normalize_to_text and actual_str != expected_str): + + if bless: + with open(snapshot_path, 'w') as snapshot_file: + actual_str = actual_str.replace(channel, "{{channel}}") + snapshot_file.write(actual_str) + else: + print('--- expected ---\n') + print(expected_str) + print('\n\n--- actual ---\n') + print(actual_str) + print() + raise FailedCheck('Actual snapshot value is different than expected') + + +# Adapted from https://github.com/formencode/formencode/blob/3a1ba9de2fdd494dd945510a4568a3afeddb0b2e/formencode/doctest_xml_compare.py#L72-L120 +def compare_tree(x1, x2, reporter=None): + if x1.tag != x2.tag: + if reporter: + reporter('Tags do not match: %s and %s' % (x1.tag, x2.tag)) + return False + for name, value in x1.attrib.items(): + if x2.attrib.get(name) != value: + if reporter: + reporter('Attributes do not match: %s=%r, %s=%r' + % (name, value, name, x2.attrib.get(name))) + return False + for name in x2.attrib: + if name not in x1.attrib: + if reporter: + reporter('x2 has an attribute x1 is missing: %s' + % name) + return False + if not text_compare(x1.text, x2.text): + if reporter: + reporter('text: %r != %r' % (x1.text, x2.text)) + return False + if not text_compare(x1.tail, x2.tail): + if reporter: + reporter('tail: %r != %r' % (x1.tail, x2.tail)) + return False + cl1 = list(x1) + cl2 = list(x2) + if len(cl1) != len(cl2): + if reporter: + reporter('children length differs, %i != %i' + % (len(cl1), len(cl2))) + return False + i = 0 + for c1, c2 in zip(cl1, cl2): + i += 1 + if not compare_tree(c1, c2, reporter=reporter): + if reporter: + reporter('children %i do not match: %s' + % (i, c1.tag)) + return False + return True + + +def text_compare(t1, t2): + if not t1 and not t2: + return True + if t1 == '*' or t2 == '*': + return True + return (t1 or '').strip() == (t2 or '').strip() + + +def stderr(*args): + if sys.version_info.major < 3: + file = codecs.getwriter('utf-8')(sys.stderr) + else: + file = sys.stderr + + print(*args, file=file) + + +def print_err(lineno, context, err, message=None): + global ERR_COUNT + ERR_COUNT += 1 + stderr("{}: {}".format(lineno, message or err)) + if message and err: + stderr("\t{}".format(err)) + + if context: + stderr("\t{}".format(context)) + + +def get_nb_matching_elements(cache, c, regexp, stop_at_first): + tree = cache.get_tree(c.args[0]) + pat, sep, attr = c.args[1].partition('/@') + if sep: # attribute + tree = cache.get_tree(c.args[0]) + return check_tree_attr(tree, pat, attr, c.args[2], False) + else: # normalized text + pat = c.args[1] + if pat.endswith('/text()'): + pat = pat[:-7] + return check_tree_text(cache.get_tree(c.args[0]), pat, c.args[2], regexp, stop_at_first) + + +ERR_COUNT = 0 + + +def check_command(c, cache): + try: + cerr = "" + if c.cmd == 'has' or c.cmd == 'matches': # string test + regexp = (c.cmd == 'matches') + if len(c.args) == 1 and not regexp: # @has <path> = file existence + try: + cache.get_file(c.args[0]) + ret = True + except FailedCheck as err: + cerr = str(err) + ret = False + elif len(c.args) == 2: # @has/matches <path> <pat> = string test + cerr = "`PATTERN` did not match" + ret = check_string(cache.get_file(c.args[0]), c.args[1], regexp) + elif len(c.args) == 3: # @has/matches <path> <pat> <match> = XML tree test + cerr = "`XPATH PATTERN` did not match" + ret = get_nb_matching_elements(cache, c, regexp, True) != 0 + else: + raise InvalidCheck('Invalid number of @{} arguments'.format(c.cmd)) + + elif c.cmd == 'count': # count test + if len(c.args) == 3: # @count <path> <pat> <count> = count test + expected = int(c.args[2]) + found = get_tree_count(cache.get_tree(c.args[0]), c.args[1]) + cerr = "Expected {} occurrences but found {}".format(expected, found) + ret = expected == found + elif len(c.args) == 4: # @count <path> <pat> <text> <count> = count test + expected = int(c.args[3]) + found = get_nb_matching_elements(cache, c, False, False) + cerr = "Expected {} occurrences but found {}".format(expected, found) + ret = found == expected + else: + raise InvalidCheck('Invalid number of @{} arguments'.format(c.cmd)) + + elif c.cmd == 'snapshot': # snapshot test + if len(c.args) == 3: # @snapshot <snapshot-name> <html-path> <xpath> + [snapshot_name, html_path, pattern] = c.args + tree = cache.get_tree(html_path) + xpath = normalize_xpath(pattern) + normalize_to_text = False + if xpath.endswith('/text()'): + xpath = xpath[:-7] + normalize_to_text = True + + subtrees = tree.findall(xpath) + if len(subtrees) == 1: + [subtree] = subtrees + try: + check_snapshot(snapshot_name, subtree, normalize_to_text) + ret = True + except FailedCheck as err: + cerr = str(err) + ret = False + elif len(subtrees) == 0: + raise FailedCheck('XPATH did not match') + else: + raise FailedCheck('Expected 1 match, but found {}'.format(len(subtrees))) + else: + raise InvalidCheck('Invalid number of @{} arguments'.format(c.cmd)) + + elif c.cmd == 'has-dir': # has-dir test + if len(c.args) == 1: # @has-dir <path> = has-dir test + try: + cache.get_dir(c.args[0]) + ret = True + except FailedCheck as err: + cerr = str(err) + ret = False + else: + raise InvalidCheck('Invalid number of @{} arguments'.format(c.cmd)) + + elif c.cmd == 'valid-html': + raise InvalidCheck('Unimplemented @valid-html') + + elif c.cmd == 'valid-links': + raise InvalidCheck('Unimplemented @valid-links') + + else: + raise InvalidCheck('Unrecognized @{}'.format(c.cmd)) + + if ret == c.negated: + raise FailedCheck(cerr) + + except FailedCheck as err: + message = '@{}{} check failed'.format('!' if c.negated else '', c.cmd) + print_err(c.lineno, c.context, str(err), message) + except InvalidCheck as err: + print_err(c.lineno, c.context, str(err)) + + +def check(target, commands): + cache = CachedFiles(target) + for c in commands: + check_command(c, cache) + + +if __name__ == '__main__': + if len(sys.argv) not in [3, 4]: + stderr('Usage: {} <doc dir> <template> [--bless]'.format(sys.argv[0])) + raise SystemExit(1) + + rust_test_path = sys.argv[2] + if len(sys.argv) > 3 and sys.argv[3] == '--bless': + bless = True + else: + # We only support `--bless` at the end of the arguments. + # This assert is to prevent silent failures. + assert '--bless' not in sys.argv + bless = False + check(sys.argv[1], get_commands(rust_test_path)) + if ERR_COUNT: + stderr("\nEncountered {} errors".format(ERR_COUNT)) + raise SystemExit(1) diff --git a/src/etc/indenter b/src/etc/indenter new file mode 100755 index 000000000..21bfc448a --- /dev/null +++ b/src/etc/indenter @@ -0,0 +1,19 @@ +#!/usr/bin/env python +import re +import sys + +indent = 0 +more_re = re.compile(r"^rust: ~\">>") +less_re = re.compile(r"^rust: ~\"<<") +while True: + line = sys.stdin.readline() + if not line: + break + + if more_re.match(line): + indent += 1 + + print("%03d %s%s" % (indent, " " * indent, line.strip())) + + if less_re.match(line): + indent -= 1 diff --git a/src/etc/installer/README.md b/src/etc/installer/README.md new file mode 100644 index 000000000..cded3bbf7 --- /dev/null +++ b/src/etc/installer/README.md @@ -0,0 +1,28 @@ +# The Rust Programming Language + +This is a compiler for Rust, including standard libraries, tools and +documentation. Rust is a systems programming language that is fast, +memory safe and multithreaded, but does not employ a garbage collector +or otherwise impose significant runtime overhead. + +To install to /usr/local (the default), run the included `install.sh` script: + + $ sudo ./install.sh + +To uninstall: + + $ sudo /usr/local/lib/rustlib/uninstall.sh + +`install.sh` has a few options, including the possibility to set an installation +prefix. You can display these options by running: + + $ sudo ./install.sh --help + +Read [The Book](https://doc.rust-lang.org/book/index.html) to learn how +to use Rust. + +Rust is primarily distributed under the terms of both the MIT license +and the Apache License (Version 2.0), with portions covered by various +BSD-like licenses. + +See LICENSE-APACHE, LICENSE-MIT, and COPYRIGHT for details. diff --git a/src/etc/installer/gfx/banner.bmp b/src/etc/installer/gfx/banner.bmp Binary files differnew file mode 100644 index 000000000..b5459a797 --- /dev/null +++ b/src/etc/installer/gfx/banner.bmp diff --git a/src/etc/installer/gfx/banner.xcf b/src/etc/installer/gfx/banner.xcf Binary files differnew file mode 100644 index 000000000..53296518e --- /dev/null +++ b/src/etc/installer/gfx/banner.xcf diff --git a/src/etc/installer/gfx/dialogbg.bmp b/src/etc/installer/gfx/dialogbg.bmp Binary files differnew file mode 100644 index 000000000..7e4674a4f --- /dev/null +++ b/src/etc/installer/gfx/dialogbg.bmp diff --git a/src/etc/installer/gfx/dialogbg.xcf b/src/etc/installer/gfx/dialogbg.xcf Binary files differnew file mode 100644 index 000000000..49ca4e0c3 --- /dev/null +++ b/src/etc/installer/gfx/dialogbg.xcf diff --git a/src/etc/installer/gfx/rust-logo.ico b/src/etc/installer/gfx/rust-logo.ico Binary files differnew file mode 100644 index 000000000..a58225d5a --- /dev/null +++ b/src/etc/installer/gfx/rust-logo.ico diff --git a/src/etc/installer/gfx/rust-logo.png b/src/etc/installer/gfx/rust-logo.png Binary files differnew file mode 100644 index 000000000..99ee7507f --- /dev/null +++ b/src/etc/installer/gfx/rust-logo.png diff --git a/src/etc/installer/msi/remove-duplicates.xsl b/src/etc/installer/msi/remove-duplicates.xsl new file mode 100644 index 000000000..05b4c9bcc --- /dev/null +++ b/src/etc/installer/msi/remove-duplicates.xsl @@ -0,0 +1,24 @@ +<?xml version="1.0" ?> +<xsl:stylesheet version="1.0" + xmlns:xsl="http://www.w3.org/1999/XSL/Transform" + xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"> + <!-- Copy all attributes and elements to the output. --> + <xsl:template match="@*|*"> + <xsl:copy> + <xsl:apply-templates select="@*|*"/> + </xsl:copy> + </xsl:template> + <xsl:output method="xml" indent="yes" /> + + <!-- LICENSE* files are installed from rustc dir. --> + <xsl:key name="duplicates-cmp-ids" match="wix:Component[./wix:File[contains(@Source, 'LICENSE')]|./wix:File[contains(@Source, 'rust-installer-version')]]" use="@Id" /> + <xsl:template match="wix:Component[key('duplicates-cmp-ids', @Id)]" /> + <xsl:template match="wix:ComponentRef[key('duplicates-cmp-ids', @Id)]" /> + + <xsl:template match="wix:File[contains(@Source, 'README.md')]"> + <xsl:copy> + <xsl:apply-templates select="@*|*"/> + <xsl:attribute name="Name">README-CARGO.md</xsl:attribute> + </xsl:copy> + </xsl:template> +</xsl:stylesheet> diff --git a/src/etc/installer/msi/rust.wxs b/src/etc/installer/msi/rust.wxs new file mode 100644 index 000000000..a182bc406 --- /dev/null +++ b/src/etc/installer/msi/rust.wxs @@ -0,0 +1,293 @@ +<?xml version="1.0"?> +<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> + + <?if $(sys.BUILDARCH)="x64" ?> + <?define ArchSuffix=" 64-bit" ?> + <?else?> + <?define ArchSuffix="" ?> + <?endif?> + + <?if $(env.CFG_CHANNEL)="stable" ?> + <?define ProductName="Rust $(env.CFG_VER_MAJOR).$(env.CFG_VER_MINOR) ($(env.CFG_ABI)$(var.ArchSuffix))" ?> + <?else?> + <?define ProductName="Rust $(env.CFG_CHANNEL) $(env.CFG_VER_MAJOR).$(env.CFG_VER_MINOR) ($(env.CFG_ABI)$(var.ArchSuffix))" ?> + <?endif?> + + <?define BaseRegKey="Software\[Manufacturer]\Rust $(env.CFG_CHANNEL) ($(env.CFG_ABI)$(var.ArchSuffix))\$(env.CFG_VER_MAJOR).$(env.CFG_VER_MINOR)" ?> + + <!-- Upgrade code should be different for each platform --> + <?if $(sys.BUILDARCH)="x64" ?> + <?if $(env.CFG_ABI)="GNU" ?> + <!-- UpgradeCode should stay the same for all MSI versions in channel --> + <?if $(env.CFG_CHANNEL)="stable" ?> + <?define UpgradeCode="B440B077-F8D1-4730-8E1D-D6D37702B4CE" ?> + <?elseif $(env.CFG_CHANNEL)="beta" ?> + <?define UpgradeCode="7205CEDC-CDA6-4B62-8E4E-4D19EC5D88FC" ?> + <?elseif $(env.CFG_CHANNEL)="nightly" ?> + <?define UpgradeCode="622497D9-E0B1-448E-838A-4A33D0C5F82C" ?> + <?elseif $(env.CFG_CHANNEL)="dev" ?> + <?define UpgradeCode="7D32FD99-BB26-45CF-935D-1B0593BBDDBE" ?> + <?endif ?> + <?elseif $(env.CFG_ABI)="MSVC" ?> + <?if $(env.CFG_CHANNEL)="stable" ?> + <?define UpgradeCode="123039F9-68E3-44F1-AC9F-C78ADD4D0723" ?> + <?elseif $(env.CFG_CHANNEL)="beta" ?> + <?define UpgradeCode="ABC640B9-2AB5-4270-9A0D-E54E502A1CCA" ?> + <?elseif $(env.CFG_CHANNEL)="nightly" ?> + <?define UpgradeCode="56263F12-4AA1-4FE1-AFAE-572915C4FA3E" ?> + <?elseif $(env.CFG_CHANNEL)="dev" ?> + <?define UpgradeCode="231A9544-7E39-4A60-A069-0EB3CA4BAB2E" ?> + <?endif ?> + <?endif ?> + <?define PlatformProgramFilesFolder="ProgramFiles64Folder" ?> + <?elseif $(sys.BUILDARCH)="x86" ?> + <?if $(env.CFG_ABI)="GNU" ?> + <?if $(env.CFG_CHANNEL)="stable" ?> + <?define UpgradeCode="1C7CADA5-D117-43F8-A356-DF15F9FBEFF6" ?> + <?elseif $(env.CFG_CHANNEL)="beta" ?> + <?define UpgradeCode="5229EAC1-AB7C-4A62-9881-6FAD2DE7D0F9" ?> + <?elseif $(env.CFG_CHANNEL)="nightly" ?> + <?define UpgradeCode="B94FF1C2-2C7B-4859-A08B-546815516FDA" ?> + <?elseif $(env.CFG_CHANNEL)="dev" ?> + <?define UpgradeCode="7E6D1349-2773-4792-B8CD-EA2685D86A99" ?> + <?endif ?> + <?elseif $(env.CFG_ABI)="MSVC" ?> + <?if $(env.CFG_CHANNEL)="stable" ?> + <?define UpgradeCode="5805719C-45E9-4CF6-9CE7-1E8B57F3C243" ?> + <?elseif $(env.CFG_CHANNEL)="beta" ?> + <?define UpgradeCode="BC0731C1-BED1-424C-BE99-3589C35C84DE" ?> + <?elseif $(env.CFG_CHANNEL)="nightly" ?> + <?define UpgradeCode="FF193BBC-E73B-4FBD-ADE0-12F3CFC84145" ?> + <?elseif $(env.CFG_CHANNEL)="dev" ?> + <?define UpgradeCode="87DFC303-6492-4E9B-911E-56EAD56C5E58" ?> + <?endif ?> + <?endif ?> + <?define PlatformProgramFilesFolder="ProgramFilesFolder" ?> + <?else ?> + <?error Unsupported value of sys.BUILDARCH=$(sys.BUILDARCH)?> + <?endif ?> + + <Product Id="*" + Name="$(var.ProductName)" + Language="1033" + Version="$(env.CFG_VER_MAJOR).$(env.CFG_VER_MINOR).$(env.CFG_VER_PATCH).$(env.CFG_VER_BUILD)" + UpgradeCode="$(var.UpgradeCode)" + Manufacturer="The Rust Project Developers"> + <Package + Comments="Rust is a systems programming language that runs blazingly fast, prevents almost all crashes, and eliminates data races." + InstallerVersion="200" + InstallPrivileges="elevated" + Compressed="yes" /> + + <Icon Id="rust.ico" SourceFile="rust-logo.ico" /> + <Property Id="ApplicationFolderName" Value="Rust $(env.CFG_CHANNEL) $(env.CFG_ABI) $(env.CFG_VER_MAJOR).$(env.CFG_VER_MINOR)" /> + <Property Id="WixAppFolder" Value="WixPerMachineFolder" /> + <Property Id="ARPPRODUCTICON" Value="rust.ico" /> + <Property Id="ARPURLINFOABOUT" Value="https://www.rust-lang.org/" /> + <Property Id="ARPCOMMENTS" Value="$(env.CFG_RELEASE_INFO)" /> + <!-- This is a dual-mode package. https://docs.microsoft.com/en-us/windows/win32/msi/single-package-authoring --> + <Property Id="ALLUSERS" Value="2" Secure="yes" /> + <Property Id="MSIINSTALLPERUSER" Secure="yes" /> + <!-- The actual install location (initialized below) --> + <Property Id="INSTALLDIR" Secure="yes" /> + + <!-- Detect path(s) of a previous installation. --> + <Property Id="INSTALLDIR_USER"> + <RegistrySearch Id="InstallDir_User" Type="raw" Root="HKCU" Key="$(var.BaseRegKey)" Name="InstallDir" /> + </Property> + <Property Id="INSTALLDIR_MACHINE"> + <RegistrySearch Id="InstallDir_Mach" Type="raw" Root="HKLM" Key="$(var.BaseRegKey)" Name="InstallDir" /> + </Property> + + <!-- Set ALLUSERS to match the previous installation mode, otherwise FindRelatedProducts will ignore + the previous installation. If both INSTALLDIR_USER and INSTALLDIR_MACHINE are set, prefer the former. --> + <SetProperty Sequence="first" Before="FindRelatedProducts" + Id="ALLUSERS" Value="{}">INSTALLDIR_USER</SetProperty> + + <!-- Set default values if RegSearch found nothing, or if we not upgrading --> + <SetProperty Sequence="both" Before="SetINSTALLDIR1" + Id="INSTALLDIR_USER" Value="[LocalAppDataFolder]Programs\[ApplicationFolderName]">NOT INSTALLDIR_USER</SetProperty> + <SetProperty Sequence="both" Before="SetINSTALLDIR1" + Id="INSTALLDIR_MACHINE" Value="[$(var.PlatformProgramFilesFolder)][ApplicationFolderName]">NOT INSTALLDIR_MACHINE</SetProperty> + + <!-- Choose the default install location according to ALLUSERS (unless set from the command line) --> + <SetProperty Sequence="both" Action="SetINSTALLDIR1" Before="SetINSTALLDIR2" + Id="INSTALLDIR" Value="[INSTALLDIR_USER]">NOT INSTALLDIR AND NOT ALLUSERS</SetProperty> + <SetProperty Sequence="both" Action="SetINSTALLDIR2" Before="CostFinalize" + Id="INSTALLDIR" Value="[INSTALLDIR_MACHINE]">NOT INSTALLDIR AND ALLUSERS</SetProperty> + + <SetProperty Sequence="ui" Before="CostFinalize" + Id="WixAppFolder" Value="WixPerUserFolder">NOT ALLUSERS</SetProperty> + + <!-- UI sets ALLUSERS per user selection; progagate this choice to MSIINSTALLPERUSER before executing installation actions --> + <SetProperty Sequence="ui" Before="ExecuteAction" + Id="MSIINSTALLPERUSER" Value="1">NOT ALLUSERS</SetProperty> + + <!-- Update ARPINSTALLLOCATION to match INSTALLDIR --> + <SetProperty Sequence="execute" Before="CostFinalize" + Id="ARPINSTALLLOCATION" Value="[INSTALLDIR]" /> + + <!-- Path of cmd.exe for the shortcut --> + <Property Id="SHORTCUTTARGET" Value="%windir%\System32\cmd.exe" /> + <!-- Microsoft Installer will resolve any Environment Variables in the working directory at install time --> + <Property Id="SHORTCUTWKDIR" Value="%SystemDrive%\" /> + + <InstallUISequence> + <FindRelatedProducts After="AppSearch" /> + </InstallUISequence> + <InstallExecuteSequence> + <FindRelatedProducts After="AppSearch" /> + <RemoveExistingProducts Before="InstallInitialize" /> + </InstallExecuteSequence> + + <Upgrade Id="$(var.UpgradeCode)"> + <UpgradeVersion + Minimum="$(env.CFG_VER_MAJOR).$(env.CFG_VER_MINOR).0" + Maximum="$(env.CFG_VER_MAJOR).$(env.CFG_VER_MINOR).65535" + IncludeMinimum="yes" + IncludeMaximum="yes" + MigrateFeatures="yes" + Property="UPGRADE_DETECTED" + /> + </Upgrade> + + <!-- Specifies a single cab file to be embedded in the installer's .msi. --> + <MediaTemplate EmbedCab="yes" CompressionLevel="mszip" /> + + <!-- Send a WM_SETTINGCHANGE message to tell processes like explorer to update their + environments so any new command prompts get the updated %PATH% --> + <CustomActionRef Id="WixBroadcastEnvironmentChange" /> + + <!-- Installation directory and files are defined in Files.wxs --> + <Directory Id="TARGETDIR" Name="SourceDir"> + <Directory Id="$(var.PlatformProgramFilesFolder)"> + <Directory Id="INSTALLDIR" Name="Rust"> + <!-- Root directories for every feature should have different IDs for correct work of heat.exe --> + <Directory Id="Rustc" Name="." /> + <?if $(env.CFG_MINGW)="1" ?> + <Directory Id="Gcc" Name="." /> + <?endif?> + <Directory Id="Docs" Name="." /> + <Directory Id="Cargo" Name="." /> + <Directory Id="Std" Name="." /> + <!-- tool-rls-start --> + <Directory Id="Rls" Name="." /> + <Directory Id="Analysis" Name="." /> + <!-- tool-rls-end --> + </Directory> + </Directory> + + <!-- Record our install location --> + <Component Id="InstallDir" Guid="*"> + <RegistryValue Root="HKMU" Key="$(var.BaseRegKey)" + Type="string" + Name="InstallDir" + Value="[INSTALLDIR]" /> + </Component> + + <!-- Add $/bin to PATH --> + <Component Id="PathEnvPerMachine" Guid="*"> + <Condition>ALLUSERS=1 OR (ALLUSERS=2 AND Privileged)</Condition> + <RegistryValue Root="HKMU" Key="$(var.BaseRegKey)" Name="PathEnvPerMachine" Type="string" Value="1" KeyPath="yes" /> + <!-- [INSTALLDIR] contains trailing backslash --> + <Environment Id="PathPerMachine" Name="PATH" Value="[INSTALLDIR]bin" Permanent="no" Part="last" Action="set" System="yes" /> + </Component> + <Component Id="PathEnvPerUser" Guid="*"> + <Condition>ALLUSERS="" OR (ALLUSERS=2 AND (NOT Privileged))</Condition> + <RegistryValue Root="HKMU" Key="$(var.BaseRegKey)" Name="PathEnvPerUser" Type="string" Value="1" KeyPath="yes" /> + <Environment Id="PathPerUser" Name="PATH" Value="[INSTALLDIR]bin" Permanent="no" Part="last" Action="set" System="no" /> + </Component> + + <!-- Start Menu shortcuts --> + <Directory Id="ProgramMenuFolder"> + <Directory Id="ApplicationProgramsFolder" Name="Rust"> + <Component Id="RustShellShortcut" Guid="*"> + <Shortcut Id="RustShell" + Name="$(var.ProductName) Shell" + Description="Opens Command Prompt with Rust tools directory added to the PATH" + Target="[SHORTCUTTARGET]" + Arguments="/K path [INSTALLDIR]bin;%PATH%" + WorkingDirectory="SHORTCUTWKDIR"> + <Icon Id="rust2.ico" SourceFile="rust-logo.ico" /> + </Shortcut> + <RegistryValue Root="HKMU" Key="$(var.BaseRegKey)" Name="RustShell" Type="integer" Value="1" KeyPath="yes" /> + <RemoveFolder Id="ApplicationProgramsFolder1" On="uninstall" /> + </Component> + <Component Id="DocIndexShortcut" Guid="*"> + <Shortcut Id="RustDocs" + Name="$(var.ProductName) Documentation" + Description="Opens Rust HTML documentation in the default browser" + Target="[INSTALLDIR]share\doc\rust\html\index.html" /> + <RegistryValue Root="HKMU" Key="$(var.BaseRegKey)" Name="RustDocs" Type="integer" Value="1" KeyPath="yes" /> + <RemoveFolder Id="ApplicationProgramsFolder2" On="uninstall" /> + </Component> + </Directory> + </Directory> + + </Directory> + + <Feature Id="Rustc" + Title="Rust compiler and standard crates" + Display="1" + Level="1" + Absent="disallow" + AllowAdvertise="no"> + <ComponentGroupRef Id="RustcGroup" /> + <ComponentRef Id="RustShellShortcut" /> + <ComponentRef Id="InstallDir" /> + </Feature> + <Feature Id="Std" + Title="The Rust standard library" + Display="2" + Level="1" + AllowAdvertise="no"> + <ComponentGroupRef Id="StdGroup" /> + </Feature> + <Feature Id="Cargo" + Title="Cargo, the Rust package manager" + Display="3" + Level="1" + AllowAdvertise="no"> + <ComponentGroupRef Id="CargoGroup" /> + </Feature> + <?if $(env.CFG_MINGW)="1" ?> + <Feature Id="Gcc" + Title="Linker and platform libraries" + Description="If you choose to not install this component, you will require an external MinGW installation in order to create executables and libraries." + Display="4" + Level="1" + AllowAdvertise="no"> + <ComponentGroupRef Id="GccGroup" /> + </Feature> + <?endif?> + <Feature Id="Docs" + Title="HTML documentation" + Display="5" + Level="1" + AllowAdvertise="no"> + <ComponentGroupRef Id="DocsGroup" /> + <ComponentRef Id="DocIndexShortcut" /> + </Feature> + <Feature Id="Path" + Title="Add to PATH" + Description="Add Rust to PATH environment variable" + Display="6" + Level="1" + AllowAdvertise="no"> + <ComponentRef Id="PathEnvPerMachine" /> + <ComponentRef Id="PathEnvPerUser" /> + </Feature> + <!-- tool-rls-start --> + <Feature Id="RLS" + Title="RLS, the Rust Language Server" + Display="7" + Level="2" + AllowAdvertise="no"> + <ComponentGroupRef Id="RlsGroup" /> + <ComponentGroupRef Id="AnalysisGroup" /> + </Feature> + <!-- tool-rls-end --> + + <UIRef Id="RustUI" /> + </Product> +</Wix> diff --git a/src/etc/installer/msi/rustwelcomedlg.wxs b/src/etc/installer/msi/rustwelcomedlg.wxs new file mode 100644 index 000000000..0ee5415ff --- /dev/null +++ b/src/etc/installer/msi/rustwelcomedlg.wxs @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> + <Fragment> + <UI> + <Dialog Id="RustWelcomeDlg" Width="370" Height="270" Title="!(loc.AdvancedWelcomeEulaDlg_Title)"> + <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.AdvancedWelcomeEulaDlgBannerBitmap)" /> + <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" /> + <Control Id="Title" Type="Text" X="20" Y="10" Width="300" Height="24" Transparent="yes" NoPrefix="yes" Text="!(loc.AdvancedWelcomeEulaDlgTitle)" /> + <Control Id="DescriptionPerMachine" Type="Text" X="20" Y="182" Width="330" Height="31" Transparent="yes" NoPrefix="yes" Hidden="yes" Text="!(loc.AdvancedWelcomeEulaDlgDescriptionPerMachine)"> + <Condition Action="show">NOT UPGRADE_DETECTED AND ALLUSERS</Condition> + </Control> + <Control Id="DescriptionPerUser" Type="Text" X="20" Y="182" Width="330" Height="31" Transparent="yes" NoPrefix="yes" Hidden="yes" Text="!(loc.AdvancedWelcomeEulaDlgDescriptionPerUser)"> + <Condition Action="show">NOT UPGRADE_DETECTED AND NOT ALLUSERS</Condition> + </Control> + <Control Id="DescriptionUpgrade" Type="Text" X="20" Y="182" Width="330" Height="31" Transparent="yes" NoPrefix="yes" Hidden="yes" + Text="Click Install to upgrade the existing version of [ProductName]. Click Advanced to change installation options."> + <Condition Action="show">UPGRADE_DETECTED</Condition> + </Control> + <Control Id="TargetPath" Type="Text" X="20" Y="212" Width="330" Height="31" Transparent="yes" NoPrefix="yes" Hidden="no" + Text="Install Directory: [INSTALLDIR]"> + </Control> + <Control Id="Print" Type="PushButton" X="88" Y="243" Width="56" Height="17" Text="!(loc.WixUIPrint)"> + <Publish Event="DoAction" Value="WixUIPrintEula">1</Publish> + </Control> + <Control Id="Advanced" Type="PushButton" X="156" Y="243" Width="56" Height="17" Text="!(loc.AdvancedWelcomeEulaDlgAdvanced)" /> + <Control Id="Install" Type="PushButton" ElevationShield="yes" X="212" Y="243" Width="80" Height="17" Default="yes" Text="!(loc.AdvancedWelcomeEulaDlgInstall)" Hidden="yes"> + <Publish Event="SpawnWaitDialog" Value="WaitForCostingDlg">!(wix.WixUICostingPopupOptOut) OR CostingComplete = 1</Publish> + <Publish Event="EndDialog" Value="Return"><![CDATA[OutOfDiskSpace <> 1]]></Publish> + <Publish Event="SpawnDialog" Value="OutOfRbDiskDlg">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND (PROMPTROLLBACKCOST="P" OR NOT PROMPTROLLBACKCOST)</Publish> + <Publish Event="EndDialog" Value="Return">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"</Publish> + <Publish Event="EnableRollback" Value="False">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"</Publish> + <Publish Event="SpawnDialog" Value="OutOfDiskDlg">(OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 1) OR (OutOfDiskSpace = 1 AND PROMPTROLLBACKCOST="F")</Publish> + <Condition Action="show">ALLUSERS</Condition> + </Control> + <Control Id="InstallNoShield" Type="PushButton" ElevationShield="no" X="212" Y="243" Width="80" Height="17" Default="yes" Text="!(loc.AdvancedWelcomeEulaDlgInstall)" Hidden="yes"> + <Publish Event="SpawnWaitDialog" Value="WaitForCostingDlg">!(wix.WixUICostingPopupOptOut) OR CostingComplete = 1</Publish> + <Publish Event="EndDialog" Value="Return"><![CDATA[OutOfDiskSpace <> 1]]></Publish> + <Publish Event="SpawnDialog" Value="OutOfRbDiskDlg">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND (PROMPTROLLBACKCOST="P" OR NOT PROMPTROLLBACKCOST)</Publish> + <Publish Event="EndDialog" Value="Return">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"</Publish> + <Publish Event="EnableRollback" Value="False">OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"</Publish> + <Publish Event="SpawnDialog" Value="OutOfDiskDlg">(OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 1) OR (OutOfDiskSpace = 1 AND PROMPTROLLBACKCOST="F")</Publish> + <Condition Action="show">NOT ALLUSERS</Condition> + </Control> + <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)"> + <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish> + </Control> + <Control Id="LicenseText" Type="ScrollableText" X="20" Y="55" Width="330" Height="121" Sunken="yes" TabSkip="no"> + <Text SourceFile="!(wix.WixUILicenseRtf)" /> + </Control> + </Dialog> + </UI> + + <InstallUISequence> + <Show Dialog="RustWelcomeDlg" Before="ProgressDlg">NOT Installed</Show> + </InstallUISequence> + </Fragment> +</Wix> diff --git a/src/etc/installer/msi/squash-components.xsl b/src/etc/installer/msi/squash-components.xsl new file mode 100644 index 000000000..17b4e0388 --- /dev/null +++ b/src/etc/installer/msi/squash-components.xsl @@ -0,0 +1,34 @@ +<?xml version="1.0" ?> +<xsl:stylesheet version="1.0" + xmlns:xsl="http://www.w3.org/1999/XSL/Transform" + xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"> + <!-- Copy all attributes and elements to the output. --> + <xsl:template match="@*|*"> + <xsl:copy> + <xsl:apply-templates select="@*|*"/> + </xsl:copy> + </xsl:template> + <xsl:output method="xml" indent="yes" /> + + <!-- Move all files in directory into first component in that directory. --> + <xsl:template match="wix:Component[1]"> + <xsl:copy> + <xsl:apply-templates select="@*|*"/> + <xsl:for-each select="../wix:Component[preceding-sibling::*]/wix:File"> + <xsl:copy> + <!-- Component can only have one KeyPath --> + <xsl:apply-templates select="@*[not(name()='KeyPath')]|*"/> + </xsl:copy> + </xsl:for-each> + </xsl:copy> + </xsl:template> + + <!-- Now the rest of components are empty, find them. --> + <xsl:key name="empty-cmp-ids" match="wix:Component[preceding-sibling::*]" use="@Id" /> + + <!-- And remove. --> + <xsl:template match="wix:Component[preceding-sibling::*]" /> + + <!-- Also remove componentsrefs referencing empty components. --> + <xsl:template match="wix:ComponentRef[key('empty-cmp-ids', @Id)]" /> +</xsl:stylesheet> diff --git a/src/etc/installer/msi/ui.wxs b/src/etc/installer/msi/ui.wxs new file mode 100644 index 000000000..3e2db6051 --- /dev/null +++ b/src/etc/installer/msi/ui.wxs @@ -0,0 +1,83 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Based on WixUI_Advanced +--> + +<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> + <Fragment> + <WixVariable Id="WixUISupportPerUser" Value="1" Overridable="yes" /> + <WixVariable Id="WixUISupportPerMachine" Value="1" Overridable="yes" /> + <WixVariable Id="WixUILicenseRtf" Value="LICENSE.rtf" /> + <WixVariable Id="WixUIDialogBmp" Value="dialogbg.bmp" /> + <WixVariable Id="WixUIBannerBmp" Value="banner.bmp" /> + + <UI Id="RustUI"> + <TextStyle Id="WixUI_Font_Normal" FaceName="!(loc.Advanced_Font_FaceName)" Size="!(loc.Advanced_Font_Normal_Size)" /> + <TextStyle Id="WixUI_Font_Bigger" FaceName="!(loc.Advanced_Font_FaceName)" Size="!(loc.Advanced_Font_Bigger_Size)" /> + <TextStyle Id="WixUI_Font_Title" FaceName="!(loc.Advanced_Font_FaceName)" Size="!(loc.Advanced_Font_Title_Size)" Bold="yes" /> + <TextStyle Id="WixUI_Font_Emphasized" FaceName="!(loc.Advanced_Font_FaceName)" Size="!(loc.Advanced_Font_Emphasized_Size)" Bold="yes" /> + + <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" /> + <Property Id="WixUI_Mode" Value="Advanced" /> + + <DialogRef Id="BrowseDlg" /> + <DialogRef Id="DiskCostDlg" /> + <DialogRef Id="ErrorDlg" /> + <DialogRef Id="FatalError" /> + <DialogRef Id="FilesInUse" /> + <DialogRef Id="MsiRMFilesInUse" /> + <DialogRef Id="PrepareDlg" /> + <DialogRef Id="ProgressDlg" /> + <DialogRef Id="ResumeDlg" /> + <DialogRef Id="UserExit" /> + <DialogRef Id="WelcomeDlg"/> + + <Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish> + + <Publish Dialog="BrowseDlg" Control="OK" Event="DoAction" Value="WixUIValidatePath" Order="1">1</Publish> + <Publish Dialog="BrowseDlg" Control="OK" Event="SpawnDialog" Value="InvalidDirDlg" Order="2"><![CDATA[WIXUI_INSTALLDIR_VALID<>"1"]]></Publish> + + <Publish Dialog="RustWelcomeDlg" Control="Advanced" Event="NewDialog" Value="InstallScopeDlg" Order="1" /> + + <Publish Dialog="InstallScopeDlg" Control="Back" Event="NewDialog" Value="RustWelcomeDlg">1</Publish> + <!-- override default WixAppFolder of WixPerMachineFolder as standard user won't be shown the radio group to set WixAppFolder --> + <Publish Dialog="InstallScopeDlg" Control="Next" Property="WixAppFolder" Value="WixPerUserFolder" Order="1">!(wix.WixUISupportPerUser) AND NOT Privileged</Publish> + <Publish Dialog="InstallScopeDlg" Control="Next" Property="ALLUSERS" Value="{}" Order="2">WixAppFolder = "WixPerUserFolder"</Publish> + <Publish Dialog="InstallScopeDlg" Control="Next" Property="ALLUSERS" Value="1" Order="3">WixAppFolder = "WixPerMachineFolder"</Publish> + <Publish Dialog="InstallScopeDlg" Control="Next" Property="INSTALLDIR" Value="[INSTALLDIR_USER]" Order="4">WixAppFolder = "WixPerUserFolder"</Publish> + <Publish Dialog="InstallScopeDlg" Control="Next" Property="INSTALLDIR" Value="[INSTALLDIR_MACHINE]" Order="5">WixAppFolder = "WixPerMachineFolder"</Publish> + <Publish Dialog="InstallScopeDlg" Control="Next" Event="NewDialog" Value="InstallDirDlg" Order="6">1</Publish> + + <Publish Dialog="InstallDirDlg" Control="Back" Event="NewDialog" Value="InstallScopeDlg" /> + <Publish Dialog="InstallDirDlg" Control="Next" Event="SetTargetPath" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish> + <Publish Dialog="InstallDirDlg" Control="Next" Event="DoAction" Value="WixUIValidatePath" Order="2">NOT WIXUI_DONTVALIDATEPATH</Publish> + <Publish Dialog="InstallDirDlg" Control="Next" Event="SpawnDialog" Value="InvalidDirDlg" Order="3"><![CDATA[NOT WIXUI_DONTVALIDATEPATH AND WIXUI_INSTALLDIR_VALID<>"1"]]></Publish> + <Publish Dialog="InstallDirDlg" Control="Next" Event="NewDialog" Value="FeaturesDlg" Order="4">WIXUI_DONTVALIDATEPATH OR WIXUI_INSTALLDIR_VALID="1"</Publish> + <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Property="_BrowseProperty" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish> + <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish> + + <Publish Dialog="FeaturesDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg">NOT Installed AND WixAppFolder = "WixPerUserFolder"</Publish> + <Publish Dialog="FeaturesDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg">NOT Installed AND WixAppFolder = "WixPerMachineFolder"</Publish> + <Publish Dialog="FeaturesDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg">Installed</Publish> + + <Publish Dialog="MaintenanceWelcomeDlg" Control="Next" Event="NewDialog" Value="MaintenanceTypeDlg">1</Publish> + + <Publish Dialog="MaintenanceTypeDlg" Control="ChangeButton" Event="NewDialog" Value="FeaturesDlg">1</Publish> + <Publish Dialog="MaintenanceTypeDlg" Control="RepairButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish> + <Publish Dialog="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish> + <Publish Dialog="MaintenanceTypeDlg" Control="Back" Event="NewDialog" Value="MaintenanceWelcomeDlg">1</Publish> + + <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="2">Installed AND NOT PATCH</Publish> + <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="3">Installed AND PATCH</Publish> + + <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">Installed AND PATCH</Publish> + </UI> + + <InstallUISequence> + <Show Dialog="WelcomeDlg" Before="RustWelcomeDlg" >Installed AND PATCH</Show> + </InstallUISequence> + + <Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR" /> + <UIRef Id="WixUI_Common" /> + </Fragment> +</Wix> diff --git a/src/etc/installer/pkg/Distribution.xml b/src/etc/installer/pkg/Distribution.xml new file mode 100644 index 000000000..077ee1751 --- /dev/null +++ b/src/etc/installer/pkg/Distribution.xml @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="utf-8" standalone="no"?> +<installer-gui-script minSpecVersion="2"> + <title>The Rust Compiler</title> + <license file="LICENSE.txt" mime-type="text/plain"/> + <pkg-ref id="org.rust-lang.rust"/> + <options customize="always" require-scripts="false" hostArchitectures="i386,x86_64"/> + <domains enable_anywhere="false" enable_currentUserHome="false" enable_localSystem="true" /> + <volume-check> + <allowed-os-versions> + <os-version min="10.7"/> + </allowed-os-versions> + </volume-check> + <choices-outline> + <line choice="install"> + <line choice="rustc"/> + <line choice="rust-std"/> + <line choice="cargo"/> + <line choice="rust-docs"/> + <!-- tool-rls-start --> + <line choice="rls"/> + <!-- tool-rls-end --> + </line> + <line choice="uninstall" /> + </choices-outline> + <!-- + These 'selected' scripts ensure that install and uninstall can never be selected at + the same time. Exectly how they work is pretty mysterious, tied to the unspecified algorithm + the installer uses to traverse the options after one is toggled. + --> + <choice id="install" visible="true" + title="Install Rust" description="Install the Rust compiler, package manager and documentation." + customLocation="/usr/local" + selected="!choices.uninstall.selected" + /> + <choice id="uninstall" visible="true" + title="Uninstall Rust" description="Select this option to uninstall an existing Rust installation." + customLocation="/usr/local" + selected="!(choices.install.selected || choices.rustc.selected || choices.cargo.selected || choices['rust-docs'].selected)" + start_selected="false" + > + <pkg-ref id="org.rust-lang.uninstall"/> + </choice> + <choice id="rustc" visible="true" + title="Compiler" description="rustc, the Rust compiler, and rustdoc, the API documentation tool." + selected="(!choices.uninstall.selected && choices.rustc.selected) || (choices.uninstall.selected && choices.install.selected)" + > + <pkg-ref id="org.rust-lang.rustc"/> + </choice> + <choice id="cargo" visible="true" + title="Cargo" description="cargo, the Rust package manager." + selected="(!choices.uninstall.selected && choices.cargo.selected) || (choices.uninstall.selected && choices.install.selected)" + > + <pkg-ref id="org.rust-lang.cargo"/> + </choice> + <choice id="rust-std" visible="true" + title="Standard Library" description="The Rust standard library." + selected="(!choices.uninstall.selected && choices['rust-std'].selected) || (choices.uninstall.selected && choices.install.selected)" + > + <pkg-ref id="org.rust-lang.rust-std"/> + </choice> + <choice id="rust-docs" visible="true" + title="Documentation" description="HTML documentation." + selected="(!choices.uninstall.selected && choices['rust-docs'].selected) || (choices.uninstall.selected && choices.install.selected)" + > + <pkg-ref id="org.rust-lang.rust-docs"/> + </choice> + <!-- tool-rls-start --> + <choice id="rls" visible="true" + title="RLS" description="RLS, the Rust Language Server" + selected="(!choices.uninstall.selected && choices['rls'].selected) || (choices.uninstall.selected && choices.install.selected)" + start_selected="false" + > + <pkg-ref id="org.rust-lang.rls"/> + <pkg-ref id="org.rust-lang.rust-analysis"/> + </choice> + <!-- tool-rls-end --> + <pkg-ref id="org.rust-lang.rustc" version="0" onConclusion="none">rustc.pkg</pkg-ref> + <pkg-ref id="org.rust-lang.cargo" version="0" onConclusion="none">cargo.pkg</pkg-ref> + <pkg-ref id="org.rust-lang.rust-docs" version="0" onConclusion="none">rust-docs.pkg</pkg-ref> + <pkg-ref id="org.rust-lang.rust-std" version="0" onConclusion="none">rust-std.pkg</pkg-ref> + <!-- tool-rls-start --> + <pkg-ref id="org.rust-lang.rls" version="0" onConclusion="none">rls.pkg</pkg-ref> + <!-- tool-rls-end --> + <pkg-ref id="org.rust-lang.rust-analysis" version="0" onConclusion="none">rust-analysis.pkg</pkg-ref> + <pkg-ref id="org.rust-lang.uninstall" version="0" onConclusion="none">uninstall.pkg</pkg-ref> + <background file="rust-logo.png" mime-type="image/png" + alignment="bottomleft"/> +</installer-gui-script> diff --git a/src/etc/installer/pkg/postinstall b/src/etc/installer/pkg/postinstall new file mode 100755 index 000000000..fb035a486 --- /dev/null +++ b/src/etc/installer/pkg/postinstall @@ -0,0 +1,26 @@ +#!/bin/sh + +source_dir="$(dirname "$0")" +dest_dir="$2" +package_id="$INSTALL_PKG_SESSION_ID" + +if [ -z "$source_dir" ]; then + exit 1 +fi +if [ -z "$dest_dir" ]; then + exit 1 +fi +if [ -z "$package_id" ]; then + exit 1 +fi + +if [ "$package_id" = "org.rust-lang.uninstall" ]; then + if [ ! -e "$dest_dir/lib/rustlib/uninstall.sh" ]; then + exit 1 + fi + sh "$dest_dir/lib/rustlib/uninstall.sh" +else + sh "$source_dir/install.sh" --prefix="$dest_dir" +fi + +exit 0 diff --git a/src/etc/lldb_batchmode.py b/src/etc/lldb_batchmode.py new file mode 100644 index 000000000..fc355c87b --- /dev/null +++ b/src/etc/lldb_batchmode.py @@ -0,0 +1,225 @@ +# This script allows to use LLDB in a way similar to GDB's batch mode. That is, given a text file +# containing LLDB commands (one command per line), this script will execute the commands one after +# the other. +# LLDB also has the -s and -S commandline options which also execute a list of commands from a text +# file. However, this command are execute `immediately`: the command of a `run` or `continue` +# command will be executed immediately after the `run` or `continue`, without waiting for the next +# breakpoint to be hit. This a command sequence like the following will not yield reliable results: +# +# break 11 +# run +# print x +# +# Most of the time the `print` command will be executed while the program is still running will thus +# fail. Using this Python script, the above will work as expected. + +from __future__ import print_function +import lldb +import os +import sys +import threading +import re +import time + +try: + import thread +except ModuleNotFoundError: + # The `thread` module was renamed to `_thread` in Python 3. + import _thread as thread + +# Set this to True for additional output +DEBUG_OUTPUT = True + + +def print_debug(s): + """Print something if DEBUG_OUTPUT is True""" + global DEBUG_OUTPUT + if DEBUG_OUTPUT: + print("DEBUG: " + str(s)) + + +def normalize_whitespace(s): + """Replace newlines, tabs, multiple spaces, etc with exactly one space""" + return re.sub("\s+", " ", s) + + +def breakpoint_callback(frame, bp_loc, dict): + """This callback is registered with every breakpoint and makes sure that the + frame containing the breakpoint location is selected """ + + # HACK(eddyb) print a newline to avoid continuing an unfinished line. + print("") + print("Hit breakpoint " + str(bp_loc)) + + # Select the frame and the thread containing it + frame.thread.process.SetSelectedThread(frame.thread) + frame.thread.SetSelectedFrame(frame.idx) + + # Returning True means that we actually want to stop at this breakpoint + return True + + +# This is a list of breakpoints that are not registered with the breakpoint callback. The list is +# populated by the breakpoint listener and checked/emptied whenever a command has been executed +new_breakpoints = [] + +# This set contains all breakpoint ids that have already been registered with a callback, and is +# used to avoid hooking callbacks into breakpoints more than once +registered_breakpoints = set() + + +def execute_command(command_interpreter, command): + """Executes a single CLI command""" + global new_breakpoints + global registered_breakpoints + + res = lldb.SBCommandReturnObject() + print(command) + command_interpreter.HandleCommand(command, res) + + if res.Succeeded(): + if res.HasResult(): + print(normalize_whitespace(res.GetOutput() or ''), end='\n') + + # If the command introduced any breakpoints, make sure to register + # them with the breakpoint + # callback + while len(new_breakpoints) > 0: + res.Clear() + breakpoint_id = new_breakpoints.pop() + + if breakpoint_id in registered_breakpoints: + print_debug("breakpoint with id %s is already registered. Ignoring." % + str(breakpoint_id)) + else: + print_debug("registering breakpoint callback, id = " + str(breakpoint_id)) + callback_command = ("breakpoint command add -F breakpoint_callback " + + str(breakpoint_id)) + command_interpreter.HandleCommand(callback_command, res) + if res.Succeeded(): + print_debug("successfully registered breakpoint callback, id = " + + str(breakpoint_id)) + registered_breakpoints.add(breakpoint_id) + else: + print("Error while trying to register breakpoint callback, id = " + + str(breakpoint_id) + ", message = " + str(res.GetError())) + else: + print(res.GetError()) + + +def start_breakpoint_listener(target): + """Listens for breakpoints being added and adds new ones to the callback + registration list""" + listener = lldb.SBListener("breakpoint listener") + + def listen(): + event = lldb.SBEvent() + try: + while True: + if listener.WaitForEvent(120, event): + if lldb.SBBreakpoint.EventIsBreakpointEvent(event) and \ + lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent(event) == \ + lldb.eBreakpointEventTypeAdded: + global new_breakpoints + breakpoint = lldb.SBBreakpoint.GetBreakpointFromEvent(event) + print_debug("breakpoint added, id = " + str(breakpoint.id)) + new_breakpoints.append(breakpoint.id) + except: + print_debug("breakpoint listener shutting down") + + # Start the listener and let it run as a daemon + listener_thread = threading.Thread(target=listen) + listener_thread.daemon = True + listener_thread.start() + + # Register the listener with the target + target.GetBroadcaster().AddListener(listener, lldb.SBTarget.eBroadcastBitBreakpointChanged) + + +def start_watchdog(): + """Starts a watchdog thread that will terminate the process after a certain + period of time""" + + try: + from time import clock + except ImportError: + from time import perf_counter as clock + + watchdog_start_time = clock() + watchdog_max_time = watchdog_start_time + 30 + + def watchdog(): + while clock() < watchdog_max_time: + time.sleep(1) + print("TIMEOUT: lldb_batchmode.py has been running for too long. Aborting!") + thread.interrupt_main() + + # Start the listener and let it run as a daemon + watchdog_thread = threading.Thread(target=watchdog) + watchdog_thread.daemon = True + watchdog_thread.start() + +#################################################################################################### +# ~main +#################################################################################################### + + +if len(sys.argv) != 3: + print("usage: python lldb_batchmode.py target-path script-path") + sys.exit(1) + +target_path = sys.argv[1] +script_path = sys.argv[2] + +print("LLDB batch-mode script") +print("----------------------") +print("Debugger commands script is '%s'." % script_path) +print("Target executable is '%s'." % target_path) +print("Current working directory is '%s'" % os.getcwd()) + +# Start the timeout watchdog +start_watchdog() + +# Create a new debugger instance +debugger = lldb.SBDebugger.Create() + +# When we step or continue, don't return from the function until the process +# stops. We do this by setting the async mode to false. +debugger.SetAsync(False) + +# Create a target from a file and arch +print("Creating a target for '%s'" % target_path) +target_error = lldb.SBError() +target = debugger.CreateTarget(target_path, None, None, True, target_error) + +if not target: + print("Could not create debugging target '" + target_path + "': " + + str(target_error) + ". Aborting.", file=sys.stderr) + sys.exit(1) + + +# Register the breakpoint callback for every breakpoint +start_breakpoint_listener(target) + +command_interpreter = debugger.GetCommandInterpreter() + +try: + script_file = open(script_path, 'r') + + for line in script_file: + command = line.strip() + if command == "run" or command == "r" or re.match("^process\s+launch.*", command): + # Before starting to run the program, let the thread sleep a bit, so all + # breakpoint added events can be processed + time.sleep(0.5) + if command != '': + execute_command(command_interpreter, command) + +except IOError as e: + print("Could not read debugging script '%s'." % script_path, file=sys.stderr) + print(e, file=sys.stderr) + print("Aborting.", file=sys.stderr) + sys.exit(1) +finally: + debugger.Terminate() + script_file.close() diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands new file mode 100644 index 000000000..4a1204ccc --- /dev/null +++ b/src/etc/lldb_commands @@ -0,0 +1,18 @@ +type synthetic add -l lldb_lookup.synthetic_lookup -x ".*" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?str$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?\\[.+\\]$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::ffi::([a-z_]+::)+)OsString$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Vec<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)VecDeque<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)BTreeSet<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)BTreeMap<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::collections::([a-z_]+::)+)HashMap<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::collections::([a-z_]+::)+)HashSet<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Rc<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Arc<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)Cell<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)Ref<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)RefMut<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)RefCell<.+>$" --category Rust +type category enable Rust diff --git a/src/etc/lldb_lookup.py b/src/etc/lldb_lookup.py new file mode 100644 index 000000000..3cee51982 --- /dev/null +++ b/src/etc/lldb_lookup.py @@ -0,0 +1,115 @@ +import lldb + +from lldb_providers import * +from rust_types import RustType, classify_struct, classify_union + + +# BACKCOMPAT: rust 1.35 +def is_hashbrown_hashmap(hash_map): + return len(hash_map.type.fields) == 1 + + +def classify_rust_type(type): + type_class = type.GetTypeClass() + if type_class == lldb.eTypeClassStruct: + return classify_struct(type.name, type.fields) + if type_class == lldb.eTypeClassUnion: + return classify_union(type.fields) + + return RustType.OTHER + + +def summary_lookup(valobj, dict): + # type: (SBValue, dict) -> str + """Returns the summary provider for the given value""" + rust_type = classify_rust_type(valobj.GetType()) + + if rust_type == RustType.STD_STRING: + return StdStringSummaryProvider(valobj, dict) + if rust_type == RustType.STD_OS_STRING: + return StdOsStringSummaryProvider(valobj, dict) + if rust_type == RustType.STD_STR: + return StdStrSummaryProvider(valobj, dict) + + if rust_type == RustType.STD_VEC: + return SizeSummaryProvider(valobj, dict) + if rust_type == RustType.STD_VEC_DEQUE: + return SizeSummaryProvider(valobj, dict) + if rust_type == RustType.STD_SLICE: + return SizeSummaryProvider(valobj, dict) + + if rust_type == RustType.STD_HASH_MAP: + return SizeSummaryProvider(valobj, dict) + if rust_type == RustType.STD_HASH_SET: + return SizeSummaryProvider(valobj, dict) + + if rust_type == RustType.STD_RC: + return StdRcSummaryProvider(valobj, dict) + if rust_type == RustType.STD_ARC: + return StdRcSummaryProvider(valobj, dict) + + if rust_type == RustType.STD_REF: + return StdRefSummaryProvider(valobj, dict) + if rust_type == RustType.STD_REF_MUT: + return StdRefSummaryProvider(valobj, dict) + if rust_type == RustType.STD_REF_CELL: + return StdRefSummaryProvider(valobj, dict) + + return "" + + +def synthetic_lookup(valobj, dict): + # type: (SBValue, dict) -> object + """Returns the synthetic provider for the given value""" + rust_type = classify_rust_type(valobj.GetType()) + + if rust_type == RustType.STRUCT: + return StructSyntheticProvider(valobj, dict) + if rust_type == RustType.STRUCT_VARIANT: + return StructSyntheticProvider(valobj, dict, is_variant=True) + if rust_type == RustType.TUPLE: + return TupleSyntheticProvider(valobj, dict) + if rust_type == RustType.TUPLE_VARIANT: + return TupleSyntheticProvider(valobj, dict, is_variant=True) + if rust_type == RustType.EMPTY: + return EmptySyntheticProvider(valobj, dict) + if rust_type == RustType.REGULAR_ENUM: + discriminant = valobj.GetChildAtIndex(0).GetChildAtIndex(0).GetValueAsUnsigned() + return synthetic_lookup(valobj.GetChildAtIndex(discriminant), dict) + if rust_type == RustType.SINGLETON_ENUM: + return synthetic_lookup(valobj.GetChildAtIndex(0), dict) + + if rust_type == RustType.STD_VEC: + return StdVecSyntheticProvider(valobj, dict) + if rust_type == RustType.STD_VEC_DEQUE: + return StdVecDequeSyntheticProvider(valobj, dict) + if rust_type == RustType.STD_SLICE: + return StdSliceSyntheticProvider(valobj, dict) + + if rust_type == RustType.STD_HASH_MAP: + if is_hashbrown_hashmap(valobj): + return StdHashMapSyntheticProvider(valobj, dict) + else: + return StdOldHashMapSyntheticProvider(valobj, dict) + if rust_type == RustType.STD_HASH_SET: + hash_map = valobj.GetChildAtIndex(0) + if is_hashbrown_hashmap(hash_map): + return StdHashMapSyntheticProvider(valobj, dict, show_values=False) + else: + return StdOldHashMapSyntheticProvider(hash_map, dict, show_values=False) + + if rust_type == RustType.STD_RC: + return StdRcSyntheticProvider(valobj, dict) + if rust_type == RustType.STD_ARC: + return StdRcSyntheticProvider(valobj, dict, is_atomic=True) + + if rust_type == RustType.STD_CELL: + return StdCellSyntheticProvider(valobj, dict) + if rust_type == RustType.STD_REF: + return StdRefSyntheticProvider(valobj, dict) + if rust_type == RustType.STD_REF_MUT: + return StdRefSyntheticProvider(valobj, dict) + if rust_type == RustType.STD_REF_CELL: + return StdRefSyntheticProvider(valobj, dict, is_cell=True) + + return DefaultSynthteticProvider(valobj, dict) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py new file mode 100644 index 000000000..35ac07f0d --- /dev/null +++ b/src/etc/lldb_providers.py @@ -0,0 +1,741 @@ +import sys + +from lldb import SBValue, SBData, SBError, eBasicTypeLong, eBasicTypeUnsignedLong, \ + eBasicTypeUnsignedChar + +# from lldb.formatters import Logger + +#################################################################################################### +# This file contains two kinds of pretty-printers: summary and synthetic. +# +# Important classes from LLDB module: +# SBValue: the value of a variable, a register, or an expression +# SBType: the data type; each SBValue has a corresponding SBType +# +# Summary provider is a function with the type `(SBValue, dict) -> str`. +# The first parameter is the object encapsulating the actual variable being displayed; +# The second parameter is an internal support parameter used by LLDB, and you should not touch it. +# +# Synthetic children is the way to provide a children-based representation of the object's value. +# Synthetic provider is a class that implements the following interface: +# +# class SyntheticChildrenProvider: +# def __init__(self, SBValue, dict) +# def num_children(self) +# def get_child_index(self, str) +# def get_child_at_index(self, int) +# def update(self) +# def has_children(self) +# def get_value(self) +# +# +# You can find more information and examples here: +# 1. https://lldb.llvm.org/varformats.html +# 2. https://lldb.llvm.org/python-reference.html +# 3. https://lldb.llvm.org/python_reference/lldb.formatters.cpp.libcxx-pysrc.html +# 4. https://github.com/llvm-mirror/lldb/tree/master/examples/summaries/cocoa +#################################################################################################### + +PY3 = sys.version_info[0] == 3 + + +class ValueBuilder: + def __init__(self, valobj): + # type: (SBValue) -> ValueBuilder + self.valobj = valobj + process = valobj.GetProcess() + self.endianness = process.GetByteOrder() + self.pointer_size = process.GetAddressByteSize() + + def from_int(self, name, value): + # type: (str, int) -> SBValue + type = self.valobj.GetType().GetBasicType(eBasicTypeLong) + data = SBData.CreateDataFromSInt64Array(self.endianness, self.pointer_size, [value]) + return self.valobj.CreateValueFromData(name, data, type) + + def from_uint(self, name, value): + # type: (str, int) -> SBValue + type = self.valobj.GetType().GetBasicType(eBasicTypeUnsignedLong) + data = SBData.CreateDataFromUInt64Array(self.endianness, self.pointer_size, [value]) + return self.valobj.CreateValueFromData(name, data, type) + + +def unwrap_unique_or_non_null(unique_or_nonnull): + # BACKCOMPAT: rust 1.32 + # https://github.com/rust-lang/rust/commit/7a0911528058e87d22ea305695f4047572c5e067 + # BACKCOMPAT: rust 1.60 + # https://github.com/rust-lang/rust/commit/2a91eeac1a2d27dd3de1bf55515d765da20fd86f + ptr = unique_or_nonnull.GetChildMemberWithName("pointer") + return ptr if ptr.TypeIsPointerType() else ptr.GetChildAtIndex(0) + + +class DefaultSynthteticProvider: + def __init__(self, valobj, dict): + # type: (SBValue, dict) -> DefaultSynthteticProvider + # logger = Logger.Logger() + # logger >> "Default synthetic provider for " + str(valobj.GetName()) + self.valobj = valobj + + def num_children(self): + # type: () -> int + return self.valobj.GetNumChildren() + + def get_child_index(self, name): + # type: (str) -> int + return self.valobj.GetIndexOfChildWithName(name) + + def get_child_at_index(self, index): + # type: (int) -> SBValue + return self.valobj.GetChildAtIndex(index) + + def update(self): + # type: () -> None + pass + + def has_children(self): + # type: () -> bool + return self.valobj.MightHaveChildren() + + +class EmptySyntheticProvider: + def __init__(self, valobj, dict): + # type: (SBValue, dict) -> EmptySyntheticProvider + # logger = Logger.Logger() + # logger >> "[EmptySyntheticProvider] for " + str(valobj.GetName()) + self.valobj = valobj + + def num_children(self): + # type: () -> int + return 0 + + def get_child_index(self, name): + # type: (str) -> int + return None + + def get_child_at_index(self, index): + # type: (int) -> SBValue + return None + + def update(self): + # type: () -> None + pass + + def has_children(self): + # type: () -> bool + return False + + +def SizeSummaryProvider(valobj, dict): + # type: (SBValue, dict) -> str + return 'size=' + str(valobj.GetNumChildren()) + + +def vec_to_string(vec): + length = vec.GetNumChildren() + chars = [vec.GetChildAtIndex(i).GetValueAsUnsigned() for i in range(length)] + return bytes(chars).decode(errors='replace') if PY3 else "".join(chr(char) for char in chars) + + +def StdStringSummaryProvider(valobj, dict): + # type: (SBValue, dict) -> str + # logger = Logger.Logger() + # logger >> "[StdStringSummaryProvider] for " + str(valobj.GetName()) + vec = valobj.GetChildAtIndex(0) + return '"%s"' % vec_to_string(vec) + + +def StdOsStringSummaryProvider(valobj, dict): + # type: (SBValue, dict) -> str + # logger = Logger.Logger() + # logger >> "[StdOsStringSummaryProvider] for " + str(valobj.GetName()) + buf = valobj.GetChildAtIndex(0).GetChildAtIndex(0) + is_windows = "Wtf8Buf" in buf.type.name + vec = buf.GetChildAtIndex(0) if is_windows else buf + return '"%s"' % vec_to_string(vec) + + +def StdStrSummaryProvider(valobj, dict): + # type: (SBValue, dict) -> str + # logger = Logger.Logger() + # logger >> "[StdStrSummaryProvider] for " + str(valobj.GetName()) + + length = valobj.GetChildMemberWithName("length").GetValueAsUnsigned() + if length == 0: + return '""' + + data_ptr = valobj.GetChildMemberWithName("data_ptr") + + start = data_ptr.GetValueAsUnsigned() + error = SBError() + process = data_ptr.GetProcess() + data = process.ReadMemory(start, length, error) + data = data.decode(encoding='UTF-8') if PY3 else data + return '"%s"' % data + + +class StructSyntheticProvider: + """Pretty-printer for structs and struct enum variants""" + + def __init__(self, valobj, dict, is_variant=False): + # type: (SBValue, dict, bool) -> StructSyntheticProvider + # logger = Logger.Logger() + self.valobj = valobj + self.is_variant = is_variant + self.type = valobj.GetType() + self.fields = {} + + if is_variant: + self.fields_count = self.type.GetNumberOfFields() - 1 + real_fields = self.type.fields[1:] + else: + self.fields_count = self.type.GetNumberOfFields() + real_fields = self.type.fields + + for number, field in enumerate(real_fields): + self.fields[field.name] = number + + def num_children(self): + # type: () -> int + return self.fields_count + + def get_child_index(self, name): + # type: (str) -> int + return self.fields.get(name, -1) + + def get_child_at_index(self, index): + # type: (int) -> SBValue + if self.is_variant: + field = self.type.GetFieldAtIndex(index + 1) + else: + field = self.type.GetFieldAtIndex(index) + return self.valobj.GetChildMemberWithName(field.name) + + def update(self): + # type: () -> None + pass + + def has_children(self): + # type: () -> bool + return True + + +class TupleSyntheticProvider: + """Pretty-printer for tuples and tuple enum variants""" + + def __init__(self, valobj, dict, is_variant=False): + # type: (SBValue, dict, bool) -> TupleSyntheticProvider + # logger = Logger.Logger() + self.valobj = valobj + self.is_variant = is_variant + self.type = valobj.GetType() + + if is_variant: + self.size = self.type.GetNumberOfFields() - 1 + else: + self.size = self.type.GetNumberOfFields() + + def num_children(self): + # type: () -> int + return self.size + + def get_child_index(self, name): + # type: (str) -> int + if name.isdigit(): + return int(name) + else: + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + if self.is_variant: + field = self.type.GetFieldAtIndex(index + 1) + else: + field = self.type.GetFieldAtIndex(index) + element = self.valobj.GetChildMemberWithName(field.name) + return self.valobj.CreateValueFromData(str(index), element.GetData(), element.GetType()) + + def update(self): + # type: () -> None + pass + + def has_children(self): + # type: () -> bool + return True + + +class StdVecSyntheticProvider: + """Pretty-printer for alloc::vec::Vec<T> + + struct Vec<T> { buf: RawVec<T>, len: usize } + struct RawVec<T> { ptr: Unique<T>, cap: usize, ... } + rust 1.31.1: struct Unique<T: ?Sized> { pointer: NonZero<*const T>, ... } + rust 1.33.0: struct Unique<T: ?Sized> { pointer: *const T, ... } + rust 1.62.0: struct Unique<T: ?Sized> { pointer: NonNull<T>, ... } + struct NonZero<T>(T) + struct NonNull<T> { pointer: *const T } + """ + + def __init__(self, valobj, dict): + # type: (SBValue, dict) -> StdVecSyntheticProvider + # logger = Logger.Logger() + # logger >> "[StdVecSyntheticProvider] for " + str(valobj.GetName()) + self.valobj = valobj + self.update() + + def num_children(self): + # type: () -> int + return self.length + + def get_child_index(self, name): + # type: (str) -> int + index = name.lstrip('[').rstrip(']') + if index.isdigit(): + return int(index) + else: + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + start = self.data_ptr.GetValueAsUnsigned() + address = start + index * self.element_type_size + element = self.data_ptr.CreateValueFromAddress("[%s]" % index, address, self.element_type) + return element + + def update(self): + # type: () -> None + self.length = self.valobj.GetChildMemberWithName("len").GetValueAsUnsigned() + self.buf = self.valobj.GetChildMemberWithName("buf") + + self.data_ptr = unwrap_unique_or_non_null(self.buf.GetChildMemberWithName("ptr")) + + self.element_type = self.data_ptr.GetType().GetPointeeType() + self.element_type_size = self.element_type.GetByteSize() + + def has_children(self): + # type: () -> bool + return True + + +class StdSliceSyntheticProvider: + def __init__(self, valobj, dict): + self.valobj = valobj + self.update() + + def num_children(self): + # type: () -> int + return self.length + + def get_child_index(self, name): + # type: (str) -> int + index = name.lstrip('[').rstrip(']') + if index.isdigit(): + return int(index) + else: + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + start = self.data_ptr.GetValueAsUnsigned() + address = start + index * self.element_type_size + element = self.data_ptr.CreateValueFromAddress("[%s]" % index, address, self.element_type) + return element + + def update(self): + # type: () -> None + self.length = self.valobj.GetChildMemberWithName("length").GetValueAsUnsigned() + self.data_ptr = self.valobj.GetChildMemberWithName("data_ptr") + + self.element_type = self.data_ptr.GetType().GetPointeeType() + self.element_type_size = self.element_type.GetByteSize() + + def has_children(self): + # type: () -> bool + return True + + +class StdVecDequeSyntheticProvider: + """Pretty-printer for alloc::collections::vec_deque::VecDeque<T> + + struct VecDeque<T> { tail: usize, head: usize, buf: RawVec<T> } + """ + + def __init__(self, valobj, dict): + # type: (SBValue, dict) -> StdVecDequeSyntheticProvider + # logger = Logger.Logger() + # logger >> "[StdVecDequeSyntheticProvider] for " + str(valobj.GetName()) + self.valobj = valobj + self.update() + + def num_children(self): + # type: () -> int + return self.size + + def get_child_index(self, name): + # type: (str) -> int + index = name.lstrip('[').rstrip(']') + if index.isdigit() and self.tail <= index and (self.tail + index) % self.cap < self.head: + return int(index) + else: + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + start = self.data_ptr.GetValueAsUnsigned() + address = start + ((index + self.tail) % self.cap) * self.element_type_size + element = self.data_ptr.CreateValueFromAddress("[%s]" % index, address, self.element_type) + return element + + def update(self): + # type: () -> None + self.head = self.valobj.GetChildMemberWithName("head").GetValueAsUnsigned() + self.tail = self.valobj.GetChildMemberWithName("tail").GetValueAsUnsigned() + self.buf = self.valobj.GetChildMemberWithName("buf") + self.cap = self.buf.GetChildMemberWithName("cap").GetValueAsUnsigned() + if self.head >= self.tail: + self.size = self.head - self.tail + else: + self.size = self.cap + self.head - self.tail + + self.data_ptr = unwrap_unique_or_non_null(self.buf.GetChildMemberWithName("ptr")) + + self.element_type = self.data_ptr.GetType().GetPointeeType() + self.element_type_size = self.element_type.GetByteSize() + + def has_children(self): + # type: () -> bool + return True + + +# BACKCOMPAT: rust 1.35 +class StdOldHashMapSyntheticProvider: + """Pretty-printer for std::collections::hash::map::HashMap<K, V, S> + + struct HashMap<K, V, S> {..., table: RawTable<K, V>, ... } + struct RawTable<K, V> { capacity_mask: usize, size: usize, hashes: TaggedHashUintPtr, ... } + """ + + def __init__(self, valobj, dict, show_values=True): + # type: (SBValue, dict, bool) -> StdOldHashMapSyntheticProvider + self.valobj = valobj + self.show_values = show_values + self.update() + + def num_children(self): + # type: () -> int + return self.size + + def get_child_index(self, name): + # type: (str) -> int + index = name.lstrip('[').rstrip(']') + if index.isdigit(): + return int(index) + else: + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + # logger = Logger.Logger() + start = self.data_ptr.GetValueAsUnsigned() & ~1 + + # See `libstd/collections/hash/table.rs:raw_bucket_at + hashes = self.hash_uint_size * self.capacity + align = self.pair_type_size + # See `libcore/alloc.rs:padding_needed_for` + len_rounded_up = (((((hashes + align) % self.modulo - 1) % self.modulo) & ~( + (align - 1) % self.modulo)) % self.modulo - hashes) % self.modulo + # len_rounded_up = ((hashes + align - 1) & ~(align - 1)) - hashes + + pairs_offset = hashes + len_rounded_up + pairs_start = start + pairs_offset + + table_index = self.valid_indices[index] + idx = table_index & self.capacity_mask + address = pairs_start + idx * self.pair_type_size + element = self.data_ptr.CreateValueFromAddress("[%s]" % index, address, self.pair_type) + if self.show_values: + return element + else: + key = element.GetChildAtIndex(0) + return self.valobj.CreateValueFromData("[%s]" % index, key.GetData(), key.GetType()) + + def update(self): + # type: () -> None + # logger = Logger.Logger() + + self.table = self.valobj.GetChildMemberWithName("table") # type: SBValue + self.size = self.table.GetChildMemberWithName("size").GetValueAsUnsigned() + self.hashes = self.table.GetChildMemberWithName("hashes") + self.hash_uint_type = self.hashes.GetType() + self.hash_uint_size = self.hashes.GetType().GetByteSize() + self.modulo = 2 ** self.hash_uint_size + self.data_ptr = self.hashes.GetChildAtIndex(0).GetChildAtIndex(0) + + self.capacity_mask = self.table.GetChildMemberWithName("capacity_mask").GetValueAsUnsigned() + self.capacity = (self.capacity_mask + 1) % self.modulo + + marker = self.table.GetChildMemberWithName("marker").GetType() # type: SBType + self.pair_type = marker.template_args[0] + self.pair_type_size = self.pair_type.GetByteSize() + + self.valid_indices = [] + for idx in range(self.capacity): + address = self.data_ptr.GetValueAsUnsigned() + idx * self.hash_uint_size + hash_uint = self.data_ptr.CreateValueFromAddress("[%s]" % idx, address, + self.hash_uint_type) + hash_ptr = hash_uint.GetChildAtIndex(0).GetChildAtIndex(0) + if hash_ptr.GetValueAsUnsigned() != 0: + self.valid_indices.append(idx) + + # logger >> "Valid indices: {}".format(str(self.valid_indices)) + + def has_children(self): + # type: () -> bool + return True + + +class StdHashMapSyntheticProvider: + """Pretty-printer for hashbrown's HashMap""" + + def __init__(self, valobj, dict, show_values=True): + # type: (SBValue, dict, bool) -> StdHashMapSyntheticProvider + self.valobj = valobj + self.show_values = show_values + self.update() + + def num_children(self): + # type: () -> int + return self.size + + def get_child_index(self, name): + # type: (str) -> int + index = name.lstrip('[').rstrip(']') + if index.isdigit(): + return int(index) + else: + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + pairs_start = self.data_ptr.GetValueAsUnsigned() + idx = self.valid_indices[index] + if self.new_layout: + idx = -(idx + 1) + address = pairs_start + idx * self.pair_type_size + element = self.data_ptr.CreateValueFromAddress("[%s]" % index, address, self.pair_type) + if self.show_values: + return element + else: + key = element.GetChildAtIndex(0) + return self.valobj.CreateValueFromData("[%s]" % index, key.GetData(), key.GetType()) + + def update(self): + # type: () -> None + table = self.table() + inner_table = table.GetChildMemberWithName("table") + + capacity = inner_table.GetChildMemberWithName("bucket_mask").GetValueAsUnsigned() + 1 + ctrl = inner_table.GetChildMemberWithName("ctrl").GetChildAtIndex(0) + + self.size = inner_table.GetChildMemberWithName("items").GetValueAsUnsigned() + self.pair_type = table.type.template_args[0] + if self.pair_type.IsTypedefType(): + self.pair_type = self.pair_type.GetTypedefedType() + self.pair_type_size = self.pair_type.GetByteSize() + + self.new_layout = not inner_table.GetChildMemberWithName("data").IsValid() + if self.new_layout: + self.data_ptr = ctrl.Cast(self.pair_type.GetPointerType()) + else: + self.data_ptr = inner_table.GetChildMemberWithName("data").GetChildAtIndex(0) + + u8_type = self.valobj.GetTarget().GetBasicType(eBasicTypeUnsignedChar) + u8_type_size = self.valobj.GetTarget().GetBasicType(eBasicTypeUnsignedChar).GetByteSize() + + self.valid_indices = [] + for idx in range(capacity): + address = ctrl.GetValueAsUnsigned() + idx * u8_type_size + value = ctrl.CreateValueFromAddress("ctrl[%s]" % idx, address, + u8_type).GetValueAsUnsigned() + is_present = value & 128 == 0 + if is_present: + self.valid_indices.append(idx) + + def table(self): + # type: () -> SBValue + if self.show_values: + hashbrown_hashmap = self.valobj.GetChildMemberWithName("base") + else: + # BACKCOMPAT: rust 1.47 + # HashSet wraps either std HashMap or hashbrown::HashSet, which both + # wrap hashbrown::HashMap, so either way we "unwrap" twice. + hashbrown_hashmap = self.valobj.GetChildAtIndex(0).GetChildAtIndex(0) + return hashbrown_hashmap.GetChildMemberWithName("table") + + def has_children(self): + # type: () -> bool + return True + + +def StdRcSummaryProvider(valobj, dict): + # type: (SBValue, dict) -> str + strong = valobj.GetChildMemberWithName("strong").GetValueAsUnsigned() + weak = valobj.GetChildMemberWithName("weak").GetValueAsUnsigned() + return "strong={}, weak={}".format(strong, weak) + + +class StdRcSyntheticProvider: + """Pretty-printer for alloc::rc::Rc<T> and alloc::sync::Arc<T> + + struct Rc<T> { ptr: NonNull<RcBox<T>>, ... } + rust 1.31.1: struct NonNull<T> { pointer: NonZero<*const T> } + rust 1.33.0: struct NonNull<T> { pointer: *const T } + struct NonZero<T>(T) + struct RcBox<T> { strong: Cell<usize>, weak: Cell<usize>, value: T } + struct Cell<T> { value: UnsafeCell<T> } + struct UnsafeCell<T> { value: T } + + struct Arc<T> { ptr: NonNull<ArcInner<T>>, ... } + struct ArcInner<T> { strong: atomic::AtomicUsize, weak: atomic::AtomicUsize, data: T } + struct AtomicUsize { v: UnsafeCell<usize> } + """ + + def __init__(self, valobj, dict, is_atomic=False): + # type: (SBValue, dict, bool) -> StdRcSyntheticProvider + self.valobj = valobj + + self.ptr = unwrap_unique_or_non_null(self.valobj.GetChildMemberWithName("ptr")) + + self.value = self.ptr.GetChildMemberWithName("data" if is_atomic else "value") + + self.strong = self.ptr.GetChildMemberWithName("strong").GetChildAtIndex( + 0).GetChildMemberWithName("value") + self.weak = self.ptr.GetChildMemberWithName("weak").GetChildAtIndex( + 0).GetChildMemberWithName("value") + + self.value_builder = ValueBuilder(valobj) + + self.update() + + def num_children(self): + # type: () -> int + # Actually there are 3 children, but only the `value` should be shown as a child + return 1 + + def get_child_index(self, name): + # type: (str) -> int + if name == "value": + return 0 + if name == "strong": + return 1 + if name == "weak": + return 2 + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + if index == 0: + return self.value + if index == 1: + return self.value_builder.from_uint("strong", self.strong_count) + if index == 2: + return self.value_builder.from_uint("weak", self.weak_count) + + return None + + def update(self): + # type: () -> None + self.strong_count = self.strong.GetValueAsUnsigned() + self.weak_count = self.weak.GetValueAsUnsigned() - 1 + + def has_children(self): + # type: () -> bool + return True + + +class StdCellSyntheticProvider: + """Pretty-printer for std::cell::Cell""" + + def __init__(self, valobj, dict): + # type: (SBValue, dict) -> StdCellSyntheticProvider + self.valobj = valobj + self.value = valobj.GetChildMemberWithName("value").GetChildAtIndex(0) + + def num_children(self): + # type: () -> int + return 1 + + def get_child_index(self, name): + # type: (str) -> int + if name == "value": + return 0 + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + if index == 0: + return self.value + return None + + def update(self): + # type: () -> None + pass + + def has_children(self): + # type: () -> bool + return True + + +def StdRefSummaryProvider(valobj, dict): + # type: (SBValue, dict) -> str + borrow = valobj.GetChildMemberWithName("borrow").GetValueAsSigned() + return "borrow={}".format(borrow) if borrow >= 0 else "borrow_mut={}".format(-borrow) + + +class StdRefSyntheticProvider: + """Pretty-printer for std::cell::Ref, std::cell::RefMut, and std::cell::RefCell""" + + def __init__(self, valobj, dict, is_cell=False): + # type: (SBValue, dict, bool) -> StdRefSyntheticProvider + self.valobj = valobj + + borrow = valobj.GetChildMemberWithName("borrow") + value = valobj.GetChildMemberWithName("value") + if is_cell: + self.borrow = borrow.GetChildMemberWithName("value").GetChildMemberWithName("value") + self.value = value.GetChildMemberWithName("value") + else: + self.borrow = borrow.GetChildMemberWithName("borrow").GetChildMemberWithName( + "value").GetChildMemberWithName("value") + self.value = value.Dereference() + + self.value_builder = ValueBuilder(valobj) + + self.update() + + def num_children(self): + # type: () -> int + # Actually there are 2 children, but only the `value` should be shown as a child + return 1 + + def get_child_index(self, name): + if name == "value": + return 0 + if name == "borrow": + return 1 + return -1 + + def get_child_at_index(self, index): + # type: (int) -> SBValue + if index == 0: + return self.value + if index == 1: + return self.value_builder.from_int("borrow", self.borrow_count) + return None + + def update(self): + # type: () -> None + self.borrow_count = self.borrow.GetValueAsSigned() + + def has_children(self): + # type: () -> bool + return True diff --git a/src/etc/natvis/intrinsic.natvis b/src/etc/natvis/intrinsic.natvis new file mode 100644 index 000000000..558536fa6 --- /dev/null +++ b/src/etc/natvis/intrinsic.natvis @@ -0,0 +1,225 @@ +<?xml version="1.0" encoding="utf-8"?> +<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> + <Type Name="str"> + <DisplayString>{(char*)data_ptr,[length]s8}</DisplayString> + <StringView>(char*)data_ptr,[length]s8</StringView> + <Expand> + <Item Name="[len]" ExcludeView="simple">length</Item> + <Synthetic Name="[chars]"> + <Expand> + <ArrayItems> + <Size>length</Size> + <ValuePointer>data_ptr</ValuePointer> + </ArrayItems> + </Expand> + </Synthetic> + </Expand> + </Type> + <Type Name="slice$<*>"> + <DisplayString>{{ len={length} }}</DisplayString> + <Expand> + <Item Name="[len]" ExcludeView="simple">length</Item> + <ArrayItems> + <Size>length</Size> + <ValuePointer>data_ptr</ValuePointer> + </ArrayItems> + </Expand> + </Type> + <Type Name="tuple$<>"> + <DisplayString>()</DisplayString> + </Type> + <Type Name="tuple$<*>"> + <DisplayString>({__0})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*>"> + <DisplayString>({__0}, {__1})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*>"> + <DisplayString>({__0}, {__1}, {__2})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3}, {__4})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + <Item Name="[4]">__4</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3}, {__4}, {__5})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + <Item Name="[4]">__4</Item> + <Item Name="[5]">__5</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3}, {__4}, {__5}, {__6})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + <Item Name="[4]">__4</Item> + <Item Name="[5]">__5</Item> + <Item Name="[6]">__6</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*,*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3}, {__4}, {__5}, {__6}, {__7})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + <Item Name="[4]">__4</Item> + <Item Name="[5]">__5</Item> + <Item Name="[6]">__6</Item> + <Item Name="[7]">__7</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*,*,*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3}, {__4}, {__5}, {__6}, {__7}, {__8})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + <Item Name="[4]">__4</Item> + <Item Name="[5]">__5</Item> + <Item Name="[6]">__6</Item> + <Item Name="[7]">__7</Item> + <Item Name="[8]">__8</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*,*,*,*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3}, {__4}, {__5}, {__6}, {__7}, {__8}, {__9})</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + <Item Name="[4]">__4</Item> + <Item Name="[5]">__5</Item> + <Item Name="[6]">__6</Item> + <Item Name="[7]">__7</Item> + <Item Name="[8]">__8</Item> + <Item Name="[9]">__9</Item> + </Expand> + </Type> + <Type Name="tuple$<*,*,*,*,*,*,*,*,*,*,*>"> + <DisplayString>({__0}, {__1}, {__2}, {__3}, {__4}, {__5}, {__6}, {__7}, {__8}, {__9}, ...)</DisplayString> + <Expand> + <Item Name="[0]">__0</Item> + <Item Name="[1]">__1</Item> + <Item Name="[2]">__2</Item> + <Item Name="[3]">__3</Item> + <Item Name="[4]">__4</Item> + <Item Name="[5]">__5</Item> + <Item Name="[6]">__6</Item> + <Item Name="[7]">__7</Item> + <Item Name="[8]">__8</Item> + <Item Name="[9]">__9</Item> + <Synthetic Name="[...]"><DisplayString>...</DisplayString></Synthetic> + </Expand> + </Type> + + <!-- Directly tagged enums. $T1 is the type name --> + <Type Name="enum$<*>"> + <Intrinsic Name="tag" Expression="discriminant" /> + <DisplayString Condition="tag() == 0">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 1" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 2" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 3" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 4" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 5" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 6" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 7" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 8" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 9" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 10" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 11" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 12" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 13" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 14" Optional="true">{tag(),en}</DisplayString> + <DisplayString Condition="tag() == 15" Optional="true">{tag(),en}</DisplayString> + + <Expand> + <Synthetic Name="[variant]"> + <DisplayString>{tag(),en}</DisplayString> + </Synthetic> + <ExpandedItem Condition="tag() == 0">variant0</ExpandedItem> + <ExpandedItem Condition="tag() == 1" Optional="true">variant1</ExpandedItem> + <ExpandedItem Condition="tag() == 2" Optional="true">variant2</ExpandedItem> + <ExpandedItem Condition="tag() == 3" Optional="true">variant3</ExpandedItem> + <ExpandedItem Condition="tag() == 4" Optional="true">variant4</ExpandedItem> + <ExpandedItem Condition="tag() == 5" Optional="true">variant5</ExpandedItem> + <ExpandedItem Condition="tag() == 6" Optional="true">variant6</ExpandedItem> + <ExpandedItem Condition="tag() == 7" Optional="true">variant7</ExpandedItem> + <ExpandedItem Condition="tag() == 8" Optional="true">variant8</ExpandedItem> + <ExpandedItem Condition="tag() == 9" Optional="true">variant9</ExpandedItem> + <ExpandedItem Condition="tag() == 10" Optional="true">variant10</ExpandedItem> + <ExpandedItem Condition="tag() == 11" Optional="true">variant11</ExpandedItem> + <ExpandedItem Condition="tag() == 12" Optional="true">variant12</ExpandedItem> + <ExpandedItem Condition="tag() == 13" Optional="true">variant13</ExpandedItem> + <ExpandedItem Condition="tag() == 14" Optional="true">variant14</ExpandedItem> + <ExpandedItem Condition="tag() == 15" Optional="true">variant15</ExpandedItem> + </Expand> + </Type> + + <!-- Single variant enums. $T1 is the name of the enum, $T2 is the name of the variant --> + <Type Name="enum$<*, *>"> + <DisplayString>{"$T2",sb}</DisplayString> + <Expand> + <Synthetic Name="[variant]"> + <DisplayString>{"$T2",sb}</DisplayString> + </Synthetic> + <ExpandedItem>$T2</ExpandedItem> + </Expand> + </Type> + + <!-- Niche-layout enums. $T1 is the name of the enum, $T2 is the low value of the dataful + variant tag, $T3 is the high value of the dataful variant tag, $T4 is the name of + the dataful variant --> + <Type Name="enum$<*, *, *, *>"> + <Intrinsic Name="tag" Expression="discriminant" /> + <Intrinsic Name="is_dataful" Expression="tag() >= $T2 && tag() <= $T3" /> + <DisplayString Condition="is_dataful()">{"$T4",sb}({dataful_variant})</DisplayString> + <DisplayString Condition="!is_dataful()">{discriminant,en}</DisplayString> + <Expand> + <ExpandedItem Condition="is_dataful()">dataful_variant</ExpandedItem> + <Synthetic Condition="is_dataful()" Name="[variant]"> + <DisplayString>{"$T4",sb}</DisplayString> + </Synthetic> + <Synthetic Condition="!is_dataful()" Name="[variant]"> + <DisplayString>{discriminant,en}</DisplayString> + </Synthetic> + </Expand> + </Type> +</AutoVisualizer> diff --git a/src/etc/natvis/liballoc.natvis b/src/etc/natvis/liballoc.natvis new file mode 100644 index 000000000..912418fa7 --- /dev/null +++ b/src/etc/natvis/liballoc.natvis @@ -0,0 +1,196 @@ +<?xml version="1.0" encoding="utf-8"?> +<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> + <Type Name="alloc::vec::Vec<*>"> + <DisplayString>{{ len={len} }}</DisplayString> + <Expand> + <Item Name="[len]" ExcludeView="simple">len</Item> + <Item Name="[capacity]" ExcludeView="simple">buf.cap</Item> + <ArrayItems> + <Size>len</Size> + <ValuePointer>buf.ptr.pointer.pointer</ValuePointer> + </ArrayItems> + </Expand> + </Type> + <Type Name="alloc::collections::vec_deque::VecDeque<*>"> + <DisplayString>{{ len={tail <= head ? head - tail : buf.cap - tail + head} }}</DisplayString> + <Expand> + <Item Name="[len]" ExcludeView="simple">tail <= head ? head - tail : buf.cap - tail + head</Item> + <Item Name="[capacity]" ExcludeView="simple">buf.cap</Item> + <CustomListItems> + <Variable Name="i" InitialValue="tail" /> + + <Size>tail <= head ? head - tail : buf.cap - tail + head</Size> + <Loop> + <If Condition="i == head"> + <Break/> + </If> + <Item>buf.ptr.pointer.pointer[i]</Item> + <Exec>i = (i + 1 == buf.cap ? 0 : i + 1)</Exec> + </Loop> + </CustomListItems> + </Expand> + </Type> + <Type Name="alloc::collections::linked_list::LinkedList<*>"> + <DisplayString>{{ len={len} }}</DisplayString> + <Expand> + <LinkedListItems> + <Size>len</Size> + <HeadPointer>*(alloc::collections::linked_list::Node<$T1> **)&head</HeadPointer> + <NextPointer>*(alloc::collections::linked_list::Node<$T1> **)&next</NextPointer> + <ValueNode>element</ValueNode> + </LinkedListItems> + </Expand> + </Type> + <Type Name="alloc::string::String"> + <DisplayString>{(char*)vec.buf.ptr.pointer.pointer,[vec.len]s8}</DisplayString> + <StringView>(char*)vec.buf.ptr.pointer.pointer,[vec.len]s8</StringView> + <Expand> + <Item Name="[len]" ExcludeView="simple">vec.len</Item> + <Item Name="[capacity]" ExcludeView="simple">vec.buf.cap</Item> + <Synthetic Name="[chars]"> + <DisplayString>{(char*)vec.buf.ptr.pointer.pointer,[vec.len]s8}</DisplayString> + <Expand> + <ArrayItems> + <Size>vec.len</Size> + <ValuePointer>(char*)vec.buf.ptr.pointer.pointer</ValuePointer> + </ArrayItems> + </Expand> + </Synthetic> + </Expand> + </Type> + + <!-- + The display string for Rc, Arc, etc is optional because the expression cannot be evaluated + if the pointee is unsized (i.e. if `ptr.pointer` is a fat pointer). + + There are also two versions for the reference count fields, one for sized and one for + dyn pointees. + + Rc<[T]> and Arc<[T]> are handled separately altogether so we can actually show + the slice values. + --> + <!-- alloc::rc::Rc<T> --> + <Type Name="alloc::rc::Rc<*>"> + <DisplayString Optional="true">{ptr.pointer->value}</DisplayString> + <Expand> + <!-- thin --> + <ExpandedItem Optional="true">ptr.pointer->value</ExpandedItem> + <Item Name="[Reference count]" Optional="true">ptr.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer->weak</Item> + + <!-- dyn --> + <Item Name="[Reference count]" Optional="true">ptr.pointer.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer.pointer->weak</Item> + </Expand> + </Type> + + <!-- alloc::rc::Rc<[T]> --> + <Type Name="alloc::rc::Rc<slice$<*> >"> + <DisplayString>{{ len={ptr.pointer.length} }}</DisplayString> + <Expand> + <Item Name="[Length]" ExcludeView="simple">ptr.pointer.length</Item> + <Item Name="[Reference count]">ptr.pointer.data_ptr->strong</Item> + <Item Name="[Weak reference count]">ptr.pointer.data_ptr->weak</Item> + <ArrayItems> + <Size>ptr.pointer.length</Size> + <!-- We add +2 to the data_ptr in order to skip the ref count fields in the RcBox --> + <ValuePointer>($T1*)(((size_t*)ptr.pointer.data_ptr) + 2)</ValuePointer> + </ArrayItems> + </Expand> + </Type> + + <!-- alloc::rc::Weak<T> --> + <Type Name="alloc::rc::Weak<*>"> + <DisplayString Optional="true">{ptr.pointer->value}</DisplayString> + <Expand> + <!-- thin --> + <ExpandedItem Optional="true">ptr.pointer->value</ExpandedItem> + <Item Name="[Reference count]" Optional="true">ptr.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer->weak</Item> + + <!-- dyn --> + <Item Name="[Reference count]" Optional="true">ptr.pointer.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer.pointer->weak</Item> + </Expand> + </Type> + + <!-- alloc::rc::Weak<[T]> --> + <Type Name="alloc::rc::Weak<slice$<*> >"> + <DisplayString>{{ len={ptr.pointer.length} }}</DisplayString> + <Expand> + <Item Name="[Length]" ExcludeView="simple">ptr.pointer.length</Item> + <Item Name="[Reference count]">ptr.pointer.data_ptr->strong</Item> + <Item Name="[Weak reference count]">ptr.pointer.data_ptr->weak</Item> + <ArrayItems> + <Size>ptr.pointer.length</Size> + <ValuePointer>($T1*)(((size_t*)ptr.pointer.data_ptr) + 2)</ValuePointer> + </ArrayItems> + </Expand> + </Type> + + <!-- alloc::sync::Arc<T> --> + <Type Name="alloc::sync::Arc<*>"> + <DisplayString Optional="true">{ptr.pointer->data}</DisplayString> + <Expand> + <!-- thin --> + <ExpandedItem Optional="true">ptr.pointer->data</ExpandedItem> + <Item Name="[Reference count]" Optional="true">ptr.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer->weak</Item> + + <!-- dyn --> + <Item Name="[Reference count]" Optional="true">ptr.pointer.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer.pointer->weak</Item> + </Expand> + </Type> + + <!-- alloc::sync::Arc<[T]> --> + <Type Name="alloc::sync::Arc<slice$<*> >"> + <DisplayString>{{ len={ptr.pointer.length} }}</DisplayString> + <Expand> + <Item Name="[Length]" ExcludeView="simple">ptr.pointer.length</Item> + <Item Name="[Reference count]">ptr.pointer.data_ptr->strong</Item> + <Item Name="[Weak reference count]">ptr.pointer.data_ptr->weak</Item> + <ArrayItems> + <Size>ptr.pointer.length</Size> + <ValuePointer>($T1*)(((size_t*)ptr.pointer.data_ptr) + 2)</ValuePointer> + </ArrayItems> + </Expand> + </Type> + + <!-- alloc::sync::Weak<T> --> + <Type Name="alloc::sync::Weak<*>"> + <DisplayString Optional="true">{ptr.pointer->data}</DisplayString> + <Expand> + <!-- thin --> + <ExpandedItem Optional="true">ptr.pointer->data</ExpandedItem> + <Item Name="[Reference count]" Optional="true">ptr.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer->weak</Item> + + <!-- dyn --> + <Item Name="[Reference count]" Optional="true">ptr.pointer.pointer->strong</Item> + <Item Name="[Weak reference count]" Optional="true">ptr.pointer.pointer->weak</Item> + </Expand> + </Type> + + <!-- alloc::sync::Weak<[T]> --> + <Type Name="alloc::sync::Weak<slice$<*> >"> + <DisplayString>{{ len={ptr.pointer.length} }}</DisplayString> + <Expand> + <Item Name="[Length]" ExcludeView="simple">ptr.pointer.length</Item> + <Item Name="[Reference count]">ptr.pointer.data_ptr->strong</Item> + <Item Name="[Weak reference count]">ptr.pointer.data_ptr->weak</Item> + <ArrayItems> + <Size>ptr.pointer.length</Size> + <ValuePointer>($T1*)(((size_t*)ptr.pointer.data_ptr) + 2)</ValuePointer> + </ArrayItems> + </Expand> + </Type> + + <Type Name="alloc::borrow::Cow<*>"> + <DisplayString Condition="RUST$ENUM$DISR == 0x0">Borrowed({__0})</DisplayString> + <DisplayString Condition="RUST$ENUM$DISR == 0x1">Owned({__0})</DisplayString> + <Expand> + <Item Name="[value]" ExcludeView="simple">__0</Item> + </Expand> + </Type> +</AutoVisualizer> diff --git a/src/etc/natvis/libcore.natvis b/src/etc/natvis/libcore.natvis new file mode 100644 index 000000000..a4e8a57e4 --- /dev/null +++ b/src/etc/natvis/libcore.natvis @@ -0,0 +1,163 @@ +<?xml version="1.0" encoding="utf-8"?> +<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> + <Type Name="core::cell::Cell<*>"> + <DisplayString>{value.value}</DisplayString> + <Expand> + <ExpandedItem>value.value</ExpandedItem> + </Expand> + </Type> + <Type Name="core::cell::Ref<*>"> + <DisplayString>{value.pointer}</DisplayString> + <Expand> + <ExpandedItem>value.pointer</ExpandedItem> + </Expand> + </Type> + <Type Name="core::cell::RefMut<*>"> + <DisplayString>{value.pointer}</DisplayString> + <Expand> + <ExpandedItem>value.pointer</ExpandedItem> + </Expand> + </Type> + <Type Name="core::cell::RefCell<*>"> + <DisplayString>{value.value}</DisplayString> + <Expand> + <Item Name="[Borrow state]" Condition="borrow.value.value == 0">"Unborrowed",sb</Item> + <Item Name="[Borrow state]" Condition="borrow.value.value > 0">"Immutably borrowed",sb</Item> + <Item Name="[Borrow state]" Condition="borrow.value.value < 0">"Mutably borrowed",sb</Item> + <ExpandedItem>value.value</ExpandedItem> + </Expand> + </Type> + <Type Name="core::cell::UnsafeCell<*>"> + <DisplayString>{value}</DisplayString> + <Expand> + <ExpandedItem>value</ExpandedItem> + </Expand> + </Type> + + <Type Name="core::mem::manually_drop::ManuallyDrop<*>"> + <DisplayString>{value}</DisplayString> + <Expand> + <ExpandedItem>value</ExpandedItem> + </Expand> + </Type> + + <Type Name="core::num::nonzero::NonZeroI8"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroI16"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroI32"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroI64"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroI128"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroIsize"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroU8"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroU16"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroU32"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroU64"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroU128"> + <DisplayString>{__0}</DisplayString> + </Type> + <Type Name="core::num::nonzero::NonZeroUsize"> + <DisplayString>{__0}</DisplayString> + </Type> + + <Type Name="core::num::wrapping::Wrapping<*>"> + <DisplayString>{__0}</DisplayString> + </Type> + + <Type Name="core::ops::range::Range<*>"> + <DisplayString>({start}..{end})</DisplayString> + </Type> + <Type Name="core::ops::range::RangeFrom<*>"> + <DisplayString>({start}..)</DisplayString> + </Type> + <Type Name="core::ops::range::RangeInclusive<*>"> + <DisplayString>({start}..={end})</DisplayString> + </Type> + <Type Name="core::ops::range::RangeTo<*>"> + <DisplayString>(..{end})</DisplayString> + </Type> + <Type Name="core::ops::range::RangeToInclusive<*>"> + <DisplayString>(..={end})</DisplayString> + </Type> + + <Type Name="core::pin::Pin<*>"> + <DisplayString>Pin({(void*)pointer}: {pointer})</DisplayString> + <Expand> + <ExpandedItem>pointer</ExpandedItem> + </Expand> + </Type> + + <Type Name="core::ptr::non_null::NonNull<*>"> + <DisplayString>NonNull({(void*) pointer}: {pointer})</DisplayString> + <Expand> + <ExpandedItem>pointer</ExpandedItem> + </Expand> + </Type> + + <Type Name="core::ptr::unique::Unique<*>"> + <DisplayString>Unique({(void*)pointer.pointer}: {pointer.pointer})</DisplayString> + <Expand> + <ExpandedItem>pointer</ExpandedItem> + </Expand> + </Type> + + <Type Name="core::sync::atomic::AtomicBool"> + <DisplayString>{(bool)v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicI8"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicI16"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicI32"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicI64"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicIsize"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicU8"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicU16"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicU32"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicU64"> + <DisplayString>{v.value}</DisplayString> + </Type> + <Type Name="core::sync::atomic::AtomicUsize"> + <DisplayString>{v.value}</DisplayString> + </Type> + + <Type Name="core::time::Duration"> + <DisplayString>{secs,d}s {nanos,d}ns</DisplayString> + <Expand> + <Item Name="seconds">secs,d</Item> + <Item Name="nanoseconds">nanos,d</Item> + </Expand> + </Type> +</AutoVisualizer> diff --git a/src/etc/natvis/libstd.natvis b/src/etc/natvis/libstd.natvis new file mode 100644 index 000000000..4371b9953 --- /dev/null +++ b/src/etc/natvis/libstd.natvis @@ -0,0 +1,120 @@ +<?xml version="1.0" encoding="utf-8"?> +<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> + <!-- + std::collection::Hash* container visualizers + + Current std impls: + std::collections::hash::set::HashSet<K, S> is implemented in terms of... + hashbrown::set::HashSet<K, S> is implemented in terms of... + hashbrown::map::HashMap<K, V, S> is implemented in terms of... + hashbrown::raw::RawTable<(K, V)> + + Ideally, we'd teach rustc to scan dependencies/crates for .natvis files so + the bulk of this could live alongside the hashbrown crate implementation, + and std would just forward using e.g. <ExpandedItem>base</ExpandedItem>. + + However, Given that std...Hash*Set* is currently implemented in terms of + hashbrown...Hash*Map*, which would visualize poorly, we want to customize the + look/feel at the std type level *anyways*... + + References: + https://github.com/rust-lang/rust/blob/master/src/libstd/collections/hash/map.rs + https://github.com/rust-lang/rust/blob/master/src/libstd/collections/hash/set.rs + https://github.com/rust-lang/hashbrown/blob/master/src/map.rs + https://github.com/rust-lang/hashbrown/blob/master/src/set.rs + https://github.com/rust-lang/hashbrown/blob/master/src/raw/mod.rs + --> + + <Type Name="std::collections::hash::map::HashMap<*,*,*>"> + <DisplayString>{{ len={base.table.table.items} }}</DisplayString> + <Expand> + <Item Name="[len]">base.table.table.items</Item> + <Item Name="[capacity]">base.table.table.items + base.table.table.growth_left</Item> + <Item Name="[state]">base.hash_builder</Item> + + <CustomListItems> + <Variable Name="i" InitialValue="0" /> + <Variable Name="n" InitialValue="base.table.table.items" /> + <Size>base.table.table.items</Size> + <Loop> + <Break Condition="n == 0" /> + <If Condition="(base.table.table.ctrl.pointer[i] & 0x80) == 0"> + <!-- Bucket is populated --> + <Exec>n--</Exec> + <Item Name="{((tuple$<$T1,$T2>*)base.table.table.ctrl.pointer)[-(i + 1)].__0}">((tuple$<$T1,$T2>*)base.table.table.ctrl.pointer)[-(i + 1)].__1</Item> + </If> + <Exec>i++</Exec> + </Loop> + </CustomListItems> + </Expand> + </Type> + + <Type Name="std::collections::hash::set::HashSet<*,*>"> + <DisplayString>{{ len={base.map.table.table.items} }}</DisplayString> + <Expand> + <Item Name="[len]">base.map.table.table.items</Item> + <Item Name="[capacity]">base.map.table.table.items + base.map.table.table.growth_left</Item> + <Item Name="[state]">base.map.hash_builder</Item> + + <CustomListItems> + <Variable Name="i" InitialValue="0" /> + <Variable Name="n" InitialValue="base.map.table.table.items" /> + <Size>base.map.table.table.items</Size> + <Loop> + <Break Condition="n == 0" /> + <If Condition="(base.map.table.table.ctrl.pointer[i] & 0x80) == 0"> + <!-- Bucket is populated --> + <Exec>n--</Exec> + <Item>(($T1*)base.map.table.table.ctrl.pointer)[-(i + 1)]</Item> + </If> + <Exec>i++</Exec> + </Loop> + </CustomListItems> + </Expand> + </Type> + + <Type Name="std::ffi::c_str::CString"> + <DisplayString>{(char*)inner.data_ptr}</DisplayString> + <Expand> + <Synthetic Name="[chars]"> + <DisplayString>{(char*)inner.data_ptr}</DisplayString> + <Expand> + <ArrayItems> + <Size>inner.length</Size> + <ValuePointer>(char*)inner.data_ptr</ValuePointer> + </ArrayItems> + </Expand> + </Synthetic> + </Expand> + </Type> + + <Type Name="std::ffi::c_str::CStr"> + <DisplayString>{(char*) inner}</DisplayString> + <Expand> + <Synthetic Name="[chars]"> + <DisplayString>{(char*) inner}</DisplayString> + <Expand> + <ArrayItems> + <Size>strlen((char *) inner) + 1</Size> + <ValuePointer>(char*)inner</ValuePointer> + </ArrayItems> + </Expand> + </Synthetic> + </Expand> + </Type> + + <Type Name="std::ffi::os_str::OsString"> + <DisplayString>{(char*)inner.inner.bytes.buf.ptr.pointer.pointer,[inner.inner.bytes.len]}</DisplayString> + <Expand> + <Synthetic Name="[chars]"> + <DisplayString>{(char*)inner.inner.bytes.buf.ptr.pointer.pointer,[inner.inner.bytes.len]}</DisplayString> + <Expand> + <ArrayItems> + <Size>inner.inner.bytes.len</Size> + <ValuePointer>(char*)inner.inner.bytes.buf.ptr.pointer.pointer</ValuePointer> + </ArrayItems> + </Expand> + </Synthetic> + </Expand> + </Type> +</AutoVisualizer> diff --git a/src/etc/pre-push.sh b/src/etc/pre-push.sh new file mode 100755 index 000000000..5f5b48bc1 --- /dev/null +++ b/src/etc/pre-push.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# +# Call `tidy --bless` before git push +# Copy this script to .git/hooks to activate, +# and remove it from .git/hooks to deactivate. +# + +set -Eeuo pipefail + +# https://github.com/rust-lang/rust/issues/77620#issuecomment-705144570 +unset GIT_DIR +ROOT_DIR="$(git rev-parse --show-toplevel)" +COMMAND="$ROOT_DIR/x.py test tidy --bless" + +if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then + COMMAND="python $COMMAND" +elif ! command -v python &> /dev/null; then + COMMAND="python3 $COMMAND" +fi + +echo "Running pre-push script '$COMMAND'" + +cd "$ROOT_DIR" + +$COMMAND diff --git a/src/etc/rust-gdb b/src/etc/rust-gdb new file mode 100755 index 000000000..b950cea79 --- /dev/null +++ b/src/etc/rust-gdb @@ -0,0 +1,24 @@ +#!/bin/sh +# Exit if anything fails +set -e + +# Prefer rustc in the same directory as this script +DIR="$(dirname "$0")" +if [ -x "$DIR/rustc" ]; then + RUSTC="$DIR/rustc" +else + RUSTC="rustc" +fi + +# Find out where the pretty printer Python module is +RUSTC_SYSROOT="$("$RUSTC" --print=sysroot)" +GDB_PYTHON_MODULE_DIRECTORY="$RUSTC_SYSROOT/lib/rustlib/etc" + +# Run GDB with the additional arguments that load the pretty printers +# Set the environment variable `RUST_GDB` to overwrite the call to a +# different/specific command (defaults to `gdb`). +RUST_GDB="${RUST_GDB:-gdb}" +PYTHONPATH="$PYTHONPATH:$GDB_PYTHON_MODULE_DIRECTORY" exec ${RUST_GDB} \ + --directory="$GDB_PYTHON_MODULE_DIRECTORY" \ + -iex "add-auto-load-safe-path $GDB_PYTHON_MODULE_DIRECTORY" \ + "$@" diff --git a/src/etc/rust-gdbgui b/src/etc/rust-gdbgui new file mode 100755 index 000000000..9744913b6 --- /dev/null +++ b/src/etc/rust-gdbgui @@ -0,0 +1,64 @@ +#!/bin/sh + +# Exit if anything fails +set -e + +if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "-help" ] || [ "$1" = "--help" ]; then + echo " +rust-gdbgui +=========== +gdbgui - https://gdbgui.com - is a graphical front-end to GDB +that runs in a browser. This script invokes gdbgui with the Rust +pretty printers loaded. + +Simple usage : rust-gdbgui target/debug/myprog +With arguments: rust-gdbgui 'target/debug/myprog arg1 arg2...' + (note the quotes) + + +Hints +===== +gdbgui won't be able to find the rust 'main' method automatically, so +in its options make sure to disable the 'Add breakpoint to main after +loading executable' setting to avoid a 'File not found: main' warning +on startup. + +Instead, type 'main' into gdbgui's file browser and you should get +auto-completion on the filename. Just pick 'main.rs', add a breakpoint +by clicking in the line number gutter, and type 'r' or hit the Restart +icon to start your program running. +" + exit 0 +fi + +# Prefer rustc in the same directory as this script +DIR="$(dirname "$0")" +if [ -x "$DIR/rustc" ]; then + RUSTC="$DIR/rustc" +else + RUSTC="rustc" +fi + +# Find out where the pretty printer Python module is +RUSTC_SYSROOT="$("$RUSTC" --print=sysroot)" +GDB_PYTHON_MODULE_DIRECTORY="$RUSTC_SYSROOT/lib/rustlib/etc" + +# Set the environment variable `RUST_GDB` to overwrite the call to a +# different/specific command (defaults to `gdb`). +RUST_GDB="${RUST_GDB:-gdb}" + +# Set the environment variable `RUST_GDBGUI` to overwrite the call to a +# different/specific command (defaults to `gdbgui`). +RUST_GDBGUI="${RUST_GDBGUI:-gdbgui}" + +# These arguments get passed through to GDB and make it load the +# Rust pretty printers. +GDB_ARGS="--directory=\"$GDB_PYTHON_MODULE_DIRECTORY\" -iex \"add-auto-load-safe-path $GDB_PYTHON_MODULE_DIRECTORY\"" + +# Finally we execute gdbgui. +PYTHONPATH="$PYTHONPATH:$GDB_PYTHON_MODULE_DIRECTORY" \ + exec ${RUST_GDBGUI} \ + --gdb ${RUST_GDB} \ + --gdb-args "${GDB_ARGS}" \ + "${@}" + diff --git a/src/etc/rust-lldb b/src/etc/rust-lldb new file mode 100755 index 000000000..bce72f1ba --- /dev/null +++ b/src/etc/rust-lldb @@ -0,0 +1,37 @@ +#!/bin/sh + +# Exit if anything fails +set -e + +# Find the host triple so we can find lldb in rustlib. +host=$(rustc -vV | sed -n -e 's/^host: //p') + +# Find out where to look for the pretty printer Python module +RUSTC_SYSROOT=$(rustc --print sysroot) +RUST_LLDB="$RUSTC_SYSROOT/lib/rustlib/$host/bin/lldb" + +lldb=lldb +if [ -f "$RUST_LLDB" ]; then + lldb="$RUST_LLDB" +else + if ! command -v "$lldb" > /dev/null; then + echo "$lldb not found! Please install it." >&2 + exit 1 + else + LLDB_VERSION=$("$lldb" --version | cut -d ' ' -f3) + + if [ "$LLDB_VERSION" = "3.5.0" ]; then + cat << EOF >&2 +*** +WARNING: This version of LLDB has known issues with Rust and cannot display the contents of local variables! +*** +EOF + fi + fi +fi + +script_import="command script import \"$RUSTC_SYSROOT/lib/rustlib/etc/lldb_lookup.py\"" +commands_file="$RUSTC_SYSROOT/lib/rustlib/etc/lldb_commands" + +# Call LLDB with the commands added to the argument list +exec "$lldb" --one-line-before-file "$script_import" --source-before-file "$commands_file" "$@" diff --git a/src/etc/rust-windbg.cmd b/src/etc/rust-windbg.cmd new file mode 100644 index 000000000..2deb2a03a --- /dev/null +++ b/src/etc/rust-windbg.cmd @@ -0,0 +1,8 @@ +@echo off +setlocal + +for /f "delims=" %%i in ('rustc --print=sysroot') do set rustc_sysroot=%%i + +set rust_etc=%rustc_sysroot%\lib\rustlib\etc + +windbg -c ".nvload %rust_etc%\intrinsic.natvis; .nvload %rust_etc%\liballoc.natvis; .nvload %rust_etc%\libcore.natvis;" %* diff --git a/src/etc/rust_types.py b/src/etc/rust_types.py new file mode 100644 index 000000000..bbc945a7d --- /dev/null +++ b/src/etc/rust_types.py @@ -0,0 +1,113 @@ +import re + + +class RustType(object): + OTHER = "Other" + STRUCT = "Struct" + TUPLE = "Tuple" + CSTYLE_VARIANT = "CStyleVariant" + TUPLE_VARIANT = "TupleVariant" + STRUCT_VARIANT = "StructVariant" + ENUM = "Enum" + EMPTY = "Empty" + SINGLETON_ENUM = "SingletonEnum" + REGULAR_ENUM = "RegularEnum" + COMPRESSED_ENUM = "CompressedEnum" + REGULAR_UNION = "RegularUnion" + + STD_STRING = "StdString" + STD_OS_STRING = "StdOsString" + STD_STR = "StdStr" + STD_SLICE = "StdSlice" + STD_VEC = "StdVec" + STD_VEC_DEQUE = "StdVecDeque" + STD_BTREE_SET = "StdBTreeSet" + STD_BTREE_MAP = "StdBTreeMap" + STD_HASH_MAP = "StdHashMap" + STD_HASH_SET = "StdHashSet" + STD_RC = "StdRc" + STD_ARC = "StdArc" + STD_CELL = "StdCell" + STD_REF = "StdRef" + STD_REF_MUT = "StdRefMut" + STD_REF_CELL = "StdRefCell" + + +STD_STRING_REGEX = re.compile(r"^(alloc::(\w+::)+)String$") +STD_STR_REGEX = re.compile(r"^&(mut )?str$") +STD_SLICE_REGEX = re.compile(r"^&(mut )?\[.+\]$") +STD_OS_STRING_REGEX = re.compile(r"^(std::ffi::(\w+::)+)OsString$") +STD_VEC_REGEX = re.compile(r"^(alloc::(\w+::)+)Vec<.+>$") +STD_VEC_DEQUE_REGEX = re.compile(r"^(alloc::(\w+::)+)VecDeque<.+>$") +STD_BTREE_SET_REGEX = re.compile(r"^(alloc::(\w+::)+)BTreeSet<.+>$") +STD_BTREE_MAP_REGEX = re.compile(r"^(alloc::(\w+::)+)BTreeMap<.+>$") +STD_HASH_MAP_REGEX = re.compile(r"^(std::collections::(\w+::)+)HashMap<.+>$") +STD_HASH_SET_REGEX = re.compile(r"^(std::collections::(\w+::)+)HashSet<.+>$") +STD_RC_REGEX = re.compile(r"^(alloc::(\w+::)+)Rc<.+>$") +STD_ARC_REGEX = re.compile(r"^(alloc::(\w+::)+)Arc<.+>$") +STD_CELL_REGEX = re.compile(r"^(core::(\w+::)+)Cell<.+>$") +STD_REF_REGEX = re.compile(r"^(core::(\w+::)+)Ref<.+>$") +STD_REF_MUT_REGEX = re.compile(r"^(core::(\w+::)+)RefMut<.+>$") +STD_REF_CELL_REGEX = re.compile(r"^(core::(\w+::)+)RefCell<.+>$") + +TUPLE_ITEM_REGEX = re.compile(r"__\d+$") + +ENCODED_ENUM_PREFIX = "RUST$ENCODED$ENUM$" +ENUM_DISR_FIELD_NAME = "<<variant>>" + +STD_TYPE_TO_REGEX = { + RustType.STD_STRING: STD_STRING_REGEX, + RustType.STD_OS_STRING: STD_OS_STRING_REGEX, + RustType.STD_STR: STD_STR_REGEX, + RustType.STD_SLICE: STD_SLICE_REGEX, + RustType.STD_VEC: STD_VEC_REGEX, + RustType.STD_VEC_DEQUE: STD_VEC_DEQUE_REGEX, + RustType.STD_HASH_MAP: STD_HASH_MAP_REGEX, + RustType.STD_HASH_SET: STD_HASH_SET_REGEX, + RustType.STD_BTREE_SET: STD_BTREE_SET_REGEX, + RustType.STD_BTREE_MAP: STD_BTREE_MAP_REGEX, + RustType.STD_RC: STD_RC_REGEX, + RustType.STD_ARC: STD_ARC_REGEX, + RustType.STD_REF: STD_REF_REGEX, + RustType.STD_REF_MUT: STD_REF_MUT_REGEX, + RustType.STD_REF_CELL: STD_REF_CELL_REGEX, + RustType.STD_CELL: STD_CELL_REGEX, +} + +def is_tuple_fields(fields): + # type: (list) -> bool + return all(TUPLE_ITEM_REGEX.match(str(field.name)) for field in fields) + + +def classify_struct(name, fields): + if len(fields) == 0: + return RustType.EMPTY + + for ty, regex in STD_TYPE_TO_REGEX.items(): + if regex.match(name): + return ty + + if fields[0].name == ENUM_DISR_FIELD_NAME: + return RustType.ENUM + + if is_tuple_fields(fields): + return RustType.TUPLE + + return RustType.STRUCT + + +def classify_union(fields): + if len(fields) == 0: + return RustType.EMPTY + + first_variant_name = fields[0].name + if first_variant_name is None: + if len(fields) == 1: + return RustType.SINGLETON_ENUM + else: + return RustType.REGULAR_ENUM + elif first_variant_name.startswith(ENCODED_ENUM_PREFIX): + assert len(fields) == 1 + return RustType.COMPRESSED_ENUM + else: + return RustType.REGULAR_UNION diff --git a/src/etc/test-float-parse/Cargo.toml b/src/etc/test-float-parse/Cargo.toml new file mode 100644 index 000000000..7ee19a0b6 --- /dev/null +++ b/src/etc/test-float-parse/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "test-float-parse" +version = "0.1.0" +edition = "2021" +publish = false + +[workspace] + +[dependencies] +rand = "0.4" + +[lib] +name = "test_float_parse" diff --git a/src/etc/test-float-parse/runtests.py b/src/etc/test-float-parse/runtests.py new file mode 100644 index 000000000..cf7279534 --- /dev/null +++ b/src/etc/test-float-parse/runtests.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 + +""" +Testing dec2flt +=============== +These are *really* extensive tests. Expect them to run for hours. Due to the +nature of the problem (the input is a string of arbitrary length), exhaustive +testing is not really possible. Instead, there are exhaustive tests for some +classes of inputs for which that is feasible and a bunch of deterministic and +random non-exhaustive tests for covering everything else. + +The actual tests (generating decimal strings and feeding them to dec2flt) is +performed by a set of stand-along rust programs. This script compiles, runs, +and supervises them. The programs report the strings they generate and the +floating point numbers they converted those strings to, and this script +checks that the results are correct. + +You can run specific tests rather than all of them by giving their names +(without .rs extension) as command line parameters. + +Verification +------------ +The tricky part is not generating those inputs but verifying the outputs. +Comparing with the result of Python's float() does not cut it because +(and this is apparently undocumented) although Python includes a version of +Martin Gay's code including the decimal-to-float part, it doesn't actually use +it for float() (only for round()) instead relying on the system scanf() which +is not necessarily completely accurate. + +Instead, we take the input and compute the true value with bignum arithmetic +(as a fraction, using the ``fractions`` module). + +Given an input string and the corresponding float computed via Rust, simply +decode the float into f * 2^k (for integers f, k) and the ULP. +We can now easily compute the error and check if it is within 0.5 ULP as it +should be. Zero and infinites are handled similarly: + +- If the approximation is 0.0, the exact value should be *less or equal* + half the smallest denormal float: the smallest denormal floating point + number has an odd mantissa (00...001) and thus half of that is rounded + to 00...00, i.e., zero. +- If the approximation is Inf, the exact value should be *greater or equal* + to the largest finite float + 0.5 ULP: the largest finite float has an odd + mantissa (11...11), so that plus half an ULP is rounded up to the nearest + even number, which overflows. + +Implementation details +---------------------- +This directory contains a set of single-file Rust programs that perform +tests with a particular class of inputs. Each is compiled and run without +parameters, outputs (f64, f32, decimal) pairs to verify externally, and +in any case either exits gracefully or with a panic. + +If a test binary writes *anything at all* to stderr or exits with an +exit code that's not 0, the test fails. +The output on stdout is treated as (f64, f32, decimal) record, encoded thusly: + +- First, the bits of the f64 encoded as an ASCII hex string. +- Second, the bits of the f32 encoded as an ASCII hex string. +- Then the corresponding string input, in ASCII +- The record is terminated with a newline. + +Incomplete records are an error. Not-a-Number bit patterns are invalid too. + +The tests run serially but the validation for a single test is parallelized +with ``multiprocessing``. Each test is launched as a subprocess. +One thread supervises it: Accepts and enqueues records to validate, observe +stderr, and waits for the process to exit. A set of worker processes perform +the validation work for the outputs enqueued there. Another thread listens +for progress updates from the workers. + +Known issues +------------ +Some errors (e.g., NaN outputs) aren't handled very gracefully. +Also, if there is an exception or the process is interrupted (at least on +Windows) the worker processes are leaked and stick around forever. +They're only a few megabytes each, but still, this script should not be run +if you aren't prepared to manually kill a lot of orphaned processes. +""" +from __future__ import print_function +import sys +import os.path +import time +import struct +from fractions import Fraction +from collections import namedtuple +from subprocess import Popen, check_call, PIPE +from glob import glob +import multiprocessing +import threading +import ctypes +import binascii + +try: # Python 3 + import queue as Queue +except ImportError: # Python 2 + import Queue + +NUM_WORKERS = 2 +UPDATE_EVERY_N = 50000 +INF = namedtuple('INF', '')() +NEG_INF = namedtuple('NEG_INF', '')() +ZERO = namedtuple('ZERO', '')() +MAILBOX = None # The queue for reporting errors to the main process. +STDOUT_LOCK = threading.Lock() +test_name = None +child_processes = [] +exit_status = 0 + +def msg(*args): + with STDOUT_LOCK: + print("[" + test_name + "]", *args) + sys.stdout.flush() + + +def write_errors(): + global exit_status + f = open("errors.txt", 'w') + have_seen_error = False + while True: + args = MAILBOX.get() + if args is None: + f.close() + break + print(*args, file=f) + f.flush() + if not have_seen_error: + have_seen_error = True + msg("Something is broken:", *args) + msg("Future errors logged to errors.txt") + exit_status = 101 + + +def cargo(): + print("compiling tests") + sys.stdout.flush() + check_call(['cargo', 'build', '--release']) + + +def run(test): + global test_name + test_name = test + + t0 = time.perf_counter() + msg("setting up supervisor") + command = ['cargo', 'run', '--bin', test, '--release'] + proc = Popen(command, bufsize=1<<20 , stdin=PIPE, stdout=PIPE, stderr=PIPE) + done = multiprocessing.Value(ctypes.c_bool) + queue = multiprocessing.Queue(maxsize=5)#(maxsize=1024) + workers = [] + for n in range(NUM_WORKERS): + worker = multiprocessing.Process(name='Worker-' + str(n + 1), + target=init_worker, + args=[test, MAILBOX, queue, done]) + workers.append(worker) + child_processes.append(worker) + for worker in workers: + worker.start() + msg("running test") + interact(proc, queue) + with done.get_lock(): + done.value = True + for worker in workers: + worker.join() + msg("python is done") + assert queue.empty(), "did not validate everything" + dt = time.perf_counter() - t0 + msg("took", round(dt, 3), "seconds") + + +def interact(proc, queue): + n = 0 + while proc.poll() is None: + line = proc.stdout.readline() + if not line: + continue + assert line.endswith(b'\n'), "incomplete line: " + repr(line) + queue.put(line) + n += 1 + if n % UPDATE_EVERY_N == 0: + msg("got", str(n // 1000) + "k", "records") + msg("rust is done. exit code:", proc.returncode) + rest, stderr = proc.communicate() + if stderr: + msg("rust stderr output:", stderr) + for line in rest.split(b'\n'): + if not line: + continue + queue.put(line) + + +def main(): + global MAILBOX + files = glob('src/bin/*.rs') + basenames = [os.path.basename(i) for i in files] + all_tests = [os.path.splitext(f)[0] for f in basenames if not f.startswith('_')] + args = sys.argv[1:] + if args: + tests = [test for test in all_tests if test in args] + else: + tests = all_tests + if not tests: + print("Error: No tests to run") + sys.exit(1) + # Compile first for quicker feedback + cargo() + # Set up mailbox once for all tests + MAILBOX = multiprocessing.Queue() + mailman = threading.Thread(target=write_errors) + mailman.daemon = True + mailman.start() + for test in tests: + run(test) + MAILBOX.put(None) + mailman.join() + + +# ---- Worker thread code ---- + + +POW2 = { e: Fraction(2) ** e for e in range(-1100, 1100) } +HALF_ULP = { e: (Fraction(2) ** e)/2 for e in range(-1100, 1100) } +DONE_FLAG = None + + +def send_error_to_supervisor(*args): + MAILBOX.put(args) + + +def init_worker(test, mailbox, queue, done): + global test_name, MAILBOX, DONE_FLAG + test_name = test + MAILBOX = mailbox + DONE_FLAG = done + do_work(queue) + + +def is_done(): + with DONE_FLAG.get_lock(): + return DONE_FLAG.value + + +def do_work(queue): + while True: + try: + line = queue.get(timeout=0.01) + except Queue.Empty: + if queue.empty() and is_done(): + return + else: + continue + bin64, bin32, text = line.rstrip().split() + validate(bin64, bin32, text.decode('utf-8')) + + +def decode_binary64(x): + """ + Turn a IEEE 754 binary64 into (mantissa, exponent), except 0.0 and + infinity (positive and negative), which return ZERO, INF, and NEG_INF + respectively. + """ + x = binascii.unhexlify(x) + assert len(x) == 8, repr(x) + [bits] = struct.unpack(b'>Q', x) + if bits == 0: + return ZERO + exponent = (bits >> 52) & 0x7FF + negative = bits >> 63 + low_bits = bits & 0xFFFFFFFFFFFFF + if exponent == 0: + mantissa = low_bits + exponent += 1 + if mantissa == 0: + return ZERO + elif exponent == 0x7FF: + assert low_bits == 0, "NaN" + if negative: + return NEG_INF + else: + return INF + else: + mantissa = low_bits | (1 << 52) + exponent -= 1023 + 52 + if negative: + mantissa = -mantissa + return (mantissa, exponent) + + +def decode_binary32(x): + """ + Turn a IEEE 754 binary32 into (mantissa, exponent), except 0.0 and + infinity (positive and negative), which return ZERO, INF, and NEG_INF + respectively. + """ + x = binascii.unhexlify(x) + assert len(x) == 4, repr(x) + [bits] = struct.unpack(b'>I', x) + if bits == 0: + return ZERO + exponent = (bits >> 23) & 0xFF + negative = bits >> 31 + low_bits = bits & 0x7FFFFF + if exponent == 0: + mantissa = low_bits + exponent += 1 + if mantissa == 0: + return ZERO + elif exponent == 0xFF: + if negative: + return NEG_INF + else: + return INF + else: + mantissa = low_bits | (1 << 23) + exponent -= 127 + 23 + if negative: + mantissa = -mantissa + return (mantissa, exponent) + + +MIN_SUBNORMAL_DOUBLE = Fraction(2) ** -1074 +MIN_SUBNORMAL_SINGLE = Fraction(2) ** -149 # XXX unsure +MAX_DOUBLE = (2 - Fraction(2) ** -52) * (2 ** 1023) +MAX_SINGLE = (2 - Fraction(2) ** -23) * (2 ** 127) +MAX_ULP_DOUBLE = 1023 - 52 +MAX_ULP_SINGLE = 127 - 23 +DOUBLE_ZERO_CUTOFF = MIN_SUBNORMAL_DOUBLE / 2 +DOUBLE_INF_CUTOFF = MAX_DOUBLE + 2 ** (MAX_ULP_DOUBLE - 1) +SINGLE_ZERO_CUTOFF = MIN_SUBNORMAL_SINGLE / 2 +SINGLE_INF_CUTOFF = MAX_SINGLE + 2 ** (MAX_ULP_SINGLE - 1) + +def validate(bin64, bin32, text): + try: + double = decode_binary64(bin64) + except AssertionError: + print(bin64, bin32, text) + raise + single = decode_binary32(bin32) + real = Fraction(text) + + if double is ZERO: + if real > DOUBLE_ZERO_CUTOFF: + record_special_error(text, "f64 zero") + elif double is INF: + if real < DOUBLE_INF_CUTOFF: + record_special_error(text, "f64 inf") + elif double is NEG_INF: + if -real < DOUBLE_INF_CUTOFF: + record_special_error(text, "f64 -inf") + elif len(double) == 2: + sig, k = double + validate_normal(text, real, sig, k, "f64") + else: + assert 0, "didn't handle binary64" + if single is ZERO: + if real > SINGLE_ZERO_CUTOFF: + record_special_error(text, "f32 zero") + elif single is INF: + if real < SINGLE_INF_CUTOFF: + record_special_error(text, "f32 inf") + elif single is NEG_INF: + if -real < SINGLE_INF_CUTOFF: + record_special_error(text, "f32 -inf") + elif len(single) == 2: + sig, k = single + validate_normal(text, real, sig, k, "f32") + else: + assert 0, "didn't handle binary32" + +def record_special_error(text, descr): + send_error_to_supervisor(text.strip(), "wrongly rounded to", descr) + + +def validate_normal(text, real, sig, k, kind): + approx = sig * POW2[k] + error = abs(approx - real) + if error > HALF_ULP[k]: + record_normal_error(text, error, k, kind) + + +def record_normal_error(text, error, k, kind): + one_ulp = HALF_ULP[k + 1] + assert one_ulp == 2 * HALF_ULP[k] + relative_error = error / one_ulp + text = text.strip() + try: + err_repr = float(relative_error) + except ValueError: + err_repr = str(err_repr).replace('/', ' / ') + send_error_to_supervisor(err_repr, "ULP error on", text, "(" + kind + ")") + + +if __name__ == '__main__': + main() diff --git a/src/etc/test-float-parse/src/bin/few-ones.rs b/src/etc/test-float-parse/src/bin/few-ones.rs new file mode 100644 index 000000000..6bb406a59 --- /dev/null +++ b/src/etc/test-float-parse/src/bin/few-ones.rs @@ -0,0 +1,15 @@ +use test_float_parse::validate; + +fn main() { + let mut pow = vec![]; + for i in 0..63 { + pow.push(1u64 << i); + } + for a in &pow { + for b in &pow { + for c in &pow { + validate(&(a | b | c).to_string()); + } + } + } +} diff --git a/src/etc/test-float-parse/src/bin/huge-pow10.rs b/src/etc/test-float-parse/src/bin/huge-pow10.rs new file mode 100644 index 000000000..722a24ffc --- /dev/null +++ b/src/etc/test-float-parse/src/bin/huge-pow10.rs @@ -0,0 +1,9 @@ +use test_float_parse::validate; + +fn main() { + for e in 300..310 { + for i in 0..100000 { + validate(&format!("{}e{}", i, e)); + } + } +} diff --git a/src/etc/test-float-parse/src/bin/long-fractions.rs b/src/etc/test-float-parse/src/bin/long-fractions.rs new file mode 100644 index 000000000..c715bc1ac --- /dev/null +++ b/src/etc/test-float-parse/src/bin/long-fractions.rs @@ -0,0 +1,15 @@ +use std::char; +use test_float_parse::validate; + +fn main() { + for n in 0..10 { + let digit = char::from_digit(n, 10).unwrap(); + let mut s = "0.".to_string(); + for _ in 0..400 { + s.push(digit); + if s.parse::<f64>().is_ok() { + validate(&s); + } + } + } +} diff --git a/src/etc/test-float-parse/src/bin/many-digits.rs b/src/etc/test-float-parse/src/bin/many-digits.rs new file mode 100644 index 000000000..ba166fd56 --- /dev/null +++ b/src/etc/test-float-parse/src/bin/many-digits.rs @@ -0,0 +1,25 @@ +extern crate rand; + +use rand::distributions::{Range, Sample}; +use rand::{IsaacRng, Rng, SeedableRng}; +use std::char; +use test_float_parse::{validate, SEED}; + +fn main() { + let mut rnd = IsaacRng::from_seed(&SEED); + let mut range = Range::new(0, 10); + for _ in 0..5_000_000u64 { + let num_digits = rnd.gen_range(100, 400); + let digits = gen_digits(num_digits, &mut range, &mut rnd); + validate(&digits); + } +} + +fn gen_digits<R: Rng>(n: u32, range: &mut Range<u32>, rnd: &mut R) -> String { + let mut s = String::new(); + for _ in 0..n { + let digit = char::from_digit(range.sample(rnd), 10).unwrap(); + s.push(digit); + } + s +} diff --git a/src/etc/test-float-parse/src/bin/rand-f64.rs b/src/etc/test-float-parse/src/bin/rand-f64.rs new file mode 100644 index 000000000..6991e8be1 --- /dev/null +++ b/src/etc/test-float-parse/src/bin/rand-f64.rs @@ -0,0 +1,18 @@ +extern crate rand; + +use rand::{IsaacRng, Rng, SeedableRng}; +use std::mem::transmute; +use test_float_parse::{validate, SEED}; + +fn main() { + let mut rnd = IsaacRng::from_seed(&SEED); + let mut i = 0; + while i < 10_000_000 { + let bits = rnd.next_u64(); + let x: f64 = unsafe { transmute(bits) }; + if x.is_finite() { + validate(&format!("{:e}", x)); + i += 1; + } + } +} diff --git a/src/etc/test-float-parse/src/bin/short-decimals.rs b/src/etc/test-float-parse/src/bin/short-decimals.rs new file mode 100644 index 000000000..49084eb35 --- /dev/null +++ b/src/etc/test-float-parse/src/bin/short-decimals.rs @@ -0,0 +1,17 @@ +use test_float_parse::validate; + +fn main() { + // Skip e = 0 because small-u32 already does those. + for e in 1..301 { + for i in 0..10000 { + // If it ends in zeros, the parser will strip those (and adjust the exponent), + // which almost always (except for exponents near +/- 300) result in an input + // equivalent to something we already generate in a different way. + if i % 10 == 0 { + continue; + } + validate(&format!("{}e{}", i, e)); + validate(&format!("{}e-{}", i, e)); + } + } +} diff --git a/src/etc/test-float-parse/src/bin/subnorm.rs b/src/etc/test-float-parse/src/bin/subnorm.rs new file mode 100644 index 000000000..ac88747ea --- /dev/null +++ b/src/etc/test-float-parse/src/bin/subnorm.rs @@ -0,0 +1,11 @@ +use std::mem::transmute; +use test_float_parse::validate; + +fn main() { + for bits in 0u32..(1 << 21) { + let single: f32 = unsafe { transmute(bits) }; + validate(&format!("{:e}", single)); + let double: f64 = unsafe { transmute(bits as u64) }; + validate(&format!("{:e}", double)); + } +} diff --git a/src/etc/test-float-parse/src/bin/tiny-pow10.rs b/src/etc/test-float-parse/src/bin/tiny-pow10.rs new file mode 100644 index 000000000..fb6ba1663 --- /dev/null +++ b/src/etc/test-float-parse/src/bin/tiny-pow10.rs @@ -0,0 +1,9 @@ +use test_float_parse::validate; + +fn main() { + for e in 301..327 { + for i in 0..100000 { + validate(&format!("{}e-{}", i, e)); + } + } +} diff --git a/src/etc/test-float-parse/src/bin/u32-small.rs b/src/etc/test-float-parse/src/bin/u32-small.rs new file mode 100644 index 000000000..5ec9d1eea --- /dev/null +++ b/src/etc/test-float-parse/src/bin/u32-small.rs @@ -0,0 +1,7 @@ +use test_float_parse::validate; + +fn main() { + for i in 0..(1 << 19) { + validate(&i.to_string()); + } +} diff --git a/src/etc/test-float-parse/src/bin/u64-pow2.rs b/src/etc/test-float-parse/src/bin/u64-pow2.rs new file mode 100644 index 000000000..984e49200 --- /dev/null +++ b/src/etc/test-float-parse/src/bin/u64-pow2.rs @@ -0,0 +1,15 @@ +use test_float_parse::validate; + +fn main() { + for exp in 19..64 { + let power: u64 = 1 << exp; + validate(&power.to_string()); + for offset in 1..123 { + validate(&(power + offset).to_string()); + validate(&(power - offset).to_string()); + } + } + for offset in 0..123 { + validate(&(u64::MAX - offset).to_string()); + } +} diff --git a/src/etc/test-float-parse/src/lib.rs b/src/etc/test-float-parse/src/lib.rs new file mode 100644 index 000000000..9cbad5486 --- /dev/null +++ b/src/etc/test-float-parse/src/lib.rs @@ -0,0 +1,16 @@ +use std::io; +use std::io::prelude::*; +use std::mem::transmute; + +// Nothing up my sleeve: Just (PI - 3) in base 16. +#[allow(dead_code)] +pub const SEED: [u32; 3] = [0x243f_6a88, 0x85a3_08d3, 0x1319_8a2e]; + +pub fn validate(text: &str) { + let mut out = io::stdout(); + let x: f64 = text.parse().unwrap(); + let f64_bytes: u64 = unsafe { transmute(x) }; + let x: f32 = text.parse().unwrap(); + let f32_bytes: u32 = unsafe { transmute(x) }; + writeln!(&mut out, "{:016x} {:08x} {}", f64_bytes, f32_bytes, text).unwrap(); +} diff --git a/src/etc/third-party/COPYING.RUNTIME b/src/etc/third-party/COPYING.RUNTIME new file mode 100644 index 000000000..e86f7fb58 --- /dev/null +++ b/src/etc/third-party/COPYING.RUNTIME @@ -0,0 +1,72 @@ +GCC RUNTIME LIBRARY EXCEPTION + +Version 3.1, 31 March 2009 + +Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/> + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +This GCC Runtime Library Exception ("Exception") is an additional +permission under section 7 of the GNU General Public License, version +3 ("GPLv3"). It applies to a given file (the "Runtime Library") that +bears a notice placed by the copyright holder of the file stating that +the file is governed by GPLv3 along with this Exception. + +When you use GCC to compile a program, GCC may combine portions of +certain GCC header files and runtime libraries with the compiled +program. The purpose of this Exception is to allow compilation of +non-GPL (including proprietary) programs to use, in this way, the +header files and runtime libraries covered by this Exception. + +0. Definitions. + +A file is an "Independent Module" if it either requires the Runtime +Library for execution after a Compilation Process, or makes use of an +interface provided by the Runtime Library, but is not otherwise based +on the Runtime Library. + +"GCC" means a version of the GNU Compiler Collection, with or without +modifications, governed by version 3 (or a specified later version) of +the GNU General Public License (GPL) with the option of using any +subsequent versions published by the FSF. + +"GPL-compatible Software" is software whose conditions of propagation, +modification and use would permit combination with GCC in accord with +the license of GCC. + +"Target Code" refers to output from any compiler for a real or virtual +target processor architecture, in executable form or suitable for +input to an assembler, loader, linker and/or execution +phase. Notwithstanding that, Target Code does not include data in any +format that is used as a compiler intermediate representation, or used +for producing a compiler intermediate representation. + +The "Compilation Process" transforms code entirely represented in +non-intermediate languages designed for human-written code, and/or in +Java Virtual Machine byte code, into Target Code. Thus, for example, +use of source code generators and preprocessors need not be considered +part of the Compilation Process, since the Compilation Process can be +understood as starting with the output of the generators or +preprocessors. + +A Compilation Process is "Eligible" if it is done using GCC, alone or +with other GPL-compatible software, or if it is done without using any +work based on GCC. For example, using non-GPL-compatible Software to +optimize any GCC intermediate representations would not qualify as an +Eligible Compilation Process. + +1. Grant of Additional Permission. + +You have permission to propagate a work of Target Code formed by +combining the Runtime Library with Independent Modules, even if such +propagation would otherwise violate the terms of GPLv3, provided that +all Target Code was generated by Eligible Compilation Processes. You +may then convey such a combination under terms of your choice, +consistent with the licensing of the Independent Modules. + +2. No Weakening of GCC Copyleft. + +The availability of this Exception does not imply any general +presumption that third-party software is unaffected by the copyleft +requirements of the license of GCC. diff --git a/src/etc/third-party/COPYING3 b/src/etc/third-party/COPYING3 new file mode 100644 index 000000000..94a9ed024 --- /dev/null +++ b/src/etc/third-party/COPYING3 @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/src/etc/third-party/README.txt b/src/etc/third-party/README.txt new file mode 100644 index 000000000..2544bfa2d --- /dev/null +++ b/src/etc/third-party/README.txt @@ -0,0 +1,5 @@ +Certain binaries in this distribution do not originate from the Rust project, but are distributed with it in its binary form. These binaries, including gcc and other parts of the GNU compiler toolchain, are licensed either under the terms of the GNU General Public License, or the GNU General Public License with the GCC Runtime Library Exception, as published by the Free Software Foundation, either version 3, or (at your option) any later version. See the files COPYING3 and COPYING.RUNTIME respectively. + +You can obtain a copy of the source of these libraries from the MinGW-w64 project[1]. + +[1]: http://mingw-w64.sourceforge.net/ diff --git a/src/etc/wasm32-shim.js b/src/etc/wasm32-shim.js new file mode 100644 index 000000000..262a53eab --- /dev/null +++ b/src/etc/wasm32-shim.js @@ -0,0 +1,24 @@ +// This is a small "shim" program which is used when wasm32 unit tests are run +// in this repository. This program is intended to be run in node.js and will +// load a wasm module into memory, instantiate it with a set of imports, and +// then run it. +// +// There's a bunch of helper functions defined here in `imports.env`, but note +// that most of them aren't actually needed to execute most programs. Many of +// these are just intended for completeness or debugging. Hopefully over time +// nothing here is needed for completeness. + +const fs = require('fs'); +const process = require('process'); +const buffer = fs.readFileSync(process.argv[2]); + +Error.stackTraceLimit = 20; + +let m = new WebAssembly.Module(buffer); +let instance = new WebAssembly.Instance(m, {}); +try { + instance.exports.main(); +} catch (e) { + console.error(e); + process.exit(101); +} |